/// <summary>
/// 將CSV內容字串轉成DataTable(全部欄位都視為string,有需要請自行轉換), 不支援""包夾格式
/// </summary>
/// <param name="csvContent">整個CSV的內容</param>
/// <param name="firstRowAsHeader">第一列是否為欄位名稱,若無則以C1, C2自動命名</param>
/// <returns></returns>
public static DataTable ConvertCSVtoDataTable(string csvContent,
bool firstRowAsHeader)
{ DataTable t = new DataTable();
using (StringReader sr = new StringReader(csvContent))
{ string line = null;
bool colCreated = false;
while ((line = sr.ReadLine()) != null)
{ string[] p = line.Split(','); if (!colCreated)
{ int idx = 1;
foreach (string s in p)
{ try
{ t.Columns.Add(
//第一欄是否有欄位名稱? 無則用C1, C2自動編號
firstRowAsHeader ? s : "C" + idx.ToString(),
typeof(string)
);
}
catch (Exception e1)
{ throw new ApplicationException(
"新增欄位失敗! 欄位名稱=" + s + "\n" + e1.ToString());
}
idx++;
}
colCreated = true;
//首欄若為欄名,則不當資料處理
if (firstRowAsHeader) continue;
}
try
{ t.Rows.Add(p);
}
catch (Exception e2)
{ throw new ApplicationException("資料匯入失敗!\n資料=" + line + "\n錯誤訊息:" + e2.ToString());
}
}
}
return t;
}
private static void test()
{ string csv = "ID,Name,Score\n1,Jeffrey,200\n2,Darkthread,999";
//Or you can read data from file
//string csv = System.IO.File.ReadAllText("B:\\mydata.csv"); DataTable t = ConvertCSVtoDataTable(csv, true);
Debug.WriteLine("RowCount=" + t.Rows.Count); foreach (DataRow r in t.Rows)
Debug.WriteLine(string.Format("{0}=>{1}", r["Name"], r["Score"])); csv = "1,Jeffrey,200\n2,Darkthread,999";
t = ConvertCSVtoDataTable(csv, false);
Debug.WriteLine("RowCount=" + t.Rows.Count); foreach (DataRow r in t.Rows)
Debug.WriteLine(string.Format("{0}=>{1}", r["C2"], r["C3"]));}