To create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office, you can make use of third-party libraries that provide support for working with Excel files. One such popular library is EPPlus. Here’s an example of how you can use EPPlus to create an Excel file:
1. Install the EPPlus NuGet package in your C# project. You can do this by right-clicking on your project in Visual Studio, selecting “Manage NuGet Packages,” searching for “EPPlus,” and clicking on “Install.”
2. Once you have installed EPPlus, you can start using it in your code. First, import the necessary namespaces:
using OfficeOpenXml;
using OfficeOpenXml.Style;
3. Next, you can create a new Excel file and populate it with data. Here’s an example that creates a simple Excel file with a single worksheet and writes some values to it:
// Create a new Excel package
using (var package = new ExcelPackage())
{
// Add a new worksheet
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
// Write some values to the worksheet
worksheet.Cells["A1"].Value = "Name";
worksheet.Cells["B1"].Value = "Age";
worksheet.Cells["A2"].Value = "John Doe";
worksheet.Cells["B2"].Value = 30;
worksheet.Cells["A3"].Value = "Jane Smith";
worksheet.Cells["B3"].Value = 25;
// Save the Excel package to a file
FileInfo fileInfo = new FileInfo("path/to/your/file.xlsx");
package.SaveAs(fileInfo);
}
4. Replace "path/to/your/file.xlsx"
with the desired file path and name where you want to save the Excel file.
5. When you run this code, it will create an Excel file with the specified data at the specified file path.
Note that EPPlus supports both the older .xls format and the newer .xlsx format. The code example above saves the file as .xlsx. If you want to save it as .xls, you can change the file extension in the file path and use the ExcelPackage.SaveAs
overload that accepts a ExcelSaveType
parameter.
EPPlus provides many more features and options for working with Excel files, such as formatting, formulas, styling, and more. You can refer to the EPPlus documentation for further information and examples: https://github.com/JanKallman/EPPlus