Introduction

There are some popular libraries that can help us deal with Excel files, such as DotNetCore.NPOI, npoi and EPPlus .etc.
In this article, we will use EPPlus to import and export Excel files in ASP.NET Core. EPPlus is a .NET library that reads and writes Excel files using the Office Open XML format (.xlsx). EPPlus has no dependencies other than .NET.
Let's take a look at how to do that.


Preparations

Create a new ASP.NET Core Web API Application and install EPPlus via nuGet.
  1. Install-Package EPPlus -Version 4.5.2.1
Create two classes we need for this demo, one is UserInfo class that contains two properties.
  1. public class UserInfo
  2. {
  3. public string UserName { get; set; }
  4. public int Age { get; set; }
  5. }
The other one is DemoResponse which unifies the response structure.
  1. public class DemoResponse<T>
  2. {
  3. public int Code { get; set; }
  4. public string Msg { get; set; }
  5. public T Data { get; set; }
  6. public static DemoResponse<T> GetResult(int code, string msg, T data = default(T))
  7. {
  8. return new DemoResponse<T>
  9. {
  10. Code = code,
  11. Msg = msg,
  12. Data = data
  13. };
  14. }
  15. }
Adding a new Web API controller named EPPlusController, we will add import and export methods here.

Import

In the real world, import functionality is complex and it involves validation, applying business rules and finally saving it in the database. But to show you, will define an import handler method to read and return the data of the Excel file.
  1. [HttpPost("import")]
  2. public async Task<DemoResponse<List<UserInfo>>> Import(IFormFile formFile, CancellationToken cancellationToken)
  3. {
  4. if (formFile == null || formFile.Length <= 0)
  5. {
  6. return DemoResponse<List<UserInfo>>.GetResult(-1, "formfile is empty");
  7. }
  8. if (!Path.GetExtension(formFile.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
  9. {
  10. return DemoResponse<List<UserInfo>>.GetResult(-1, "Not Support file extension");
  11. }
  12. var list = new List<UserInfo>();
  13. using (var stream = new MemoryStream())
  14. {
  15. await formFile.CopyToAsync(stream, cancellationToken);
  16. using (var package = new ExcelPackage(stream))
  17. {
  18. ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
  19. var rowCount = worksheet.Dimension.Rows;
  20. for (int row = 2; row <= rowCount; row++)
  21. {
  22. list.Add(new UserInfo
  23. {
  24. UserName = worksheet.Cells[row, 1].Value.ToString().Trim(),
  25. Age = int.Parse(worksheet.Cells[row, 2].Value.ToString().Trim()),
  26. });
  27. }
  28. }
  29. }
  30. // add list to db ..
  31. // here just read and return
  32. return DemoResponse<List<UserInfo>>.GetResult(0, "OK", list);
  33. }
We have an Excel file named aa.xlsx, and the following screenshot shows the contents of it.
Using EPPlus To Import And Export Data In ASP.NET Core
We will import this file, and may get the following result.
Using EPPlus To Import And Export Data In ASP.NET Core

Export

There are two ways to export an Excel file.
  • Create a file and return the download link
  • Return the file directly
For the first way,
  1. private readonly IHostingEnvironment _hostingEnvironment;
  2. public EPPlusController(IHostingEnvironment hostingEnvironment)
  3. {
  4. this._hostingEnvironment = hostingEnvironment;
  5. }
  6. [HttpGet("export")]
  7. public async Task<DemoResponse<string>> Export(CancellationToken cancellationToken)
  8. {
  9. string folder = _hostingEnvironment.WebRootPath;
  10. string excelName = $"UserList-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";
  11. string downloadUrl = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, excelName);
  12. FileInfo file = new FileInfo(Path.Combine(folder, excelName));
  13. if (file.Exists)
  14. {
  15. file.Delete();
  16. file = new FileInfo(Path.Combine(folder, excelName));
  17. }
  18. // query data from database
  19. await Task.Yield();
  20. var list = new List<UserInfo>()
  21. {
  22. new UserInfo { UserName = "catcher", Age = 18 },
  23. new UserInfo { UserName = "james", Age = 20 },
  24. };
  25. using (var package = new ExcelPackage(file))
  26. {
  27. var workSheet = package.Workbook.Worksheets.Add("Sheet1");
  28. workSheet.Cells.LoadFromCollection(list, true);
  29. package.Save();
  30. }
  31. return DemoResponse<string>.GetResult(0, "OK", downloadUrl);
  32. }
After executing this method, we will get the link, and it will create a file in the wwwroot folder,
Using EPPlus To Import And Export Data In ASP.NET Core
Using EPPlus To Import And Export Data In ASP.NET Core
Opening this file, you may get the following content.
Using EPPlus To Import And Export Data In ASP.NET Core

For the second way,
  1. [HttpGet("exportv2")]
  2. public async Task<IActionResult> ExportV2(CancellationToken cancellationToken)
  3. {
  4. // query data from database
  5. await Task.Yield();
  6. var list = new List<UserInfo>()
  7. {
  8. new UserInfo { UserName = "catcher", Age = 18 },
  9. new UserInfo { UserName = "james", Age = 20 },
  10. };
  11. var stream = new MemoryStream();
  12. using (var package = new ExcelPackage(stream))
  13. {
  14. var workSheet = package.Workbook.Worksheets.Add("Sheet1");
  15. workSheet.Cells.LoadFromCollection(list, true);
  16. package.Save();
  17. }
  18. stream.Position = 0;
  19. string excelName = $"UserList-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";
  20. //return File(stream, "application/octet-stream", excelName);
  21. return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName);
  22. }
After executing this method, we will get the file directly.
Using EPPlus To Import And Export Data In ASP.NET Core
Here is the source code you can find in my GitHub page.

Summary

This short article shows how to use EPPlus library to import and export the Excel 2007+ file in ASP.NET Core simply. There are many other usages you can do with EPPlus, such as Cell styling, Charts. etc. We can visit its Github page for more information.