How to export DataTable to Excel

后端 未结 21 2345
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 15:36

How can I export a DataTable to Excel in C#? I am using Windows Forms. The DataTable is associated with a DataGridView control. I have

21条回答
  •  心在旅途
    2020-11-22 15:44

    Try simple code, to convert DataTable to excel file as csv:

    var lines = new List();
    
    string[] columnNames = dataTable.Columns
        .Cast()
        .Select(column => column.ColumnName)
        .ToArray();
    
    var header = string.Join(",", columnNames.Select(name => $"\"{name}\""));
    lines.Add(header);
    
    var valueLines = dataTable.AsEnumerable()
        .Select(row => string.Join(",", row.ItemArray.Select(val => $"\"{val}\"")));
    
    lines.AddRange(valueLines);
    
    File.WriteAllLines("excel.csv", lines);
    

    This will write a new file excel.csv into the current working directory which is generally either where the .exe is or where you launch it from.

提交回复
热议问题