Export To Excel In ASP.NET MVC

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.

Install EPPlus nuget
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.

 Process Export to Excel
Figure 2: Process Export to Excel

Using the Code

As per the above process, we need four operations here. These are as follows,

  1. Data: We use static data to keep this example simple.
  2. List: Static data store in a List<T>.
  3. Data Table : Convert List<T> in to DataTable.
  4. 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.

  1. namespace ExportExcel.Code  
  2. {  
  3.     public class Technology  
  4.     {  
  5.         public string Name { get; set; }  
  6.         public int Project { get; set; }  
  7.         public int Developer { get; set; }  
  8.         public int TeamLeader { get; set; }  
  9.     }  
  10. }  
Now, we create a static data list of Technology types in that StaticData class, as per the following code snippet.
  1. using System.Collections.Generic;  
  2.   
  3. namespace ExportExcel.Code  
  4. {  
  5.     public class StaticData  
  6.     {  
  7.         public static List<Technology> Technologies  
  8.         {  
  9.             get  
  10.             {  
  11.                 return new List<Technology>{  
  12.                      new Technology{Name="ASP.NET"Project=12,Developer=50TeamLeader=6},  
  13.                     new Technology{Name="Php"Project=40,Developer=60TeamLeader=9},  
  14.                     new Technology{Name="iOS"Project=11,Developer=5TeamLeader=1},  
  15.                      new Technology{Name="Android"Project=20,Developer=26TeamLeader=2}  
  16.                 };  
  17.             }  
  18.         }  
  19.     }  
  20. }  
This data will be used to export to Excel. After that, we create export to excel functionality helper class which has the following features. 
  1. Convert List<T> to DataTable method
  2. Customize the columns which need to export means dynamically choose columns which will be export from list to Excel.
  3. Serial number in Excel sheet.
  4. Add and Remove functionality for the custom heading in Excel sheet.
  5. Excel sheet heading with colors.
  6. Dynamic name for worksheet.

The following code snippet is used for the class ExcelExportHelper .

  1. using OfficeOpenXml;  
  2. using OfficeOpenXml.Style;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.ComponentModel;  
  6. using System.Data;  
  7. using System.Linq;  
  8.   
  9. namespace ExportExcel.Code  
  10. {  
  11.     public class ExcelExportHelper  
  12.     {  
  13.         public static string ExcelContentType  
  14.         {  
  15.             get  
  16.             { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }  
  17.         }  
  18.   
  19.         public static DataTable ListToDataTable<T>(List<T> data)  
  20.         {  
  21.             PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));  
  22.             DataTable dataTable = new DataTable();  
  23.   
  24.             for (int i = 0; i < properties.Count; i++)  
  25.             {  
  26.                 PropertyDescriptor property = properties[i];  
  27.                 dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);  
  28.             }  
  29.   
  30.             object[] values = new object[properties.Count];  
  31.             foreach (T item in data)  
  32.             {  
  33.                 for (int i = 0; i < values.Length; i++)  
  34.                 {  
  35.                     values[i] = properties[i].GetValue(item);  
  36.                 }  
  37.   
  38.                 dataTable.Rows.Add(values);  
  39.             }  
  40.             return dataTable;  
  41.         }  
  42.   
  43.         public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)  
  44.         {  
  45.   
  46.             byte[] result = null;  
  47.             using (ExcelPackage package = new ExcelPackage())  
  48.             {  
  49.                 ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data",heading));  
  50.                 int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;  
  51.   
  52.                 if (showSrNo)  
  53.                 {  
  54.                     DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));  
  55.                     dataColumn.SetOrdinal(0);  
  56.                     int index = 1;  
  57.                     foreach (DataRow item in dataTable.Rows)  
  58.                     {  
  59.                         item[0] = index;  
  60.                         index++;  
  61.                     }  
  62.                 }  
  63.   
  64.   
  65.                 // add the content into the Excel file  
  66.                 workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);  
  67.   
  68.                 // autofit width of cells with small content  
  69.                 int columnIndex = 1;  
  70.                 foreach (DataColumn column in dataTable.Columns)  
  71.                 {  
  72.                     ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];  
  73.                     int maxLength = columnCells.Max(cell => cell.Value.ToString().Count());  
  74.                     if (maxLength < 150)  
  75.                     {  
  76.                         workSheet.Column(columnIndex).AutoFit();  
  77.                     }  
  78.   
  79.   
  80.                     columnIndex++;  
  81.                 }  
  82.   
  83.                 // format header - bold, yellow on black  
  84.                 using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])  
  85.                 {  
  86.                     r.Style.Font.Color.SetColor(System.Drawing.Color.White);  
  87.                     r.Style.Font.Bold = true;  
  88.                     r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;  
  89.                     r.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#1fb5ad"));  
  90.                 }  
  91.   
  92.                 // format cells - add borders  
  93.                 using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])  
  94.                 {  
  95.                     r.Style.Border.Top.Style = ExcelBorderStyle.Thin;  
  96.                     r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;  
  97.                     r.Style.Border.Left.Style = ExcelBorderStyle.Thin;  
  98.                     r.Style.Border.Right.Style = ExcelBorderStyle.Thin;  
  99.   
  100.                     r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);  
  101.                     r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);  
  102.                     r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);  
  103.                     r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);  
  104.                 }  
  105.   
  106.                 // removed ignored columns  
  107.                 for (int i = dataTable.Columns.Count - 1; i >= 0; i--)  
  108.                 {  
  109.                     if (i == 0 && showSrNo)  
  110.                     {  
  111.                         continue;  
  112.                     }  
  113.                     if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))  
  114.                     {  
  115.                         workSheet.DeleteColumn(i + 1);  
  116.                     }  
  117.                 }  
  118.   
  119.                 if (!String.IsNullOrEmpty(heading))  
  120.                 {  
  121.                     workSheet.Cells["A1"].Value = heading;  
  122.                     workSheet.Cells["A1"].Style.Font.Size = 20;  
  123.   
  124.                     workSheet.InsertColumn(1, 1);  
  125.                     workSheet.InsertRow(1, 1);  
  126.                     workSheet.Column(1).Width = 5;  
  127.                 }  
  128.   
  129.                 result = package.GetAsByteArray();  
  130.             }  
  131.   
  132.             return result;  
  133.         }  
  134.   
  135.         public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)  
  136.         {  
  137.             return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake);  
  138.         }  
  139.   
  140.     }  
  141. }  
Now, we do front-end development and create Model, View and Controller. We create TechnologyViewModel view model that binds to the View, as per the following code snippet.
  1. using ExportExcel.Code;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace ExportExcel.Models  
  5. {  
  6.     public class TechnologyViewModel  
  7.     {  
  8.         public List<Technology> Technologies  
  9.         {  
  10.             get  
  11.             {  
  12.                 return StaticData.Technologies;  
  13.             }  
  14.         }  
  15.     }  
  16. }  
After this, we create a controller, HomeController, which has an Index action method. It returns View with Model in the browser.
  1. using ExportExcel.Code;  
  2. using ExportExcel.Models;  
  3. using System.Collections.Generic;  
  4. using System.Web.Mvc;  
  5.   
  6. namespace ExportExcel.Controllers  
  7. {  
  8.     public class HomeController : Controller  
  9.     {  
  10.         [HttpGet]  
  11.         public ActionResult Index()  
  12.         {  
  13.             TechnologyViewModel model = new TechnologyViewModel();  
  14.             return View(model);  
  15.         }  
  16.     }  
  17. }  
Now, we create a view that shows the data in the listing and has a button linked to export to Excel functionality. The following code snippet is for the Index view.
  1. @model ExportExcel.Models.TechnologyViewModel  
  2. @{  
  3.     ViewBag.Title = "Export To Excel";  
  4. }  
  5. <div class="panel">  
  6.     <div class="panel-heading">  
  7.         <a href="@Url.Action("ExportToExcel")" class="btn btn-primary">Export</a>  
  8.     </div>  
  9.     <div class="panel-body">  
  10.         <table class="table table-striped table-bordered">  
  11.             <thead>  
  12.                 <tr>  
  13.                     <th>Name</th>  
  14.                     <th>Project</th>  
  15.                     <th>Team Leader</th>  
  16.                     <th>Developer</th>  
  17.                 </tr>  
  18.             </thead>  
  19.             <tbody>  
  20.                 @foreach (var item in Model.Technologies)  
  21.                 {  
  22.                     <tr>  
  23.                         <td>@item.Name</td>  
  24.                         <td>@item.Project</td>  
  25.                         <td>@item.TeamLeader</td>  
  26.                         <td>@item.Developer</td>  
  27.                     </tr>  
  28.                 }  
  29.             </tbody>  
  30.         </table>  
  31.     </div>  
  32. </div>  
The application runs and shows results as follows.

Listing for Data
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.
  1. [HttpGet]  
  2.         public FileContentResult ExportToExcel()  
  3.         {  
  4.             List<Technology> technologies = StaticData.Technologies;  
  5.             string[] columns = {"Name","Project","Developer"};  
  6.             byte[] filecontent = ExcelExportHelper.ExportExcel(technologies, "Technology"true,columns );  
  7.             return File(filecontent, ExcelExportHelper.ExcelContentType, "Technologies.xlsx");  
  8.         }  
Now, click on export button. The button calls the above action method and the result is as shown in the figure.

Dialog for Excel
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.

Excel with Data
Figure 5: Excel with Data
 
Download
 
You can download the complete solution source code from the link.