开发者

Preserve images in Excel headers using Apache POI

I am trying to generate Excel reports using Apache POI 3.6 (latest).

Since POI has limited support for header and footer generation (text only), I decided to start from a blank excel file with the header already prepared and fill the Excel cells using POI (cf. question 714172).

Un开发者_StackOverflow社区fortunately, when opening the workbook with POI and writing it immediately to disk (without any cell manpulation), the header seems to be lost.

Here is the code I used to test this behavior:

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


The headers of the Excel file are preserved as long as those headers are supported in Excel 97-2003. For example, images are supported (I just tried it), but colored text is not.

The tricky part of this is that your Excel template file "dump.xls" must be in Excel 97-2003 format. Please note: this is not the file extension, but the actual contents of the file. The newest Excel will happily save the newest formatting in a .xls file, which POI cannot read.

To test this, save your Excel file as an .xls file. Important - If you receive a compatibility warning, then you must click the "Correct" link in the dialog to correct the Excel. Just clicking Proceed makes the Excel file invalid to POI.

Once you have a real .xls file (with compatible contents) then your code works. I just tested it myself:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜