C# 生成CSV檔案 或者匯出CSV檔案
阿新 • • 發佈:2019-02-18
直接上程式碼
/// <summary> /// 匯出CSV /// </summary> /// <param name="dataGridView">表格控制元件</param> /// <param name="dataView">資料表格</param> /// <param name="directory">目錄</param> /// <param name="fileName">檔名</param> public static void ExportCSV(System.Data.DataTable table, string directory, string fileName) { // 開始忙了 string directoryName = directory; if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } string file = directory + fileName; // if (!this.FileExist(file)) // { ExportCSV(table, file); //Process.Start(file); // } // 已經忙完了 }
#region public static void ExportCSV(DataTable dataTable, string fileName) 匯出CSV格式檔案 /// <summary> /// 匯出CSV格式檔案 /// </summary> /// <param name="dataTable">資料表</param> /// <param name="fileName">檔名</param> public static void ExportCSV(DataTable dataTable, string fileName) { StreamWriter StreamWriter = new StreamWriter(fileName, false, System.Text.Encoding.GetEncoding("gb2312")); StreamWriter.WriteLine(GetCSVFormatData(dataTable).ToString()); StreamWriter.Flush(); StreamWriter.Close(); } #endregion
#region public static StringBuilder GetCSVFormatData(DataTable dataTable) 通過DataTable獲得CSV格式資料 /// <summary> /// 通過DataTable獲得CSV格式資料 /// </summary> /// <param name="dataTable">資料表</param> /// <returns>CSV字串資料</returns> public static StringBuilder GetCSVFormatData(DataTable dataTable) { StringBuilder StringBuilder = new StringBuilder(); // 寫出表頭 StringBuilder.Append("AAAA,VVVVV,CCCCC "); StringBuilder.Append("\n"); // 寫出資料 int count = 0; foreach (DataRowView dataRowView in dataTable.DefaultView) { count++; foreach (DataColumn DataColumn in dataTable.Columns) { string field = dataRowView[DataColumn.ColumnName].ToString(); if (field.IndexOf('"') >= 0) { field = field.Replace("\"", "\"\""); } field = field.Replace(" ", " "); if (field.IndexOf(',') >= 0 || field.IndexOf('"') >= 0 || field.IndexOf('<') >= 0 || field.IndexOf('>') >= 0 || field.IndexOf("'") >= 0) { field = "\"" + field + "\""; } StringBuilder.Append(field + ","); field = string.Empty; } if (count != dataTable.Rows.Count) { StringBuilder.Append("\n"); } } return StringBuilder; } #endregion