Introduction
This article introduces how to export data in an Excel file. Most of the back-end applications have report functionality that show the data in the grid. So, we are required to export this grid data into an Excel file. The export to Excel functionality is implemented using the EPPlus nuGet package, as shown in this example.
Configuration and Process
We install EPPlus nuGet package in the application. The EPPlus is a library to manage Excel spreadsheets using OOXML. The OOXML stands for Office Open Extended Markup Language and is also called Open XML. The OOXML is developed by Microsoft. It has by default target file formats for Microsoft office.
The EPPlus is a NuGet package and can be installed from Manage NuGet Packages window, as shown in figure 1. The package is available here also.

Figure 1: Install EPPlus nuget
When we use ORM in our application, we keep most of the data inthe collection which easily converts it in a list. The list can’t be exported to the Excel directly. That’s why we need to convert this list in data table first. After that, this data table can be exported in the Excel file as shown in figure 2.

Figure 2: Process Export to Excel
Using the Code
As per the above process, we need four operations here. These are as follows,
- Data: We use static data to keep this example simple.
- List: Static data store in a List<T>.
- Data Table : Convert List<T> in to DataTable.
- Export: DataTable exports to excel file.
First of all, we create a class, so that we can have a collection of similar data. The following code snippet is for Technology class.
- namespace ExportExcel.Code
- {
- public class Technology
- {
- public string Name { get; set; }
- public int Project { get; set; }
- public int Developer { get; set; }
- public int TeamLeader { get; set; }
- }
- }
- using System.Collections.Generic;
- namespace ExportExcel.Code
- {
- public class StaticData
- {
- public static List<Technology> Technologies
- {
- get
- {
- return new List<Technology>{
- new Technology{Name="ASP.NET", Project=12,Developer=50, TeamLeader=6},
- new Technology{Name="Php", Project=40,Developer=60, TeamLeader=9},
- new Technology{Name="iOS", Project=11,Developer=5, TeamLeader=1},
- new Technology{Name="Android", Project=20,Developer=26, TeamLeader=2}
- };
- }
- }
- }
- }
- Convert List<T> to DataTable method
- Customize the columns which need to export means dynamically choose columns which will be export from list to Excel.
- Serial number in Excel sheet.
- Add and Remove functionality for the custom heading in Excel sheet.
- Excel sheet heading with colors.
- Dynamic name for worksheet.
The following code snippet is used for the class ExcelExportHelper .
- using OfficeOpenXml;
- using OfficeOpenXml.Style;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Linq;
- namespace ExportExcel.Code
- {
- public class ExcelExportHelper
- {
- public static string ExcelContentType
- {
- get
- { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
- }
- public static DataTable ListToDataTable<T>(List<T> data)
- {
- PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
- DataTable dataTable = new DataTable();
- for (int i = 0; i < properties.Count; i++)
- {
- PropertyDescriptor property = properties[i];
- dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
- }
- object[] values = new object[properties.Count];
- foreach (T item in data)
- {
- for (int i = 0; i < values.Length; i++)
- {
- values[i] = properties[i].GetValue(item);
- }
- dataTable.Rows.Add(values);
- }
- return dataTable;
- }
- public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
- {
- byte[] result = null;
- using (ExcelPackage package = new ExcelPackage())
- {
- ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data",heading));
- int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;
- if (showSrNo)
- {
- DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
- dataColumn.SetOrdinal(0);
- int index = 1;
- foreach (DataRow item in dataTable.Rows)
- {
- item[0] = index;
- index++;
- }
- }
- // add the content into the Excel file
- workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);
- // autofit width of cells with small content
- int columnIndex = 1;
- foreach (DataColumn column in dataTable.Columns)
- {
- ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
- int maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
- if (maxLength < 150)
- {
- workSheet.Column(columnIndex).AutoFit();
- }
- columnIndex++;
- }
- // format header - bold, yellow on black
- using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
- {
- r.Style.Font.Color.SetColor(System.Drawing.Color.White);
- r.Style.Font.Bold = true;
- r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
- r.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#1fb5ad"));
- }
- // format cells - add borders
- using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
- {
- r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
- r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
- r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
- r.Style.Border.Right.Style = ExcelBorderStyle.Thin;
- r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
- r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
- r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
- r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
- }
- // removed ignored columns
- for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
- {
- if (i == 0 && showSrNo)
- {
- continue;
- }
- if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
- {
- workSheet.DeleteColumn(i + 1);
- }
- }
- if (!String.IsNullOrEmpty(heading))
- {
- workSheet.Cells["A1"].Value = heading;
- workSheet.Cells["A1"].Style.Font.Size = 20;
- workSheet.InsertColumn(1, 1);
- workSheet.InsertRow(1, 1);
- workSheet.Column(1).Width = 5;
- }
- result = package.GetAsByteArray();
- }
- return result;
- }
- public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
- {
- return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake);
- }
- }
- }
- using ExportExcel.Code;
- using System.Collections.Generic;
- namespace ExportExcel.Models
- {
- public class TechnologyViewModel
- {
- public List<Technology> Technologies
- {
- get
- {
- return StaticData.Technologies;
- }
- }
- }
- }
- using ExportExcel.Code;
- using ExportExcel.Models;
- using System.Collections.Generic;
- using System.Web.Mvc;
- namespace ExportExcel.Controllers
- {
- public class HomeController : Controller
- {
- [HttpGet]
- public ActionResult Index()
- {
- TechnologyViewModel model = new TechnologyViewModel();
- return View(model);
- }
- }
- }
- @model ExportExcel.Models.TechnologyViewModel
- @{
- ViewBag.Title = "Export To Excel";
- }
- <div class="panel">
- <div class="panel-heading">
- <a href="@Url.Action("ExportToExcel")" class="btn btn-primary">Export</a>
- </div>
- <div class="panel-body">
- <table class="table table-striped table-bordered">
- <thead>
- <tr>
- <th>Name</th>
- <th>Project</th>
- <th>Team Leader</th>
- <th>Developer</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var item in Model.Technologies)
- {
- <tr>
- <td>@item.Name</td>
- <td>@item.Project</td>
- <td>@item.TeamLeader</td>
- <td>@item.Developer</td>
- </tr>
- }
- </tbody>
- </table>
- </div>
- </div>

Figure 3: Listing for Data
Now, we write the action method to call the export to Excel functionality. This action method returns n aexported Excel file. The action method returns FileContentResult which is used when we have a byte array and return as a file. The following code snippet is used for the same.
- [HttpGet]
- public FileContentResult ExportToExcel()
- {
- List<Technology> technologies = StaticData.Technologies;
- string[] columns = {"Name","Project","Developer"};
- byte[] filecontent = ExcelExportHelper.ExportExcel(technologies, "Technology", true,columns );
- return File(filecontent, ExcelExportHelper.ExcelContentType, "Technologies.xlsx");
- }

Figure 4: Dialog for Excel
The resulted Excel file has the data. It has only those columns that we exported rather than all the columns of the collection.



Lakshmi NNairPosted Apr 5, 2019, 1:09 AM EDT
Hai sir how to export graph from aspx page to excel
Alice NguyenPosted Dec 13, 2018, 8:04 PM EST
Thanks, Sandeep so great
Alice NguyenPosted Dec 13, 2018, 8:03 PM EST
Thanks Sandeep
Jagath WanniarachchiPosted Nov 22, 2018, 4:48 PM EST
I tried this but my data-set has DateTime fields, instead of proper values it shows me random numbers like, '43399'. How to resolve this?
Chetan SharmaPosted Jul 25, 2018, 10:28 PM EDT
Hello Sir, I have one query: What is the best way to export data to Excel and Export Data to PPT using Asp.Net MVC 5 application.Any help will be appreciated.
Marcelino ValenzuelaPosted May 9, 2018, 10:00 AM EDT
Hello thanks for the examplebut I have a problem with the dates format in the excel
Dan GomolaPosted Feb 8, 2018, 5:49 AM EST
Thanks Sandeep, can you tell me how to do cell formatting. I'm interested especially in date fields.
Nick WagnerPosted Feb 2, 2018, 12:10 PM EST
This fails to autofit columns if there is a null value. Change line 73 to int maxLength = columnCells.Max(cell => (cell.Value "" ).ToString().Length); will address this issue
haz mohdPosted Jan 2, 2018, 4:35 PM EST
Hi, what if I want to export data from database instead of declared data ?
Shelby PostonPosted Nov 7, 2017, 8:18 AM EST
How does this work with a single record
Muhammad AhmedPosted Oct 10, 2017, 12:29 AM EDT
What if the data that I want to export isnt as simple as this is. I mean what if my list contains another list like a parent-child relation. How can I process it?
Bebins VPosted Mar 7, 2017, 6:12 AM EST
Hi In the same excel if i want to add additional sheet, could you please share code for that?
Noman ChaliPosted Jan 2, 2017, 8:36 PM EST
If ms office is not installed on machine then style, bold, alignment are not working why ?
Vineeth GeeverPosted Dec 18, 2016, 3:20 AM EST
How to edit the column names in excel file?
Cao FangshengPosted Dec 7, 2016, 10:15 PM EST
Nice,thanks.......................
Humayun Kabir MamunPosted Jul 23, 2016, 8:47 PM EDT
Nice...
Sandeep Singh ShekhawatPosted Jul 23, 2016, 3:30 AM EDT
Thanks a lot
Vivek TripathiPosted Jul 23, 2016, 2:55 AM EDT
Gr8
Hanif HefazPosted Jul 21, 2016, 11:04 PM EDT
Thank You Sir
Shridhar SharmaPosted Jul 21, 2016, 9:55 PM EDT
Good one sir
Pankaj Kumar ChoudharyTOP 100Posted Jul 21, 2016, 9:39 PM EDT
Nice example Sir...........
kalu singh raoPosted Jul 21, 2016, 9:22 PM EDT
Nice Share
Debendra DashPosted Jul 12, 2016, 9:58 PM EDT
Good one..
Munesh SharmaPosted Jul 12, 2016, 3:25 AM EDT
Good one
Vignesh ManiTOP 100Posted Jul 11, 2016, 8:37 AM EDT
Nice
Sandeep Singh ShekhawatPosted Jul 11, 2016, 7:30 AM EDT
Thanks all :)
Raja TPosted Jul 11, 2016, 3:10 AM EDT
Nice, Thanks for sharing
Humayun Kabir MamunPosted Jul 10, 2016, 9:03 PM EDT
Nice...
Debasis SahaTOP 100Posted Jul 10, 2016, 8:44 PM EDT
Nice one..
RakeshPosted Jul 10, 2016, 8:31 AM EDT
Good share