首页 文章

使用Apache POI在Excel标头中保留图像

提问于
浏览
1

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

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

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

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

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

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

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

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

    要对此进行测试,请将Excel文件另存为.xls文件 . 重要信息 - 如果收到兼容性警告,则必须单击对话框中的"Correct"链接以更正Excel . 只需单击Proceed即可使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); 
      }
    }
    

相关问题