Reference: http://closedxml.codeplex.com/
add namespace:
using ClosedXML.Excel; using System.IO; Method:
public void ExportDataToExcel(DataTable dt, string fileName) { using (XLWorkbook wb = new XLWorkbook()) { var ws = wb.Worksheets.Add(dt, "ws"); // worksheets name must be added. wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; wb.Style.Font.Bold = true; //set header style ws.Rows(1, 1).Style.Fill.BackgroundColor = XLColor.White; ws.Rows(1, 1).Style.Font.Bold = true; ws.Rows(1, 1).Style.Font.FontColor = XLColor.Onyx; ws.Columns().Width = 20; //remove AutoFilter ws.Tables.FirstOrDefault().ShowAutoFilter = false; Response.Clear(); Response.Buffer = true; Response.Charset = "utf-8"; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx"); using (MemoryStream MyMemoryStream = new MemoryStream()) { wb.SaveAs(MyMemoryStream); MyMemoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } } }
时间: 2024-10-12 22:39:45