asp.net using library ClosedXML to export excel

Reference:  http://closedxml.codeplex.com/ 

 

1. First add refenrence ClosedXML.dll and DocumentFormat.OpenXml.dll to the project. 

2. add namespace: 

using ClosedXML.Excel;
using System.IO;




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

你可能感兴趣的:(asp.net using library ClosedXML to export excel)