java poi excel 列宽自适应

2020-07-23  本文已影响0人  Jin110

1)列宽自适应列宽度

intmaxColumn=sheet.getRow(0).getPhysicalNumberOfCells();

for (int columnNum = 0; columnNum <= maxColumn; columnNum++) {

intcolumnWidth=sheet.getColumnWidth(columnNum) / 256;

for(introwNum= 0;rowNum<=sheet.getLastRowNum();rowNum++) {

RowcurrentRow;

if(sheet.getRow(rowNum) ==null) {

currentRow=sheet.createRow(rowNum);

}else{

currentRow = sheet.getRow(rowNum);

}

if(currentRow.getCell(columnNum) !=null) {

CellcurrentCell = currentRow.getCell(columnNum);

try{

intlength=currentCell.toString().getBytes("GBK").length;

if(columnWidth

columnWidth = length + 8;

}

}catch(UnsupportedEncodingExceptione) {

e.printStackTrace();

}

}

}

sheet.setColumnWidth(columnNum,columnWidth* 256);

}

2)列宽自适应的第二种方法

//存储最大列宽Map maxWidth =newHashMap<>();

            // 将列头设置到sheet的单元格中for(intn = 0; n < columnNum; n++) {

                HSSFCell cellRowName = rowRowName.createCell(n);//创建列头对应个数的单元格cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);//设置列头单元格的数据类型HSSFRichTextString text =new HSSFRichTextString(columnName[n]);

                cellRowName.setCellValue(text);                                    //设置列头单元格的值cellRowName.setCellStyle(columnTopStyle);//设置列头单元格样式maxWidth.put(n, cellRowName.getStringCellValue().getBytes().length * 256 + 512);

            }

            sheet.createFreezePane(2, 1, 2, 1);

            for(inti = 0; i < dataList.size(); i++) {

                intj = 0;

                Map map = dataList.get(i);//遍历每个对象HSSFRow row = sheet.createRow(i + 1);//创建所需的行数for (Object key : map.keySet()) {

                    HSSFCell cell =null;//设置单元格的数据类型cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);

                    if(!"".equals(map.get(key)) && map.get(key) !=null) {

                        cell.setCellValue(map.get(key).toString());

                        intlength = cell.getStringCellValue().getBytes().length * 256 + 512;

                        //这里把宽度最大限制到15000if(length > 15000) {

                            length = 15000;

                        }

                        maxWidth.put(j, Math.max(length, maxWidth.get(j)));

                    }

                    j++;

                    cell.setCellStyle(style);  //设置单元格样式                }

            }

int maxColumn=sheet.getRow(0).getPhysicalNumberOfCells();

            for(inti = 0; i <maxColumn; i++) {

                sheet.setColumnWidth(i, maxWidth.get(i));

            }

上一篇 下一篇

猜你喜欢

热点阅读