gpt4 book ai didi

c# - 将 DataTable 内容导出到 CSV 文件

转载 作者:行者123 更新时间:2023-11-30 17:25:45 25 4
gpt4 key购买 nike

我的代码导出了 3 个 csv 文件,这是我想要做的。但我的问题是每个 csv 文件都包含所有区域的所有数据,而不是仅包含指定区域的数据。

我应该如何更改才能获得仅包含指定区域数据的 3 个 csv 文件?

private void GenerateRegionTest()
{
DataTable regionInfo = new DataTable();
regionInfo.Columns.Add("storeID", typeof(int));
regionInfo.Columns.Add("storeName", typeof(string));
regionInfo.Columns.Add("Region", typeof(string));
regionInfo.Rows.Add(25, "Store 1", "Region 1");
regionInfo.Rows.Add(50, "Store 2", "Region 1");
regionInfo.Rows.Add(10, "Store 3", "Region 1");
regionInfo.Rows.Add(21, "Store 4", "Region 1");
regionInfo.Rows.Add(251, "Store 11", "Region 11");
regionInfo.Rows.Add(501, "Store 21", "Region 11");
regionInfo.Rows.Add(101, "Store 31", "Region 11");
regionInfo.Rows.Add(211, "Store 41", "Region 11");
regionInfo.Rows.Add(215, "Store 12", "Region 12");
regionInfo.Rows.Add(510, "Store 22", "Region 12");
regionInfo.Rows.Add(110, "Store 32", "Region 12");
regionInfo.Rows.Add(211, "Store 42", "Region 12");
StringBuilder sb = new StringBuilder();
var columnNames = dt.AsEnumerable().GroupBy((storeName) => storeName.Field<string>("Region"))
.Select((group) => new
{
Region = group.Key,
DataRowList = group.OrderBy((dataRow) => dataRow.Field<string>("storeName")).ToList()
}).OrderBy(x => x.Region).ToList();

sb.AppendLine(string.Join(",", columnNames));
foreach (var row in columnNames)
{
foreach (var dataRow in row.DataRowList)
{
IEnumerable<string> fields = dataRow.ItemArray.Select(field => string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
sb.AppendLine(string.Join(",", fields));
}
string fileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)) + "\\" + row + "Breakout.csv";
File.WriteAllText(fileName, sb.ToString());
}
}

最佳答案

您必须将 StringBuilder 的初始化移动到循环中:

foreach (var row in columnNames)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(string.Join(",", columnNames));
foreach (var dataRow in row.DataRowList)
{
IEnumerable<string> fields = dataRow.ItemArray.Select(field => string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
sb.AppendLine(string.Join(",", fields));
}
string fileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)) + "\\" + row + "Breakout.csv";
File.WriteAllText(fileName, sb.ToString());
}

关于c# - 将 DataTable 内容导出到 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57727059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com