To create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office, you can make use of third-party libraries that provide Excel manipulation capabilities. One popular library is EPPlus, which is a free open-source library for creating and manipulating Excel files in C#. Here's how you can use EPPlus to create an Excel file:
Install EPPlus: Use NuGet Package Manager to install the EPPlus library into your C# project. You can do this by right-clicking on your project in Visual Studio, selecting "Manage NuGet Packages," and searching for "EPPlus" to install it.
Import EPPlus namespace: In your C# code file, import the EPPlus namespace using the following statement:
using OfficeOpenXml;
- Create a new Excel file and add data: Use the EPPlus library to create an Excel package, add worksheets, and populate them with data. Here's an example that creates a simple Excel file with a single worksheet and some data:
// Create a new Excel package
using (ExcelPackage package = new ExcelPackage())
{
// Add a new worksheet
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
// Add data to the worksheet
worksheet.Cells["A1"].Value = "Hello";
worksheet.Cells["B1"].Value = "World!";
// Save the Excel file
package.SaveAs(new FileInfo("path_to_your_excel_file.xlsx"));
}
In the above code, replace "path_to_your_excel_file.xlsx" with the desired file path and name for your Excel file. This will create an Excel file with the specified data.
- Optional: Save as .XLS format (Excel 97-2003): By default, EPPlus saves the Excel file in .XLSX format (Excel 2007 and later). If you specifically need to save it in .XLS format (Excel 97-2003), you can use a different library like NPOI, which supports older Excel formats.
By following these steps and utilizing EPPlus or similar libraries, you can create Excel files (.XLSX format) in C# without the need to install Microsoft Office.
Comments
Post a Comment