我的代码导出了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/

10-13 09:15