DataTable转为TXT文档
程序员文章站
2022-05-29 09:30:15
public static void SaveCSV(DataTable dt, string fullPath) { var fi = new FileInfo(fullPath); if (!fi.Directory.Exists) { fi.Directory.Create(); } var ......
public static void savecsv(datatable dt, string fullpath) { var fi = new fileinfo(fullpath); if (!fi.directory.exists) { fi.directory.create(); } var fs = new filestream(fullpath, filemode.append, fileaccess.write); //streamwriter sw = new streamwriter(fs, system.text.encoding.default); var sw = new streamwriter(fs, encoding.utf8); var data = ""; //写出列名称 if (s == 0) { ++s; for (var i = 0; i < dt.columns.count; i++) { data += dt.columns[i].columnname; if (i < dt.columns.count - 1) { data += ","; } } sw.writeline(data); } //写出各行数据 for (var i = 0; i < dt.rows.count; i++) { data = ""; for (var j = 0; j < dt.columns.count; j++) { var str = dt.rows[i][j].tostring(); str = str.replace("\"", "\"\""); //替换英文冒号 英文冒号需要换成两个冒号 if (str.contains(',') || str.contains('"') || str.contains('\r') || str.contains('\n')) //含逗号 冒号 换行符的需要放到引号中 { str = string.format("\"{0}\"", str); } data += str; if (j < dt.columns.count - 1) { data += ","; } } sw.writeline(data); } sw.close(); fs.close(); }
非原创
上一篇: SSH agent 的使用 - 资料摘录
下一篇: 今天春分吃啥好吃的