poi常用代码片段

原创
2022/08/24 14:44
阅读数 86

poi常用代码片段

创建一个excel表格

XSSFWorkbook workbook = new XSSFWorkbook();

创建sheet页

XSSFSheet sheet = workbook.createSheet("Sheet1");

创建表头

public void createHeader(XSSFWorkbook workbook, Sheet sheet, String[] headers) {
    Row headerRow = sheet.createRow(0);
    XSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setFillPattern(FillPatternType.NO_FILL);
    cellStyle.setLocked(false);

    // 填充色
    XSSFColor color = new XSSFColor(new Color(205, 235, 241));
    cellStyle.setFillForegroundColor(color);
    cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

    // 边框样式
    BorderStyle borderStyle = BorderStyle.THIN;
    cellStyle.setBorderTop(borderStyle);
    cellStyle.setBorderBottom(borderStyle);
    cellStyle.setBorderLeft(borderStyle);
    cellStyle.setBorderRight(borderStyle);

    // 边框颜色
    short borderColor = IndexedColors.BLACK1.getIndex();
    cellStyle.setTopBorderColor(borderColor);
    cellStyle.setBottomBorderColor(borderColor);
    cellStyle.setLeftBorderColor(borderColor);
    cellStyle.setRightBorderColor(borderColor);

    // 单元格字体
    XSSFFont font = workbook.createFont();
    font.setBold(true);
    font.setFontName("宋体");
    font.setFontHeightInPoints((short) 10);
    cellStyle.setFont(font);

    // 字体对齐方式
    cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
    cellStyle.setAlignment(HorizontalAlignment.CENTER);

    // 单元格大小
    headerRow.setHeight((short) 330);
    for (int i = 0; i < headers.length; i++) {
        // 设置一个比较大的宽度,之后再自动伸缩
        sheet.setColumnWidth(i, 15000);
        Cell cell = headerRow.createCell(i);
        cell.setCellStyle(cellStyle);
        cell.setCellValue(headers[i]);
    }
}

调用:

String[] header = {"序号", "编号", "姓名", "性别"};
createHeader(workbook, sheet, header);

单元格宽度自适应

public void setCellWidth(XSSFSheet sheet, String[] header) {
    for (int i = 0; i < header.length; i++) {
        // 自适应宽度
        sheet.autoSizeColumn(i);
        // 设置一个最大宽度,不能超过这个值
        if (sheet.getColumnWidth(i) > 15000) {
            sheet.setColumnWidth(i, 15000);
        }
    }
}
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部