Excel Export in Asp.Net MVC using XlWorkbook
XlWorkBook
XlWorkbook is a third party library that helps you to export data into excel file in easy steps. It also helps in giving formatting to excel like background color, border, color and formulas
Exporting Excel using XlWorkbook in Asp.Net MVC
So, first of all you have to install ClosedXml nuget package in your project which is showed in the image
After installing the package , you have to go to the controller and add namespace
using ClosedXML.Excel;
Now you can use Xlworkbook in your code , Xlworkbook requires data as datatable to export it into excel. Please have a look at this sample code
public ActionResult Download() { DataTable table = DummyDataTableSource(); using (XLWorkbook workbook = new XLWorkbook()) { table.TableName = "Table 1";/*Giving table name is mandatory and it must be unique between multiple worksheets*/ workbook.Worksheets.Add(table); Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment;filename=Dummy Excel Export.xlsx"); using (MemoryStream MyMemoryStream = new MemoryStream()) { workbook.SaveAs(MyMemoryStream); MyMemoryStream.WriteTo(Response.OutputStream); } } Response.Flush(); Response.End(); return View(); } private static DataTable DummyDataTableSource() { DataTable table = new DataTable(); table.Columns.Add("Name"); table.Columns.Add("Number"); table.Columns.Add("Address"); table.Columns.Add("City"); for (int i = 0; i < 10; i++) { DataRow dr = table.NewRow(); dr["Name"] = "Name " + i; dr["Number"] = "Number " + i; dr["Address"] = "Address " + i; dr["City"] = "City " + i; table.Rows.Add(dr); } return table; }
Here, we have to pass the data to worksheet in the datatable format and you have to provide a tablename to datatable. We will call this action from view like this
<a style="margin-top:10px" class="btn btn-primary" href="/Home/Download">Export to Excel</a>
So, if you will click on this button you will see your data is exported in excel format. You can check in the image
So, this is how you can export data in excel using XlWorkbook in Asp.Net mvc.