How to merge cells in C# using NPOI?
The steps for merging cells using NPOI in C# are as follows:
- Firstly, import the NPOI namespace.
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; //如果是xlsx文件
using NPOI.HSSF.UserModel; //如果是xls文件
- Create a workbook object and a worksheet object.
IWorkbook workbook = new XSSFWorkbook(); //如果是xlsx文件
//IWorkbook workbook = new HSSFWorkbook(); //如果是xls文件
ISheet sheet = workbook.CreateSheet("Sheet1");
- Specify the range of cells to merge:
int firstRow = 1;
int lastRow = 3;
int firstCol = 1;
int lastCol = 4;
- calling the method to merge cells:
CellRangeAddress region = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
sheet.AddMergedRegion(region);
- Set the style of merged cells.
ICellStyle style = workbook.CreateCellStyle();
style.Alignment = HorizontalAlignment.Center;
style.VerticalAlignment = VerticalAlignment.Center;
IRow row = sheet.GetRow(firstRow);
ICell cell = row.GetCell(firstCol);
cell.CellStyle = style;
Please note that after merging cells, only the style of the first cell within the merged range needs to be set.
- Save the workbook before exiting.
using (FileStream fs = new FileStream("output.xlsx", FileMode.Create))
{
workbook.Write(fs);
}
The above are the basic steps to merge cells using NPOI. Based on your actual needs, you can adjust and expand according to your own requirements.