C#实现DataTable转TXT、CSV文件

C#实现DataTable转TXT、CSV文件

转TXT文件 public object DataTableToTXT(DataTable vContent, string vOutputFilePath) { object resObj; StringBuilder sTxtContent; try { if (File.Exists(vOutputFilePath)) File.Delete(vOutputFilePath); sTxtContent = new StringBuilder(); //数据 foreach (DataRow row in vContent.Rows) { for (int i = 0; i < vContent.Columns.Count; i++) { sTxtContent.Append(row[i].ToString().Trim()); sTxtContent.Append(i == vContent.Columns.Count - 1 ? "\r\n" : "\t"); } } File.WriteAllText(vOutputFilePath, sTxtContent.ToString(), Encoding.Unicode); resObj = new object[] { 0, "OK" }; } catch (Exception ex) { resObj = new object[] { 0, "OK" }; } return resObj; } 转.CSV文件

将DataTable转换成CSV文件是一种常见的转换形式,主要通过遍历Table的每行,再对每行遍历每列,实现对数据的读取,然后用分隔符分隔Table的每个栏位数据,把读取的字符写入到CSV文件中。这里每个栏位之间用逗号分隔,每行用换行符。实现代码如下:

public ExecutionResult DataTableToCsv(System.Data.DataTable vContent, string vOutputFilePath) { ExecutionResult sResult = new ExecutionResult(); System.Text.StringBuilder sCsvContent; try { sCsvContent = new System.Text.StringBuilder(); //栏位 for (int i = 0; i < vContent.Columns.Count; i++) { sCsvContent.Append(vContent.Columns[i].ColumnName); sCsvContent.Append(i == vContent.Columns.Count - 1 ? "\r\n" : ","); } //数据 foreach (System.Data.DataRow row in vContent.Rows) { for (int i = 0; i < vContent.Columns.Count; i++) { sCsvContent.Append(row[i].ToString().Trim()); sCsvContent.Append(i == vContent.Columns.Count - 1 ? "\r\n" : ","); } } File.WriteAllText(vOutputFilePath, sCsvContent.ToString(), Encoding.UTF8); sResult.Status = true; } catch (Exception ex) { sResult.Message = ex.Message; sResult.Status = false; } return sResult; }

到此这篇关于C#实现DataTable转TXT、CSV文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持易知道(ezd.cc)。

推荐阅读