让列宽随着导出的列长自动适应 

//让列宽随着导出的列长自动适应
int maxColumnWidth = 30 * 256;
int columnNum = headName.length;
for (int colNum = 0; colNum < columnNum; colNum++) {
    /*//方法一:中文有问题
    int columnWidth = sheet.getColumnWidth(colNum) / 256;
    for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
        HSSFRow currentRow;
        //当前行未被使用过
        if (sheet.getRow(rowNum) == null) {
            currentRow = sheet.createRow(rowNum);
        } else {
            currentRow = sheet.getRow(rowNum);
        }
        if (currentRow.getCell(colNum).getRichStringCellValue() != null) {
            //取得当前的单元格
            HSSFCell currentCell = currentRow.getCell(colNum);
            int length = 0;
            //如果当前单元格类型为字符串
            if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                try {
                    length = currentCell.getStringCellValue().getBytes().length;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (columnWidth < length) {
                    //将单元格里面值大小作为列宽度
                    columnWidth = length;
                }
            }
        }
    }
    //再根据不同列单独做下处理
    sheet.setColumnWidth(colNum, (columnWidth + 2) * 256);*/

    //方法二:中文有OK
    sheet.autoSizeColumn(colNum);
    //手动调整列宽,解决中文不能自适应问题
    //sheet.setColumnWidth(colNum, sheet.getColumnWidth(colNum) * 12 / 10);
    //like12 add,20220122,设置最大宽度限制
    int columnWidth = sheet.getColumnWidth(colNum);
    if(columnWidth > maxColumnWidth){
        columnWidth = maxColumnWidth;
    }
    sheet.setColumnWidth(colNum, columnWidth * 12 / 10);
}

正式使用 

//让列宽随着导出的列长自动适应
int maxColumnWidth = 30 * 256;
int columnNum = headName.length;
for (int colNum = 0; colNum < columnNum; colNum++) {
    //自动列宽
    sheet.autoSizeColumn(colNum);
    //like12 add,20220122,设置最大宽度限制
    int columnWidth = sheet.getColumnWidth(colNum);
    if(columnWidth > maxColumnWidth){
        columnWidth = maxColumnWidth;
    }
    //手动调整列宽,解决中文不能自适应问题
    sheet.setColumnWidth(colNum, columnWidth * 12 / 10);
}

HSSFFont自动换行

HSSFCellStyle cellStyleData = wb.createCellStyle();
cellStyleData.setWrapText(true);//自动换行

cell.setCellStyle(cellStyleData);

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐