Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache POI Excel - how to configure columns to be expanded?

People also ask

How do I automatically adjust column width in Excel using Apache POI?

sheetName. autoSizeColumn(columnIndex);

How do you widen a column to show all data?

To quickly set the column width to display everything, double-click the column separator. To shrink the contents of a cell so that they fit in the current column width: In Excel 2016 for Mac, on the Home tab, click the Format button, click Format Cells, and then select Shrink to Fit.

How do you change cell width in POI?

You can set the column width using setColumnWidth method of XSSFWorkbook . The 1st parameter is the column number (starts from zero) and the 2nd parameter is the width. We need to be little tricky here to set the width. To set the width as 25 we need to pass the parameter as 25 * 256 .


After you have added all your data to the sheet, you can call autoSizeColumn(int column) on your sheet to autofit the columns to the proper size

Here is a link to the API.

See this post for more reference Problem in fitting the excel cell size to the size of the content when using apache poi


Tip : To make Auto size work , the call to sheet.autoSizeColumn(columnNumber) should be made after populating the data into the excel.

Calling the method before populating the data, will have no effect.


If you want to auto size all columns in a workbook, here is a method that might be useful:

public void autoSizeColumns(Workbook workbook) {
    int numberOfSheets = workbook.getNumberOfSheets();
    for (int i = 0; i < numberOfSheets; i++) {
        Sheet sheet = workbook.getSheetAt(i);
        if (sheet.getPhysicalNumberOfRows() > 0) {
            Row row = sheet.getRow(sheet.getFirstRowNum());
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                int columnIndex = cell.getColumnIndex();
                sheet.autoSizeColumn(columnIndex);
            }
        }
    }
}

You can try something like this:

HSSFSheet summarySheet = wb.createSheet();
summarySheet.setColumnWidth(short column, short width);

Here params are:column number in sheet and its width But,the units of width are pretty small, you can try 4000 for example.


For Excel POI:

sheetName.autoSizeColumn(cellnum); 

sample code below

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("your sheet name");
HSSFRow row = sheet.createRow(0);

cell = row.createCell(0);
cell.setCellValue("A BIG NAME WITH AUTO SIZE FEATURE ENABLED");

//this is crucial

sheet.autoSizeColumn(0);

//argument must be cell number

cell = row.createCell(1);
cell.setCellValue("a big name without auto size feature enabled");

Check the output and go nuts :)