在C#中使用NPOI合并单元格的步骤如下:
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; //如果是xlsx文件
using NPOI.HSSF.UserModel; //如果是xls文件
IWorkbook workbook = new XSSFWorkbook(); //如果是xlsx文件
//IWorkbook workbook = new HSSFWorkbook(); //如果是xls文件
ISheet sheet = workbook.CreateSheet("Sheet1");
int firstRow = 1;
int lastRow = 3;
int firstCol = 1;
int lastCol = 4;
CellRangeAddress region = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
sheet.AddMergedRegion(region);
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;
注意:合并单元格后,只需要设置合并范围内的第一个单元格的样式即可。
using (FileStream fs = new FileStream("output.xlsx", FileMode.Create))
{
workbook.Write(fs);
}
以上就是使用NPOI合并单元格的基本步骤,根据实际需要,可以根据自己的需求进行调整和扩展。