Export Data list to Excel with EPPLUS

Export Data list to Excel with EPPLUS

Summary

  • What is EPPLUS

  • How to export

  • Advance customizations

What is EPPLUS

EPPLUS is a .Net library that helps to export data to Excel.

As a developer, there are sometimes when we are working on a certain kind of project we could need to export data to Excel for report purposes or analysis purposes. In that case, if you want to use the provided built-in Api for Excel interop with .Net, it can take you too long. that's where EPPLUS comes to rescue us.

How to Export.

  • First, you will need to download the EPPLUS package from the Nuget package manager of your application.

  • in this example, we'll use a list of objects.

Let's say we want to reuse the same DTO we use to get data and export our data. but we want to have a different name displayed on the column header.

we can process it as follows

public class Data
{
     [System.ComponentModel.DisplayName("Idenitifier")]
      public int Id { get; set; }

     [System.ComponentModel.DisplayName("Names")]
      public string Fullname { get; set; }

     [System.ComponentModel.DisplayName("Location")]
      public string Position { get; set; }
}

In the below lines, we use the DisplayName attribute to specify how the header, based on the entity properties should be displayed(printed) on the Excel sheet.

After that, we can proceed to the exportation as shown below.

//Save the file on the desktop.
var basePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var path = Path.Combine(basePath, $"file_{DateTime.Now.ToString("dd_MM_yyyy")}.xlsx");

List<Data> datas = new List<Data>()
 {
    new Data{Id= 1, Fullname="Emp 1", Position="Software developer"},
    new Data{Id=2, Fullname="Emp 2", Position="UI Designer" },
    new Data{Id= 3, Fullname="Emp 3", Position="Software Architect"},
    new Data{Id= 4, Fullname="Emp 4", Position="Manager"},
  };

ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

 FileInfo file = new FileInfo(path1);
 using (var excelPack = new ExcelPackage(file))
 {

      var ws = excelPack.Workbook.Worksheets.Add("Test_data");
      ws.DefaultColWidth = 30;

       ws.Cells["A1"].LoadFromCollection(datas, config =>
       {
          config.PrintHeaders = true;
           config.TableStyle = OfficeOpenXml.Table.TableStyles.Light5;           
        });

        excelPack.Save();
 }
  • First, we are defining the path where to save the file and the name of the file, in our case It's the desktop folder.

  • Then we define the list mock list for exportation.

  • after that we're specifying the license type that we will use, in this case, it's a non-commercial one for demo purposes, but if it's a commercial one please check the EPPLUS official site for further information.

  • Now we use the FilInfo class to get metadata of the path created where we will save the file.

  • last thing we are creating the file.

After that, the sheet is ready to be used.

Advance customizations

The EPPLUS library is very flexible and customizable, we can even decide which property should be used column or displayed when exporting data. To do that, we can proceed as follow

using (var excelPack = new ExcelPackage(file))
{
    var ws = excelPack.Workbook.Worksheets.Add("Test_data");
    ws.DefaultColWidth = 30;

     var dataType  = typeof(Data);
     ws.Cells["A1"].LoadFromCollection(datas, config =>
     {
        config.PrintHeaders = true;
        config.TableStyle = OfficeOpenXml.Table.TableStyles.Light5;

        //Here we are specifying the properties to use as column(export) and even
        //the column orders
        config.Members = new System.Reflection.MemberInfo[]
        {
            dataType .GetProperty(nameof(Data.Id)),
            dataType .GetProperty(nameof(Data.Expiry)),
            dataType .GetProperty(nameof(Data.Position)),
        };
     });
     excelPack.Save();
 }

Conclusion

With the above short explanations, I hope that this article will be helpful to you.