在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
public void DataTableToCSV(DataTable dtCSV, string csvFileFullName, bool writeHeader, string delimeter) { if ((null != dtCSV) && (dtCSV.Rows.Count > 0)) { //Delete the old one if (File.Exists(csvFileFullName)) { File.Delete(csvFileFullName); } string tmpLineText = ""; //Write header if (writeHeader) { tmpLineText = ""; for (int i = 0; i < dtCSV.Columns.Count; i++) { string tmpColumnValue = dtCSV.Columns[i].ColumnName; if (tmpColumnValue.Contains(delimeter)) { tmpColumnValue = "\"" + tmpColumnValue + "\""; } if (i == dtCSV.Columns.Count - 1) { tmpLineText += tmpColumnValue; } else { tmpLineText += tmpColumnValue + delimeter; } } WriteFile(csvFileFullName, tmpLineText); } //Write content for (int j = 0; j < dtCSV.Rows.Count; j++) { tmpLineText = ""; for (int k = 0; k < dtCSV.Columns.Count; k++) { string tmpRowValue = dtCSV.Rows[j][k].ToString(); if (tmpRowValue.Contains(delimeter)) { tmpRowValue = "\"" + tmpRowValue + "\""; } if (k == dtCSV.Columns.Count - 1) { tmpLineText += tmpRowValue; } else { tmpLineText += tmpRowValue + delimeter; } } WriteFile(csvFileFullName, tmpLineText); } } } private void WriteFile(string fileFullName, string message) { using (StreamWriter sw = new StreamWriter(fileFullName, true, Encoding.UTF8)) { sw.WriteLine(message); } }
|
请发表评论