将DataTable内容导出到CSV文件

时间:2019-08-30 12:48:08

标签: c#

我的代码导出了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());
    }
}

1 个答案:

答案 0 :(得分:1)

您必须将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());
}