首页 > 代码库 > c# datatable 如何转CSV文件
c# datatable 如何转CSV文件
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 =http://www.mamicode.com/ 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 =http://www.mamicode.com/ 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); } }
c# datatable 如何转CSV文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。