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
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.