C#实现DataTable转.CSV文件
2021-01-20 04:15
标签:text false enc 常见 换行 col stat 实现 uil 将DataTable转换成CSV文件是一种常见的转换形式,主要通过遍历Table的每行,再对每行遍历每列,实现对数据的读取,然后用分隔符分隔Table的每个栏位数据,把读取的字符写入到CSV文件中。这里每个栏位之间用逗号分隔,每行用换行符。实现代码如下: C#实现DataTable转.CSV文件 标签:text false enc 常见 换行 col stat 实现 uil 原文地址:https://www.cnblogs.com/wml-it/p/12145656.htmlpublic 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 )
{
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 )
{
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;
}