简体   繁体   English

使用 asp.net 将 csv 导入 gridview

[英]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.在我的 asp.net 应用程序中,有两个选项可以将 CSV 文件导入 gridview。

One is StreamReader like this:一个是这样的StreamReader

string rowValue;
string[] cellValue;

System.IO.StreamReader streamReader = new StreamReader(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:另一种是使用 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 :-使用StreamReader :-

for example, my data in csv file is like this.例如,我在 csv 文件中的数据是这样的。

Copy this below data in to notepad and save as it "test.csv" and try将以下数据复制到记事本并保存为“test.csv”并尝试

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

in first row string array you will get like this {1,user1,India}在第一行字符串数组中你会得到这样的{1,user1,India}

But, problem with second is {2,user2,"Chennai,India"}但是,第二个问题是{2,user2,"Chennai,India"}

using OleDb :-使用OleDb :-

I feel, it is best to use OleDb.我觉得,最好用OleDb。 Because, we no need to worry about string manipulation.因为,我们无需担心字符串操作。 And we access the data using SQL WHERE conditions.我们使用 SQL WHERE 条件访问数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM