NPOI是一个C#中操作EXCEL比较方便的库 , 在已有报表模板情况下,将数据导出到报表模板并存储为新报表文件步骤如下:
- 打开报表模板
- 写入数据
- 保存报表文件
- 获取行
- 判定行是否为空,若为空创建新行并设定行内单元格样式
- 写入数据
IWorkbook workbook = new XSSFWorkbook("报表模板.xlsx");ISheet sheet = workbook.GetSheetAt(0);IRow row;int rowCount = 0;while (sdr.Read()){//跳过表头int rowIdx = rowCount2;int cellIdx = 0;row = sheet.GetRow(rowIdx);//超出预留数据行if (null == row){row = sheet.CreateRow(rowIdx);//源样式行IRow rowFirstData = https://www.itzhengshu.com/excel/sheet.GetRow(3);//设定Cell边框for (int i = 0; i < 8;i){ICell cell = row.CreateCell(i);ICell cellSrc = rowFirstData.GetCell(i);cell.CellStyle = cellSrc.CellStyle;}row.RowStyle = rowFirstData.RowStyle;}//序号row.GetCell(cellIdx).SetCellValue(rowCount1);//.....//合格判定bool isOk = Convert.ToBoolean(sdr["Judge"]);row.GetCell(cellIdx).SetCellValue(isOk ? "是" : "否");rowCount;}//保存到新文件using (var fsDst = new FileStream(sTargetFile, FileMode.Create, FileAccess.Write)){workbook.Write(fsDst);}