How to export DataTable to Excel using ClosedXML in C#

05 April 2023 | Viewed 7243 times

ClosedXML is a .NET library for reading, manipulating and writing Excel 2007+ (.xlsx, .xlsm) files. It provides user-friendly interface to dealing with the underlying OpenXML API.

C# Code

public void ExportDataTableToExcel()
{
DataTable dataTable = GetDataTable(); get your data

XLWorkbook workbook = new XLWorkbook();
// Add worksheet with data
var worksheet = workbook.Worksheets.Add(dataTable, "Sheet1");

// Formattings Sheet
worksheet.Table(0).Theme = XLTableTheme.TableStyleLight20;
worksheet.Row(1).Style.Font.Bold = true;
worksheet.SheetView.FreezeRows(1);
worksheet.Columns().AdjustToContents(10.0, 50.0);

// Convert workbook into stream to download
var stream = new MemoryStream();
workbook.SaveAs(stream);

// Download ExcelFile from Bynary Data
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xlsx");
HttpContext.Current.Response.BinaryWrite(stream.ToArray());

HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}


PreviousNext