C# 读取 CSV 文件数据到 DataTable。
public static DataTable ReadCSVtoDataTable(string fileName)
{
DataTable dt = new DataTable();
Regex regex = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
using (StreamReader sr = new StreamReader(fileName))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (sr.Peek() > 0)
{
string[] rows = regex.Split(sr.ReadLine());
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
dt.Rows.Add(dr);
}
}
return dt;
}