In this ASP.Net MVC tutorial, we will explore how to use ClosedXML to download files in the xlsx
format.
https://i.sstatic.net/iJhPN.png
DownloadExcelFileController
private void DownloadExcelFile(ClosedXML.Excel.XLWorkbook workBook, string fileNameFormat)
{
string currentTime = DateTime.Now.ToString();
string headerString = fileNameFormat.Replace("{0}", currentTime);
headerString = headerString.Replace(" ", "");
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", headerString);
using (MemoryStream memoryStream = new MemoryStream())
{
workBook.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
memoryStream.Close();
}
Response.End();
}
ClosedXML.Excel.XLWorkbook GenerateWorkBook
public static ClosedXML.Excel.XLWorkbook GenerateWorkBook(DataTable data, string sheetName)
{
ClosedXML.Excel.XLWorkbook workBook = new ClosedXML.Excel.XLWorkbook();
ClosedXML.Excel.IXLWorksheet workSheet = workBook.Worksheets.Add(data, sheetName);
return workBook;
}
Action Method for POST Request
[Authorize]
[HttpPost]
public void ExportDataToExcel(BalanceStatementModel modelReceived)
{
List<FinanceEntity> rows = GetRunningBalanceDueForPractice();
DataTable table = new DataTable();
using (var reader = FastMember.ObjectReader.Create(rows, "ItemDescription", "EventDate", "Amount", "RunningBalanceDue"))
{
table.Load(reader);
}
ClosedXML.Excel.XLWorkbook workBook = CommonBusinessMethodHelpers.GenerateWorkBook(table, "Statement");
string fileNameFormat = "attachment;filename=\"BalanceStatement-{0}.xlsx\"";
DownloadExcelFile(workBook, fileNameFormat);
}
Note: This code utilizes the FastMember library available through NuGet.
Additional Resources:
Making OpenXML Easy with ClosedXML
Use the library ClosedXml for creating Excel files