你的位置:首页 > ASP.net教程

[ASP.net教程]DataTable转CSV


直接上方法:

 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     }