Working with Excel files in .Net
Amir Doosti
.Net Software Engineer | 20+ Years of Expertise | C#, .NET, Microservices Architecture
Using Excel files in software applications is common for several reasons, as they provide a practical and versatile solution for managing, analyzing, and sharing data.?
There are many reason that you may want to add Excel manipulation capabilities in your software among them:
In this article I would like to talk about the available packages in .Net to work with Excel and I will briefly explain one of them.
You can find the complete source of the example in my GitHub in the link bellow:
Available packages and libraries to work with Excel
Here is a list of some packages and libraries for working with Excel files in .Net that I know.?
Open-Source packages
NPOI:
ClosedXML:
ExcelDataReader (Read-Only):
Commercial Libraries (For Enterprise Use)
Aspose.Cells:
Syncfusion XlsIO:
EPPlus:
For this article I’ve chosen EPPlus and I would like to have a close look to it.
EPPLus
As a developer using the EPPlus library, which is primarily used for reading from and writing to Excel files, you should understand its core concepts, key classes, and common use cases. EPPlus simplifies working with Excel documents in C# and .NET by providing a robust API for managing spreadsheets without requiring Excel to be installed on the system.
Main points about EPPlus:
Core Classes and Components in EPPlus:
1. ExcelPackage:
using (var package = new ExcelPackage(new FileInfo("path-to-file.xlsx")))
{
var worksheet = package.Workbook.Worksheets[0]; // Access first worksheet
// Work with data...
package.Save(); // Save the changes
}
2. ExcelWorkbook:
ExcelWorkbook workbook = package.Workbook;
3. ExcelWorksheet:
var worksheet = package.Workbook.Worksheets.Add("NewSheet");
worksheet.Cells[1, 1].Value = "Hello, World!";
4. ExcelRange:
worksheet.Cells["A1"].Value = "EPPlus";
worksheet.Cells[2, 1].Value = DateTime.Now;
5. ExcelCell:
领英推荐
6. ExcelTable:
var range = worksheet.Cells["A1:B10"];
worksheet.Tables.Add(range, "MyTable");
7. ExcelNamedRange:
var namedRange = package.Workbook.Names.Add("MyRange", worksheet.Cells["A1:A10"]);
8. ExcelChart:
var chart = worksheet.Drawings.AddChart("SalesChart", eChartType.ColumnClustered);
chart.SetPosition(5, 0, 5, 0); // Position of the chart
chart.Series.Add(worksheet.Cells["B2:B5"], worksheet.Cells["A2:A5"]); // Data for chart
9. ExcelStyles:
worksheet.Cells["A1"].Style.Font.Bold = true;
worksheet.Cells["A1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells["A1"].Style.Fill.BackgroundColor.SetColor(Color.LightBlue);
10. ExcelComment:
worksheet.Cells["A1"].AddComment("This is a comment", "AuthorName");
Additional Features of EPPlus:
1. Formulas:
worksheet.Cells["A3"].Formula = "SUM(A1:A2)";
2. Data Validation:
var validation = worksheet.DataValidations.AddListValidation("A1");
validation.Formula.Values.Add("Option 1");
validation.Formula.Values.Add("Option 2");
3. Conditional Formatting:
var condition = worksheet.ConditionalFormatting.AddThreeColorScale(worksheet.Cells["A1:A10"]);
4. Pivot Tables:
var pivotTable = worksheet.PivotTables.Add(worksheet.Cells["D3"], worksheet.Cells["A1:B10"], "PivotTable");
5. Encryption and Protection:
package.SaveAs(new FileInfo("encrypted.xlsx"), "password");
Example
In the following sample, I tried to show you some of the features of EPPlus like reading, writing, styling, creating a chart, working with formulas and managing worksheets. You can find complete code in my github.
Before running this example, ensure you have installed the EPPlus NuGet package in your project:
111Install-Package EPPlus
Code:
using OfficeOpenXml.Drawing.Chart;
using OfficeOpenXml.Style;
using OfficeOpenXml;
using System.Drawing;
Console.WriteLine("Working with Excel file ...");
// License requirement for EPPlus 5 and above
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
// Define the file path for saving the Excel file
var filePath = new FileInfo("EPPlusExample.xlsx");
if (File.Exists(filePath.FullName))
File.Delete(filePath.FullName);
using (var package = new ExcelPackage(filePath))
{
Console.WriteLine("Creating Excel File ...");
// Create a new worksheet
var worksheet = package.Workbook.Worksheets.Add("Employee Data");
// Add some headers
worksheet.Cells["A1"].Value = "ID";
worksheet.Cells["B1"].Value = "Name";
worksheet.Cells["C1"].Value = "Position";
worksheet.Cells["D1"].Value = "Salary";
worksheet.Cells["E1"].Value = "Tax";
worksheet.Cells["F1"].Value = "Net Salary";
// Apply some styling to the headers
using (var range = worksheet.Cells["A1:F1"])
{
range.Style.Font.Bold = true;
range.Style.Fill.PatternType = ExcelFillStyle.Solid;
range.Style.Fill.BackgroundColor.SetColor(Color.LightBlue);
range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
range.Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);
}
// Add employee data
var employees = new[]
{
new { Id = 1, Name = "John Doe", Position = "Manager", Salary = 5500 },
new { Id = 2, Name = "Jane Smith", Position = "Engineer", Salary = 4500 },
new { Id = 3, Name = "Sam Brown", Position = "Technician", Salary = 3000 }
};
int row = 2;
foreach (var employee in employees)
{
worksheet.Cells[row, 1].Value = employee.Id;
worksheet.Cells[row, 2].Value = employee.Name;
worksheet.Cells[row, 3].Value = employee.Position;
worksheet.Cells[row, 4].Value = employee.Salary;
// Add a formula for tax (10% of salary) and net salary
worksheet.Cells[row, 5].Formula = $"D{row}*0.1";
worksheet.Cells[row, 6].Formula = $"D{row}-E{row}";
row++;
}
// Apply some currency format to salary, tax, and net salary columns
using (var range = worksheet.Cells["D2:F4"])
{
range.Style.Numberformat.Format = "$#,##0.00";
range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
// AutoFit columns for better display
worksheet.Cells.AutoFitColumns();
// Add a chart to represent salary data
var chart = worksheet.Drawings.AddChart("SalaryChart", eChartType.ColumnClustered);
chart.Title.Text = "Employee Salary Data";
chart.SetPosition(6, 0, 1, 0);
chart.SetSize(600, 300);
// Add series to the chart
var series = chart.Series.Add(worksheet.Cells["D2:D4"], worksheet.Cells["B2:B4"]);
series.Header = "Salary";
// Save the workbook
package.Save();
Console.WriteLine("Excel file created successfully!");
Console.WriteLine($"File Path: {filePath.FullName}");
}
// Read the data back from the file
using (var package = new ExcelPackage(filePath))
{
var worksheet = package.Workbook.Worksheets["Employee Data"];
Console.WriteLine("Reading from the Excel file...");
for (int row = 2; row <= 4; row++)
{
var id = worksheet.Cells[row, 1].Text;
var name = worksheet.Cells[row, 2].Text;
var position = worksheet.Cells[row, 3].Text;
var salary = worksheet.Cells[row, 4].Text;
Console.WriteLine($"ID: {id}, Name: {name}, Position: {position}, Salary: {salary}");
}
}
Conclusion
As a developer, being able to work with Excel files from within your program can be very useful and reassuring. EPPlus offers a wide range of functionality for working with Excel files programmatically in C#. Understanding its core classes like ExcelPackage, ExcelWorksheet, and ExcelRange will allow you to efficiently create, modify, and analyze Excel documents within your .NET applications.
#csharp #dotnet #excel #spreadsheet #eeplus #npoi #closedxml #exceldatareader