How to create an Excel file (XLSX) in C# and populate it using a list of C# objects
Introduction
This C# recipe shows how you can use EPPlus library to create an Excel file and populate the first worksheet from a list of C# objects
Ingredients
The recipe uses the EPPlus library version 4.5.3.3. This is the last version of EPPlus under the LGPL License (aka free for commercial uses). You can install it using Nuget Package manager:
Install-Package EPPlus -Version 4.5.3.3
C# Code Snippet
var path = @"C:\Temp\ExcelRecipes\Creating\";
var fileName = "populate_from_list.xlsx";
var fileInfo = new FileInfo(path + fileName);
using (var excelFile = new ExcelPackage(fileInfo))
{
// step 1: file requires at least one worksheet
excelFile.Workbook.Worksheets.Add("Sheet1");
// lets create a list of companies
var companies = new List<NasdaqCompany>()
{
new NasdaqCompany
{
Symbol = "TSLA", Name = "Tesla", Country = "USA", IpoYear = 2010, Sector = "Capital Goods",
Industry = "Auto Manufacturing"
},
new NasdaqCompany
{
Symbol = "NFLX", Name = "Netflix", Country = "USA", IpoYear = 2002, Sector = "Consumer Services",
Industry = "Consumer Electronics/Video Chains"
},
new NasdaqCompany
{
Symbol = "ZN", Name = "Zoom", Country = "USA", IpoYear = 2019, Sector = "Technology",
Industry = "Computer Software: Programming Data Processing"
},
};
// populate the first worksheet with the list of companies
var ws = excelFile.Workbook.Worksheets.First();
var newRange = ws.Cells["A1"].LoadFromCollection(companies, PrintHeaders: true);
// lets auto fit these columns
newRange.AutoFitColumns();
excelFile.Save();
}