How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

 

To create Excel (.XLS and .XLSX) files in C# without installing Microsoft Office, you can use a third-party library like EPPlus for .XLSX or NPOI for .XLS. In this example, I'll show you how to create an XLSX file using EPPlus.

Using EPPlus to Create an XLSX File:

  1. Create a new C# console application project in Visual Studio or your preferred IDE.

  2. Install the EPPlus NuGet package, which provides easy-to-use features for working with Excel files:

    mathematica
  • Install-Package EPPlus
  • Write the code to create an Excel file. Here's an example:

    csharp
    1. using OfficeOpenXml; // Import the EPPlus namespace class Program { static void Main(string[] args) { // Create a new Excel package using (var package = new ExcelPackage()) { // Add a new worksheet to the Excel package var worksheet = package.Workbook.Worksheets.Add("Sheet1"); // Add data to the worksheet worksheet.Cells["A1"].Value = "Name"; worksheet.Cells["B1"].Value = "Age"; worksheet.Cells["A2"].Value = "John"; worksheet.Cells["B2"].Value = 30; worksheet.Cells["A3"].Value = "Alice"; worksheet.Cells["B3"].Value = 25; // Save the Excel package to a file var file = new System.IO.FileInfo("example.xlsx"); package.SaveAs(file); } Console.WriteLine("Excel file created successfully."); } }

      In this code, we use EPPlus to create a new Excel package, add a worksheet, populate it with data, and save it as "example.xlsx."

    2. Run the application. After it executes, you'll find the "example.xlsx" Excel file in your project directory with the specified data.

    EPPlus supports a wide range of Excel features, including formatting, formulas, and more. You can customize the Excel file as needed for your specific requirements.

    If you need to create XLS files (Excel 97-2003 format), you can use the NPOI library, which is also available via NuGet. The usage is similar, but you'll work with different classes and namespaces specific to NPOI.

    Remember to handle any potential exceptions that may occur during file operations, and be sure to properly manage file paths and names based on your project's requirements.

    Comments