How to export DataTable to Excel

user1057221 picture user1057221 · Nov 21, 2011 · Viewed 492.7k times · Source

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 to export records of DataTable to Excel.

Answer

hmqcnoesy picture hmqcnoesy · Nov 21, 2011

I would recommend ClosedXML -

You can turn a DataTable into an Excel worksheet with some very readable code:

XLWorkbook wb = new XLWorkbook();
DataTable dt = GetDataTableOrWhatever();
wb.Worksheets.Add(dt,"WorksheetName");

The developer is responsive and helpful. The project is actively developed, and the documentation is superb.