简体   繁体   中英

Can't see styling changes in POI Apache Excel .xls document

I wonder how to autoSize the columns in Excel doc. When I run this code it don't do a jack shit in the document. And I can't really find out what is wrong!

Literally, nothing is autoSized in the document. I don't understand what could be wrong!! Very frustrating problem..

Also, I would be happy to get some feedback on the code, do I practice bad coding habits?

Thanks!

Here is my code:

try
        {
            FileInputStream myxls = new FileInputStream("/Users/xxxxxx/Desktop/tryIt.xls");
            HSSFWorkbook workbook = new HSSFWorkbook(myxls);
            HSSFSheet sheet = workbook.getSheetAt(0);
            int lastRow=sheet.getLastRowNum();


        HSSFCellStyle styleRowHeading = workbook.createCellStyle();
        HSSFCellStyle style = workbook.createCellStyle();

        HSSFFont fontRowHeading = workbook.createFont();
        HSSFFont font = workbook.createFont();

        fontRowHeading.setBold(true);
        fontRowHeading.setFontName(HSSFFont.FONT_ARIAL);
        fontRowHeading.setFontHeightInPoints((short) 14);

        styleRowHeading.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
        styleRowHeading.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        styleRowHeading.setBorderTop(BorderStyle.MEDIUM);
        styleRowHeading.setBorderBottom(BorderStyle.MEDIUM);
        styleRowHeading.setBorderLeft(BorderStyle.MEDIUM);
        styleRowHeading.setBorderRight(BorderStyle.MEDIUM);
        styleRowHeading.setFont(fontRowHeading);

        font.setFontName(HSSFFont.FONT_ARIAL);
        font.setFontHeightInPoints((short)12);

        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderTop(BorderStyle.MEDIUM);
        style.setBorderBottom(BorderStyle.MEDIUM);
        style.setBorderLeft(BorderStyle.MEDIUM);
        style.setBorderRight(BorderStyle.MEDIUM);
        style.setFont(font);

        // Create heading

        if(lastRow <=0){
        Row rowHeading = sheet.createRow(lastRow);
        rowHeading.createCell(0).setCellValue("TEST1");
        rowHeading.createCell(1).setCellValue("TEST2");
        rowHeading.createCell(2).setCellValue("TEST3");
        rowHeading.createCell(3).setCellValue("TEST4");

        for(int i = 0; i < 4; i++){                
            rowHeading.getCell(i).setCellStyle(styleRowHeading);
        }
        }

        Row row = sheet.createRow(++lastRow);

        int i = 0;

        org.apache.poi.ss.usermodel.Cell cellId = row.createCell(i);
        org.apache.poi.ss.usermodel.Cell cellId1 = row.createCell(i+=1);
        org.apache.poi.ss.usermodel.Cell cellId2 = row.createCell(i+=1);
        org.apache.poi.ss.usermodel.Cell cellId3 = row.createCell(i+=1);

        cellId.setCellValue(todaysDate);
        cellId1.setCellValue(txt_year.getText());
        cellId2.setCellValue(txt_correct.getText());
        cellId3.setCellValue(txt_errors.getText());

        cellId.setCellStyle(style);
        cellId1.setCellStyle(style);
        cellId2.setCellStyle(style);
        cellId3.setCellStyle(style);


        // Autofit

        for(int w = 0; w < 5; w++){
            sheet.autoSizeColumn(w);
        }

        myxls.close();

        FileOutputStream output_file =new FileOutputStream(new File("/Users/xxxx/Desktop/tryIt.xls"));
        //write changes
        workbook.write(output_file);
        output_file.close();
        System.out.println("SUCCESSSSSSSSS!");


        }catch(Exception e){
            System.out.println(e.getMessage());
        }

I assume HSSFCellStyle might be causing issues here, could you change to CellStyle and check once if you see any formatting changes:

CellStyle style=null;
XSSFFont defaultFont= wb.createFont();
defaultFont.setFontHeightInPoints((short)10);
defaultFont.setFontName("Arial");
defaultFont.setColor(IndexedColors.BLACK.getIndex());
defaultFont.setBold(false);
defaultFont.setItalic(false);

XSSFFont font= wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("Arial");
font.setColor(IndexedColors.WHITE.getIndex());
font.setBold(true);
font.setItalic(false);

style=row.getRowStyle();
style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFont(font);

Key things to keep in mind:

Let's understand the basic difference between HSSFWorkbook and XSSFWorkbook

  • HSSFWorkbook : This class has methods to read and write Microsoft Excel files in .xls format.

  • XSSFWorkbook : This class has methods to read and write Microsoft Excel and OpenOffice xml files in .xls or .xlsx format.

  • SXSSF : it is an API-compatible streaming extension of XSSF to be used when very large spreadsheets have to be produced, and heap space is limited

Workbook

This is the super-interface of all classes that create or maintain Excel workbooks. It belongs to the org.apache.poi.ss.usermodel package and both the above mentioned XSSF , HSSF and SXSSF are implementations of WORKBOOK

Hence, my suggestion would be to until-unless utmost necessary, ie, you need a specific feature for xlsx or xls, just go with the workbook implementation

Most of the styling changes are hit and trial. You need to keep digging iterating with to finally find what you need.


Suggestions:

If you code for just HSSF via HSSFWorkbook, you can only work with .xls files. I'd suggest you go for the common ones wherever possible ( workbook )

Your loading code should be something like:

 Workbook wb = WorkbookFactory.create(new File("test.xls"));
 Sheet s = wb.getSheetAt(0);
 ....

Now, it will auto-detect the type of the file and give you back a working object for either .xls or .xlsx based on what it finds. Also, wherever possible try to keep the styling and designing parts generic and version independent. That way the same code could be re-used for both formats.

If you need to have any specific feature which require either XSSF or HSSF and can't use just the Workbook then do a check for the type first like this:

Workbook wb = WorkbookFactory.create(myExcelFile);
Then you can check the exact type created by the factory:

if (wb instanceof HSSFWorkbook) {
    // do whatever
} else if (wb instanceof SXSSFWorkbook) {
    // do whatever
} else if (wb instanceof XSSFWorkbook) {
    // do whatever
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM