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