/// <summary>
/// DataTable转CSV
/// </summary>
/// <param name="dtData">数据内容</param>
/// <param name="outFilePath">导出路径 eg:C:\Users\res.csv</param>
/// <returns>是否成功</returns>
public static bool DataTableToCsv(DataTable dtData, string outFilePath)
{
try
{
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < dtData.Columns.Count; i++)
{
sBuilder.Append(dtData.Columns[i].ColumnName);
sBuilder.Append(i == dtData.Columns.Count - 1 ? "\r\n" : ",");
}
foreach (DataRow row in dtData.Rows)
{
for (int i = 0; i < dtData.Columns.Count; i++)
{
sBuilder.Append(row[i].ToString().Trim());
sBuilder.Append(i == dtData.Columns.Count - 1 ? "\r\n" : ",");
}
}
File.WriteAllText(outFilePath, sBuilder.ToString(), Encoding.UTF8);
return true;
}
catch (Exception ex)
{
return false;
}
}
C# DataTable转CSV
最新推荐文章于 2023-12-20 10:11:56 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)