Generate Excel files with NPOI in C#

First, you’ll need to add the NPOI NuGet package to your project. You can do this by right-clicking on your project in the Solution Explorer and selecting “Manage NuGet Packages.” Search for “NPOI” and install the latest version.

Next, you can use the following code to create a new Excel file and write some data to it:

using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

// Create a new Excel workbook
IWorkbook workbook = new XSSFWorkbook();

// Create a new sheet
ISheet sheet = workbook.CreateSheet("Sheet1");

// Create a header row
IRow headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("Name");
headerRow.CreateCell(1).SetCellValue("Age");

// Write some data to the sheet
IRow dataRow = sheet.CreateRow(1);
dataRow.CreateCell(0).SetCellValue("John");
dataRow.CreateCell(1).SetCellValue(30);

dataRow = sheet.CreateRow(2);
dataRow.CreateCell(0).SetCellValue("Jane");
dataRow.CreateCell(1).SetCellValue(25);

// Save the workbook to a file
using (FileStream stream = new FileStream("output.xlsx", FileMode.Create, FileAccess.Write))
{
    workbook.Write(stream);
}

This code creates a new Excel workbook, adds a sheet called “Sheet1”, creates a header row with two columns (“Name” and “Age”), and writes some data to the sheet. Finally, the workbook is saved to a file called “output.xlsx”.

You can customize this code to suit your specific requirements, such as adding more sheets, formatting the cells, and so on.