开发者

Import csv into a gridview using asp.net

In my asp.net app there are two options to import a CSV file into a gridview.

One is StreamReader like this:

string rowValue;
string[] cellValue;

System.IO.StreamReader streamReader = new StreamReade开发者_Python百科r(txtPath.Text);

// Reading header
rowValue = streamReader.ReadLine();
cellValue = rowValue.Split(',');                

for (int i = 0; i <= cellValue.Count() - 1; i++)
{
    DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();

    column.Name = cellValue[i];
    column.HeaderText = cellValue[i];

    dataGridView1.Columns.Add(column);
}

// Reading content
while (streamReader.Peek() != -1)
{
     rowValue = streamReader.ReadLine();
     cellValue = rowValue.Split(',');

     dataGridView1.Rows.Add(cellValue);
}

streamReader.Close();

The other is using OleDb:

string cmdString = string.Format("SELECT * FROM {0}", System.IO.Path.GetFileName(target + "\\" + FileUpload1.FileName));

OleDbDataAdapter dataAdapter = new OleDbDataAdapter(cmdString, connString);

DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);

GridView1.DataSource = dataSet.Tables[0];
GridView1.DataBind();

What's the difference between these two? Is there an advantage to using one over the other?


using StreamReader :-

for example, my data in csv file is like this.

Copy this below data in to notepad and save as it "test.csv" and try

id,name,address
1,user1,India
2,user2,"Chennai,India"

in first row string array you will get like this {1,user1,India}

But, problem with second is {2,user2,"Chennai,India"}

using OleDb:-

I feel, it is best to use OleDb. Because, we no need to worry about string manipulation. And we access the data using SQL WHERE conditions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜