您好,登錄后才能下訂單哦!
//author: walker //date: 2014-01-07 //function: 將DataTable導出到csv文件 public static bool datatableToCSV(DataTable dt, string pathFile) { string strLine = ""; StreamWriter sw; try { sw = new StreamWriter(pathFile, false, System.Text.Encoding.GetEncoding(-0)); //覆蓋 //表頭 for (int i = 0; i < dt.Columns.Count; i++) { if (i > 0) strLine += ","; strLine += dt.Columns[i].ColumnName; } strLine.Remove(strLine.Length - 1); sw.WriteLine(strLine); strLine = ""; //表的內容 for (int j = 0; j < dt.Rows.Count; j++) { strLine = ""; int colCount = dt.Columns.Count; for (int k = 0; k < colCount; k++) { if (k > 0 && k < colCount) strLine += ","; if (dt.Rows[j][k] == null) strLine += ""; else { string cell = dt.Rows[j][k].ToString().Trim(); //防止里面含有特殊符號 cell = cell.Replace("\"", "\"\""); cell = "\"" + cell + "\""; strLine += cell; } } sw.WriteLine(strLine); } sw.Close(); string msg = "數據被成功導出到:" + pathFile; Console.WriteLine(msg); } catch (Exception ex) { string msg = "導出錯誤:" + pathFile; Console.WriteLine(msg); return false; } return true; }
相關閱讀:
1、關于特殊符號和分隔符。
2、C#將DataGridView導出到csv文件。
*** walker ***
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。