tags:

views:

293

answers:

1

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

Unfortunately, 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
        }
      }
    }
  }
}
A: 

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

zaib mughal
This works for creating a new header in a blank sheet but what I'm trying to do is to preserve the header of an existing sheet loaded from a file. Thanks for the pointer though!
dimdm