开发者

Import csv into a gridview using asp.net

开发者 https://www.devze.com 2023-03-21 17:44 出处:网络
In my asp.net app there are two options to import a CSV file into a gridview. One is StreamReader like this:

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

精彩评论

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

关注公众号