使用Apache POI保存Excel报头中的图像

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

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

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

这是我用来testing这个行为的代码:

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 } } } } } 

 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); 

只要Excel 97-2003支持这些头文件,Excel文件的头文件将被保留。 例如,支持的图像(我只是试了一下),但彩色文字不支持。

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

要testing这个,请将您的Excel文件保存为.xls文件。 重要 – 如果收到兼容性警告,则必须单击对话框中的“更正”链接以更正Excel。 只需点击继续即可使Excel文件对POI无效。

一旦你有一个真正的.xls文件(与兼容的内容),那么你的代码工作。 我只是自己testing一下:

 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); } }