excel设置单元格边框线, 自适应行高

/**
     * 设置单元格边框线, 自适应行高
     *
     * @param workbook
     */
    private static void setBorderAndLineHeight(Workbook workbook) {
        //根据内容长度设置行高,pdf折行
        Sheet sheet = workbook.getSheetAt(0);
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            int cells = row.getLastCellNum();
            int temp = 0;
            String cellStr = "";
            for (int c = 0; c < cells; c++) {
                Cell cell = row.getCell(c);
                CellStyle style = cell.getCellStyle();
                style.setBorderTop(BorderStyle.THIN); //细实线
                style.setBorderBottom(BorderStyle.THIN);
                style.setBorderLeft(BorderStyle.THIN);
                style.setBorderRight(BorderStyle.THIN);
                int length = cell.toString().length(); //单元格字符串长度
                if (length > temp) {
                    cellStr = cell.toString();  //最长的字符串
                    temp = length;
                }
            }
            short height = 25;
            //设置默认行高
            row.setHeightInPoints(height);
            int lineHeight = 0;
            for (char a : cellStr.toCharArray()) {
                if (isContainsChinese(String.valueOf(a))) {
                    lineHeight += 2;  //中文 2 个字符
                } else {
                    lineHeight += 1;  //英文 1 个字符
                }
            }
            //excel宽的单位是字符,高的单位是磅,大概换算一下行高比例
            int fixed = 10;
            //计算倍数,向上取整
            int hl = (lineHeight / fixed);
            int hly = lineHeight % fixed;
            hl = hly > 0 ? hl + 1 : hl;
            int rowHeight = hl * height;
            row.setHeightInPoints(rowHeight);
        }
    }

    /**
     * 是否包含中文字符
     *
     * @param str
     * @return
     */
    public static boolean isContainsChinese(String str) {
        if (str == null) {
            return false;
        }
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        return m.find();
    }

你可能感兴趣的:(java,excel,java,开发语言)