[C#] export DataTable to Excel using ClosedXML in C#

inno
2024-02-05 12:48 210 0
[C#] export DataTable to Excel using ClosedXML in C#


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();
}

コメント