Home » excel » java – Autosize column width using poi

java – Autosize column width using poi

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am appending data to the existing excel using POI. But on appending the data, the excel headers which are already present before the editing are compressed to small areas. Can someone please suggest me how to avoid this? I have applied even autoSize after appending data, but of no use.

FileInputStream inputStream = new FileInputStream(new File("dataexcel.xlsx"));

    XSSFWorkbook workbook = new XSSFWorkbook(intputStream);
    XSSFSheet sheet = workbook.getSheetAt(0);
    int rowNum = sheet.getPhysicalNumberOfRows();

                    int cellNum = 1;
                    Row lastRow = sheet.createRow(rowNum);

    for(int i =0 ; i<7; i++)
    {
                    Cell cell = lastRow.createCell(cellNum++);
                    cell.setCellValue(value);
                    cell.setCellStyle(generalStyle);
    }

Suppose the headers has a long text like "This is very long text" and appending the 7 values(2,3,1,7,4,6,5) to the existing excel in each cell to the next row like above. Then the enitre columns’ widths shrink to the values of these single digits and the headers’ text is almost invisible until it is expanded manually.

How to&Answers:

Use autoSizeColumn() method?

Example Your Sheet as below

+----------+----------+----------+-------------+
| Column A | Column B | Column C | Column D    |
+----------+----------+----------+-------------+
|   xxx    |    xxx   |This is very long text  |
|          |          |          |             |
+----------+----------+----------+-------------+

If so, make auto column size for Column c, sheet.autoSizeColumn(2);. Result will be

+----------+----------+------------------------+-------------+
| Column A | Column B | Column C               | Column D    |
+----------+----------+------------------------+-------------+
|   xxx    |    xxx   |This is very long text                |
|          |          |                        |             |
+----------+----------+------------------------+-------------+

Answer:

POI 4.0: Try to call sheet.autoSizeColumn(*) after the calling all of createCell methods.

Answer:

I believe this is a known issue in Apache POI 3.9 and earlier. The problem is POI sets the column width to 0. Try updating to POI 3.10 and see if that solves your problem.

More info at https://issues.apache.org/bugzilla/show_bug.cgi?id=55644