Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a specific cell width to column in XSSF Apache POI

I am trying to export a table as xlsx using Apache POI XSSF. Table has 5 columns.

First row has title block merging 5 columns. In the second row, 5 headings for the table. Remaining rows are data. I want to set width of the column as max width of each heading blocks.

I tried mySheet.autoSizeColumn(colnum) and mySheet.setColumnWidth(columnIndex, width). Problem with AutosizeColumn, it is returning the highest width of the data in all the rows. So If width of some data in table is more, table header width is becoming very large. And for the second one, setColumnWidth, I need to know width of the header cell so I can set it to the sheet. But how to find the width of a specific cell? Had no luck yet in figuring out how to do it. Any idea on how to that?

like image 227
om39a Avatar asked Jan 03 '14 04:01

om39a


People also ask

How do I change the width of a column in Excel using poi?

Also, you should create all your rows and fill them with content first, before you call autoSizeColumn(so the column gets the width of the value with the broadest width). (If you want to set the column width to a fixed value, use HSSFSheet. setColumnWidth(int,int) instead.)


1 Answers

I would suggest simple solution that I have used.

Use a condition and after writing the 2nd row, i.e. the heading row, use AutosizeColumn() it will change the cell width according to the header width and then the width will remain as it is.

like image 103
Sankumarsingh Avatar answered Oct 18 '22 03:10

Sankumarsingh