Search code examples
javatomcat7apache-poi

Probable fatal error:No fonts found-while setting sheet.autoSizeColumn


I am creating a program that writes information to an excel file using the apache poi..every thing working fine until i used

 sheet.autoSizeColumn(1);

after adding this code .i am getting a exception
java.lang.Error: Probable fatal error:No fonts found.

i researched about this and found that it is because of absence of fonts.if i comment the above code ,every thing works fine.my question is how the sheet.autoSizeColumn function is related with font . and also i need to install fonts,i am using Ubuntu 12.04.2 , tomcat 7, and java-6-openjdk-amd64 any help will be appreciated


Solution

  • The size of characters depends on which font is chosen. For instance, the width of the same phrase written with 10pt Arial and 10pt Times New Roman fonts is different. So, to calculate the width of the column apache-poi should know about the font you're using. Therefore, you should set the font for each cell you want to autosize. Here's an example:

    CellStyle cellStyle = workbook.createCellStyle();
    Font font = workbook.createFont();
    font.setFontHeight(14.0);
    //some additional font configuration
    cellStyle.setFont(font);
    //For each cell:
        cell.setStyle(cellStyle)
    

    Notice that you need to create cellStyle just one time, and then apply it to every cell that should have this style.