0

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());
        }
Van_Cleff
  • 842
  • 6
  • 14

1 Answers1

0

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, i.e, 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
}
Van_Cleff
  • 842
  • 6
  • 14
  • Original: 4309Resized: 4298Original: 4053Resized: 4070Original: 3498Resized: 3501Original: 4309Resized: 4298Original: 4010Resized: 4010 – CoffeeCodingSweden Mar 11 '19 at 19:56
  • Did you even read my code? I don't think you understand the issue I'm facing? – CoffeeCodingSweden Mar 11 '19 at 19:58
  • Your' resize is working just fine, compare the original and resized value from your output :) – Van_Cleff Mar 11 '19 at 19:58
  • your auto-size is working as per the output you provided. what else is not wrking? – Van_Cleff Mar 11 '19 at 20:01
  • Well even if the autoSize is working, this is definitely not a solution for the problem! So, the actual .xls document is not showing the data I just added. It clearly isn't resized for optimal view! So even if the autoSize is working, it's not! The heading is not autoSized, and not the new rows that's added each session. – CoffeeCodingSweden Mar 11 '19 at 20:04
  • It would be nice if you just update the tile of this question and put `nothing is working for styling the xls` Also if the original cell width is small and the resized one is almost close to it you won't see it visually. I hope you understand. Also it's written clearly in the answer it's not a solution just validating output from user. – Van_Cleff Mar 11 '19 at 20:10
  • I see! I tried with changing some stuff, and it looks like the problem is where the font is added. Bold, Size and FontName is causing some problem! Do you have any further suggestions on how to solve this? – CoffeeCodingSweden Mar 12 '19 at 06:45
  • Can you check once, what type is your excel by loading it as workbook like this and checking type `Workbook wb = WorkbookFactory.create(myExcelFile);` – Van_Cleff Mar 12 '19 at 07:19
  • If I go with "Workbook wb = ...." how do I create the stuff with cellStyle and font? It won't compile with HSSF references if I go with Workbook? – CoffeeCodingSweden Mar 12 '19 at 07:55
  • You could keep it the way it is and just do a check at first if the file is compatible for HSSF operations. – Van_Cleff Mar 12 '19 at 07:57
  • "Cannot find symbol SXSSFWorkbook, XSSFWorkbook" – CoffeeCodingSweden Mar 12 '19 at 07:59
  • see it here https://stackoverflow.com/questions/32456595/error-cannot-find-symbol-using-apache-poi – Van_Cleff Mar 12 '19 at 08:19