直接說吧!
sheet.autoSizeColumn((short)col, true);
只要這樣寫就解決了!
第一個參數是自動寬度的列數(第幾列),第二個參數是說是否算上已經合並的單元格。
本來寫的代碼:
1 for (int col = 0; col < propIds.size(); col++) { 2 sheet.autoSizeColumn((short)col); 3 int maxColumnWidth = sheet.getColumnWidth(col); 4 int width = 0; 5 for (int i = 1; i <= headDeal.rows; i++) { 6 if(sheet.getRow(i).getCell(col).getStringCellValue().length() != 0) 7 width = sheet.getRow(i).getCell(col).getStringCellValue().length() * 512; 8 } 9 maxColumnWidth = (maxColumnWidth>width) ? maxColumnWidth : width; 10 sheet.setColumnWidth(col, maxColumnWidth); 11 } 12 System.out.println("header rows: " + headDeal.rows);
中間的代碼(第3到第10行)
(除第一行for循環和第二行sheet.autoSizeColumn((short)col); 之外),
就是我本來寫的解決辦法,功能同樣能實現。
不過,算是白寫了,poi原來自帶一種方法的。
其中的 512 ,是因為中文在表格中被解析會占用512的寬度所致,數字和英文256。
結果看了源碼才知道,原來poi自帶有合並表格模式。
意思就是:poi對於合並表頭的表格設計,在sheet.autoSizeColumn 有方法,第二個參數就是設置是否加入被合並的表格計算自動寬度。(true是加入,false不加,默認false)