POI Excel列宽中文自适应

POI Excel列宽中文自适应

// 自适应宽度(中文支持)
private void setSizeColumn(HSSFSheet sheet) {
    for (int columnNum = 0; columnNum <= 8; columnNum++) {
        int columnWidth = sheet.getColumnWidth(columnNum) / 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(columnNum) != null) {
                HSSFCell currentCell = currentRow.getCell(columnNum);
                if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                    int length = currentCell.getStringCellValue().getBytes().length;
                    if (columnWidth < length) {
                        columnWidth = length;
                    }
                }
            }
        }
        sheet.setColumnWidth(columnNum, columnWidth * 256);
    }
}

你可能感兴趣的:(Java基础)