直接上方法:
1 /// <summary> 2 /// 將DataTable轉換成CSV文件 3 /// </summary> 4 /// <param name="dt">DataTable</param> 5 /// <param name="filePath">文件路徑</param> 6 public static void SaveCSV(DataTable dt, string filePath) 7 { 8 FileStream fs = new FileStream(filePath + dt.TableName + ".csv", System.IO.FileMode.Create, System.IO.FileAccess.Write); 9 StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default); 10 string data = ""; 11 12 //寫出列名稱 13 for (int i = 0; i < dt.Columns.Count; i++) 14 { 15 data += dt.Columns[i].ColumnName.ToString(); 16 if (i < dt.Columns.Count - 1) 17 { 18 data += ","; 19 } 20 } 21 sw.WriteLine(data); 22 23 //寫出各行數據 24 for (int i = 0; i < dt.Rows.Count; i++) 25 { 26 data = ""; 27 for (int j = 0; j < dt.Columns.Count; j++) 28 { 29 data += dt.Rows[i][j].ToString(); 30 if (j < dt.Columns.Count - 1) 31 { 32 data += ","; 33 } 34 } 35 sw.WriteLine(data); 36 } 37 sw.Close(); 38 fs.Close(); 39 }