我正在使用“Apache POI”生成Excel报告。我有一个设计良好的Excel模板。我想通过将数据填充到模板的预定义位置来创建报告。也就是说,我不想关心报告的格式。这是否可能?您能给我一些指导吗?
我找到了答案。我可以使用Microsoft Excel中的“单元格命名”实用程序,然后使用以下代码定位单元格并执行操作。
CellReference[] crefs = this.getCellsByName(wb, cName);
// Locate the cell position
Sheet sheet = wb.getSheet(crefs[0].getSheetName());
Row row = sheet.getRow(crefs[0].getRow());
Cell cell = row.getCell(crefs[0].getCol());
// Write in data
cell.setCellValue(cellRegion.getContent());
"cName"是Microsoft Excel中预定义的单元格名称。
"您可以像加载其他XLS文件一样加载模板文件。然后对特定单元格进行所需更改,并将其写入另一个文件。
以下是一些示例代码:
加载文件
InputStream inputStream = new FileInputStream ("D:\\book_original.xls");
POIFSFileSystem fileSystem = new POIFSFileSystem (inputStream);
HSSFWorkbook workBook = new HSSFWorkbook (fileSystem);
做一些事情
HSSFSheet sheet1 = workBook.getSheetAt (0);
Iterator<Row> rows = sheet1.rowIterator ();
while (rows.hasNext ())
{
Row row = rows.next ();
// do stuff
if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
System.out.println ("Row No.: " + row.getRowNum ()+ " " + row.getCell(0).getNumericCellValue());
HSSFCell cell = row.createCell(0);
cell.setCellValue("100");
}
将输出写入文件
FileOutputStream fileOut1 = new FileOutputStream("D:\\book_modified.xls");
workBook.write(fileOut1);
fileOut1.close();