java 通过从模板编程创建 Excel 报告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3666011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create Excel reports by programming from templates
提问by Sefler
I'm using "Apache POI" to generate Excel report. I've a well designed Excel template. I want to create a report by filling the data into predefined locations of the template. That is to say, I do not want to care about the formats of the report. Is that possible? Could you give me some instructions?
我正在使用“Apache POI”来生成 Excel 报告。我有一个精心设计的 Excel 模板。我想通过将数据填充到模板的预定义位置来创建报告。也就是说,我不想关心报告的格式。那可能吗?你能给我一些指示吗?
回答by Sefler
I got my answer. I can use the "Cell Naming" utility in Microsoft Excel and then use the following code to locate the cell and do something.
我得到了答案。我可以使用 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" is the cell's name predefined in Microsoft Excel.
“cName”是 Microsoft Excel 中预定义的单元格名称。
回答by wyz
You can have a look at jXLS, I think that's what you are looking for.
你可以看看 jXLS,我认为这就是你要找的。
It takes a Excel as template and you can write a Java app to fill the data:
它以 Excel 为模板,您可以编写一个 Java 应用程序来填充数据:
回答by JoseK
You can load you template file like any other XLS. And then make the changes you want to the specific cells and write it out into another file.
您可以像加载任何其他 XLS 一样加载模板文件。然后对特定单元格进行所需的更改并将其写入另一个文件。
Some sample code:
一些示例代码:
Load file
加载文件
InputStream inputStream = new FileInputStream ("D:\book_original.xls");
POIFSFileSystem fileSystem = new POIFSFileSystem (inputStream);
HSSFWorkbook workBook = new HSSFWorkbook (fileSystem);
do stuff
做东西
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");
}
Write the output to a file
将输出写入文件
FileOutputStream fileOut1 = new FileOutputStream("D:\book_modified.xls");
workBook.write(fileOut1);
fileOut1.close();