C# .NET CSV 转 DataTable

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;
}
—— 完 ——
相关推荐
评论

立 为 非 似

中 谁 昨 此

宵 风 夜 星

。 露 , 辰

文章点击榜

细 无 轻 自

如 边 似 在

愁 丝 梦 飞

。 雨 , 花