内容目录
代码所示,将 Table 导出为 .csv 格式的数据。
public static async Task SaveCSV(DataTable dt,string[] header, string fileName)
{
StringBuilder sb = new StringBuilder();
sb.Append($"{string.Join(",", header)}\r\n");
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j <= dt.Columns.Count - 1; j++)
{
sb.Append("\"" + dt.Rows[i][j] + "\"" + ",");
}
sb.Remove(sb.Length - 1, 1).Append("\r\n");
}
var bytes = Encoding.UTF8.GetBytes(sb.ToString());
using FileStream fileStream = new FileStream(fileName, FileMode.CreateNew);
await fileStream.WriteAsync(bytes);
}
调用:
DataTable dataTable = new DataTable("结果");
var header = new List<string>() { "id","name",... };
foreach (var item in header)
{
dataTable.Columns.Add(item,typeof(string));
}
foreach (var item in exportObj.Values)
{
DataRow dr = dataTable.NewRow();
foreach (var r in item)
{
dr[r.Key] = r.Value;
}
dataTable.Rows.Add(dr);
}
SaveCSV(dataTable, header.ToArray(), filePath).Wait();
文章评论