1

我正在尝试使用 Apache POI 3.6(最新)生成 Excel 报告。

由于 POI 对页眉和页脚生成的支持有限(仅限文本),我决定从一个已准备好页眉的空白 Excel 文件开始,并使用 POI 填充 Excel 单元格(参见问题714172)。

不幸的是,当使用 POI 打开工作簿并立即将其写入磁盘(没有任何单元格操作)时,标题似乎丢失了。

这是我用来测试此行为的代码:

public final class ExcelWorkbookCreator {

  public static void main(String[] args) {
    FileOutputStream outputStream = null;
    try {
      outputStream = new FileOutputStream(new File("dump.xls"));
      InputStream inputStream = ExcelWorkbookCreator.class.getResourceAsStream("report_template.xls");
      HSSFWorkbook workbook = new HSSFWorkbook(inputStream, true);
      workbook.write(outputStream);
    } catch (Exception exception) {
      throw new RuntimeException(exception);
    } finally {
      if (outputStream != null) {
        try {
          outputStream.close();
        } catch (IOException exception) {
          // Nothing much to do
        }
      }
    }
  }
}
4

2 回答 2

1
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet    sheet    = new HSSFSheet();

Header header = sheet.getHeader() //get header from workbook's sheet
header.setCenter(HSSFHeader.font("COURIER", "Normal")+ HSSFHeader.fontSize((short) 15) + "Hello world" +new Date()); // set header with desire font style 

FileOutputStream fileOut = new FileOutputStream("C:\\book.xls");
workbook.write(fileOut);       
于 2010-04-21T11:19:53.060 回答
1

只要 Excel 97-2003 支持这些标头,就会保留 Excel 文件的标头。例如,支持图像(我刚刚尝试过),但不支持彩色文本。

棘手的部分是您的 Excel 模板文件“dump.xls”必须是 Excel 97-2003 格式。请注意:这不是文件扩展名,而是文件的实际内容。最新的 Excel 很乐意将最新的格式保存在 POI 无法读取的 .xls 文件中。

要对此进行测试,请将 Excel 文件另存为 .xls 文件。重要- 如果您收到兼容性警告,则必须单击对话框中的“更正”链接以更正 Excel。只需单击继续,Excel 文件对 POI 无效。

一旦你有了一个真正的 .xls 文件(具有兼容的内容),你的代码就可以工作了。我自己测试了一下:

public static void main(String[] args) throws Exception {
  try (FileInputStream fis = new FileInputStream("./report_template.xls"); 
      FileOutputStream fos = new FileOutputStream("./dump.xls")) {
    HSSFWorkbook wb = new HSSFWorkbook(fis);
    wb.write(fos); 
  }
}
于 2013-06-18T11:36:23.833 回答