Search code examples
apache-poiexport-to-excelexcel-2003poi-hssf

apache-poi inserting filename in header or footer


I'm using the apache poi library (poi-3.8-20120326.jar)

How can I add the filename in the footer of an xls (hssf) document?

My approach is the following:

final static public String FILE_NAME = "&[File]";
public static void insertFilename(Sheet sheet) {
    sheet.getFooter().setLeft(FILE_NAME);
}

The Problem is, the Microsoft Excel 2003 displays

File]

If I open the Footer-editor, click in the field, change nothing, and save--it works. Editor shows it as

&[File]

Is there a workaround or a dirty trick to avoid this?

Thank you


Solution

  • It may look like "&[File]" in Excel, but that's not how it's stored internally. You're using HSSF for your .xls file, so use the following static HeaderFooter method to get the internal Excel code for the filename:

    import org.apache.poi.hssf.usermodel.HeaderFooter;
    
    String fileIndicator = HeaderFooter.file();
    

    A quick look at the source code determines that the internal code is the string "&F".

    If someone is using XSSF for a .xlsx file, then there is no corresponding file method. However, the documentation for XSSFHeaderFooter indicates that you can use the string "&F" directly.