/// <summary>
/// 操作 Csv 文件的辅助类
/// </summary>
/// <remarks>
/// 创建:宋飞 2013-3-18
/// </remarks>
public class CsvHelper
{
/// <summary>
/// 把 Csv 文件转化为数据表
/// </summary>
/// <param name="file">csv 文件</param>
/// <returns>数据表</returns>
public static DataTable ToDataTable(string file)
{
DataTable dt = new DataTable();
if (!File.Exists(file))
throw new FileNotFoundException("要读取的 csv 文件不存在,请检测路径 " + file + " 是否正确!");
string[] arr = File.ReadLines(file,Encoding.Default).ToArray();
if (arr.Length > 0)
{
//读取列
string[] head = arr[0].Replace("\"", "").Split(',');
for (int i = 0; i < head.Length; i++)
{
DataColumn column = new DataColumn(head[i].Trim());
dt.Columns.Add(column);
}
//读取行
for (int i = 1; i < arr.Length; i++)
{
DataRow row = dt.NewRow();
string[] content = arr[i].Replace("\"", "").Split(',');
for (int j = 0; j < content.Length; j++)
row[j] = content[j];
dt.Rows.Add(row);
}
}
else
{
throw new Exception("文件没有数据!");
}
return dt;
}
}