poi 实现自动列宽

网上找了几个,autoSize ,autoWidth方法,测试发现都没有生效,
然后自己写了一个,如下:

    public static void autoColumnWidth(XSSFSheet sheet) {
        XSSFRow head = sheet.getRow(0);
        if (Objects.isNull(head)) {
            return;
        }
        int[] columnWidths = new int[head.getLastCellNum()];
        for (int i = 0; i < columnWidths.length; i++) {
            System.out.println("columnWidths[" + i + "] = " + columnWidths[i]);
        }
        List<String> oneClass = Arrays.asList("PMD Program","Model Number", "RF Test");
        List<String> twoClass = Arrays.asList("HW", "SW");

        for (int i = 0; i < sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            for (int j = 0; j < row.getLastCellNum(); j++) {
                String stringCellValue = row.getCell(j).getStringCellValue();
                if (stringCellValue != null) {
                    int length = stringCellValue.getBytes().length;
                    if (length > 255) {
                        continue;
                    }
                    int width = getWidth(oneClass, stringCellValue, length, twoClass);
                    columnWidths[j] = Math.max(columnWidths[j], width);
                }
            }
        }
        for (int i = 0; i < columnWidths.length; i++) {
            System.out.println("columnWidths[" + i + "] = " + columnWidths[i]);
            try {
                sheet.setColumnWidth(i, columnWidths[i]);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
	// 某些 header 字段 特殊处理
    private static int getWidth(List<String> oneClass, String stringCellValue, int length, List<String> twoClass) {
        int width =0;
        if(oneClass.contains(stringCellValue)){
            width = length * 380;
        }else if(twoClass.contains(stringCellValue)){
            width = 8 * 256;
        }else if(NumberUtil.isNumber(stringCellValue)){
            width = length * 360;
        }else if(stringCellValue.toUpperCase().equals(stringCellValue)){
            width = length * 360;
        }else if(DateUtils.isCSTStr(stringCellValue)){
            width = length * 360;
        }else{
            width = length * 256;
        }
        return width;
    }

你可能感兴趣的:(poi)