NPOI用法。

1、读入模板excel

FileStream file = new FileStream(@"E:/数字县区/东源县/东源地灾地矿信息管理系统/其他文件/地灾导出excel模板test.xls", FileMode.Open, FileAccess.Read);

hssfworkbook = new HSSFWorkbook(file);

2、定义cellstyle。如果要实现自动换行,且有边框,必须先设置borderstyle,再设置wraptext,最后设置alignment。(注:先设置alignment再设置wraptext会导致alignment失效)

ISheet sheet1 = hssfworkbook.GetSheet("Sheet1");
//create cell on rows, since rows do already exist,it's not necessary to create rows again.
//sheet1.GetRow(1).GetCell(1).SetCellValue(200200);
ICellStyle blackBorder = hssfworkbook.CreateCellStyle();
blackBorder.BorderBottom = BorderStyle.Thin;
blackBorder.BorderLeft = BorderStyle.Thin;
blackBorder.BorderRight = BorderStyle.Thin;
blackBorder.BorderTop = BorderStyle.Thin;
blackBorder.BottomBorderColor = HSSFColor.Black.Index;
blackBorder.LeftBorderColor = HSSFColor.Black.Index;
blackBorder.RightBorderColor = HSSFColor.Black.Index;
blackBorder.TopBorderColor = HSSFColor.Black.Index;
blackBorder.WrapText = true;
blackBorder.Alignment = HorizontalAlignment.Center;
blackBorder.VerticalAlignment = VerticalAlignment.Center;

3、批量设置region的cellstyle。通过for循环语句实现,先createrow().createcell().setvalue()。再getrow().getcell().cellstyle。(注:cell的位置(i,j)根据左上角格子为(0,0)开始算)

sheet1.CreateRow(2).CreateCell(16).SetCellValue("丘国文 13435529188 ");
sheet1.GetRow(2).GetCell(16).CellStyle = blackBorder;

循环中不能直接在最底层循环使用createrow语句,会导致清除之前的row。如下语句是错误的:

for (int i = 2; i <= 12; i++)
{
for (int j = 1; j <= 16; j++)
{
sheet1.CreateRow(i).CreateCell(j).SetCellValue("黎王忠 13829300556 丘国文 13435529188 ");
sheet1.GetRow(i).GetCell(j).CellStyle = blackBorder;
}
}

应将createrow放到上一层,createcell放到最底层。如下:

for (int i = 2; i <= 12; i++)
{
IRow currentRow = sheet1.CreateRow(i);
for (int j = 1; j <= 16; j++)
{
currentRow.CreateCell(j).SetCellValue("黎王忠 13829300556 丘国文 13435529188 ");
sheet1.GetRow(i).GetCell(j).CellStyle = blackBorder;
}
}

原文地址:https://www.cnblogs.com/xlyg-14/p/4617953.html