12

I want to increase the width of the column of excel sheet. as the i am writing trough code is long. and I need to drag the column manually to see the full text.

I did this –

HSSFRow dataRow = sampleDataSheet.createRow(0);

HSSFCellStyle cellStyle = setHeaderStyle(sampleWorkbook);

cellStyle.setWrapText(true);

***sampleDataSheet.autoSizeColumn(1000000);***

But its not changing anything..

Integrating Stuff
  • 5,253
  • 2
  • 33
  • 39
smriti
  • 1,124
  • 5
  • 14
  • 35

3 Answers3

22

This should work. However,

sampleDataSheet.autoSizeColumn(1000000);

auto-expands column 1000000.

If you want to auto-expand column 0(the first column), use:

sampleDataSheet.autoSizeColumn(0);

To auto-expand column 0 to 9(the first 10 columns):

for (int i=0; i<10; i++){
   sampleDataSheet.autoSizeColumn(i);
}

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.)

Integrating Stuff
  • 5,253
  • 2
  • 33
  • 39
  • hi-- I m doing like this static HSSFSheet sampleDataSheet = sampleWorkbook.createSheet("ABC"); sampleDataSheet.setColumnWidth(20,20); but I m not getting the setColumnWidth methiod in the API.. pls see.. – smriti Aug 19 '12 at 18:13
  • sampleDataSheet.autoSizeColumn(0); worked for me on 1st column thanks soo much,+1 but cud u pls suggest me for my sampleDataSheet.setColumnWidth(20,20); query... – smriti Aug 19 '12 at 21:37
14
// We can set column width for each cell in the sheet        
sheet.setColumnWidth(0, 1000);
sheet.setColumnWidth(1, 7500);
sheet.setColumnWidth(2, 7500);

// By applying style for cells we can see the total text in the cell for specified width
HSSFCellStyle cellStyle = workBook.createCellStyle();
cell.setCellStyle(cellStyle );
cellStyle.setWrapText(true);
Dani
  • 3,744
  • 4
  • 27
  • 35
swamy
  • 1,200
  • 10
  • 23
0

sheet.autoSizeColumn(columnNumber) works. this will resize the column to the largest cell length.

deHaar
  • 17,687
  • 10
  • 38
  • 51
Nilesh
  • 133
  • 3
  • 10
  • 1
    It only consider the width of the header not the content of the other cell of the column. – Naveen Jan 23 '16 at 16:17
  • @Naveen This is incorrect -- `autoSizeColumn` should adjust the column width to fit all row contents. – Zz'Rot Nov 28 '16 at 21:14