3

I'm trying to build an excell file with apache. (HSSFWorkbook)

I cant figure out how to set column width size.

Look at the following example:

enter image description here

The first column (A) has the value: "row number" which we cant see the whole string. The columns (D) and (E) have the same problem, but If we double click on it we can see the full string.

I want to create cells which the user wouldn't need to double click on it. How can I do it ?

4 Answers 4

5

You can use autoSizecolumn() which will set column size based on its header.

sheet.autoSizeColumn(0)// to adjust first column

Please refer this link. It would be helpful...

To set all the available columns , use a for loop

for(int colNum = 0; colNum<row.getLastCellNum();colNum++)   
    workbook.getSheetAt(0).autoSizeColumn(colNum);
1
  • My mistake, it works. I Had tryied autiSizeColumn before I had put data. I just move this command to the end of the code and it works Commented Nov 7, 2014 at 15:22
2

Try using the setColumnWidth() method on the HSSFSheet object

sheet.setColumnWidth(0, 1000);

This requires more code than using autoSizeColumn() but I have found that autoSizeColumn() can be ignored when opening the produced file in newer versions of Excel (2013).

1

Autofit will also work

(from the help file)
This example changes the width of columns A through I on Sheet1 to achieve the best fit.

Worksheets("Sheet1").Columns("A:I").AutoFit 

This example changes the width of columns A through E on Sheet1 to achieve the best fit, based only on the contents of cells A1:E1.

Worksheets("Sheet1").Range("A1:E1").Columns.AutoFit 
1
  • Not sure what language that is, but I'm fairly sure it isn't Java nor using the Apache POI library, which the OP is asking about
    – Gagravarr
    Commented Nov 8, 2014 at 11:37
0

From the documentation:

Sheet sheet = workbook.getSheetAt(0);
sheet.autoSizeColumn(0); //adjust width of the first column
sheet.autoSizeColumn(1); //adjust width of the second column

Not the answer you're looking for? Browse other questions tagged or ask your own question.