Efficiently Automating Excel File Creation and Download with EPPlus in C#: A Practical Guide for .NET Developers
Jawad Amir
Full-Stack | .NET | Angular | Microservices | AWS | Docker | +5 years of expertise
To download an Excel file in C# using the EPPlus library, you need to perform a few steps. EPPlus is a .NET library that reads and writes Excel files using the Office Open XML format (.xlsx). Below is a simplified example of how you might implement this:
Install-Package EPPlus
领英推荐
Here's an example of how the code might look:
using OfficeOpenXml;
using System.IO;
using System.Web.Mvc;
public ActionResult DownloadExcel()
{
// Setting the license context for EPPlus
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
// Create a new Excel package
using (var package = new ExcelPackage())
{
// Add a new worksheet to the empty workbook
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
// Add some sample data
worksheet.Cells["A1"].Value = "ID";
worksheet.Cells["B1"].Value = "Name";
worksheet.Cells["A2"].Value = 1;
worksheet.Cells["B2"].Value = "John Doe";
// Set the stream to save the file
var stream = new MemoryStream();
// Save the package to the stream
package.SaveAs(stream);
// Set the position of the stream to 0
stream.Position = 0;
// Return the stream as a file download
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "MyExcelFile.xlsx");
}
}
This is a basic example for a web application using ASP.NET MVC. Adjustments may be needed depending on the specifics of your application, such as the data source and the ASP.NET version you are using. If you're working in a different type of application (e.g., a console or a desktop app), the way you handle the file stream will differ.