直接上方法:
1 ///2 /// 将DataTable转换成CSV文件 3 /// 4 /// DataTable 5 /// 文件路径 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 }