使用Apache POI和EasyExcel生成Excel文件(二)

178 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第二十四天,点击查看活动详情


上一章简单讲述了使用poi生成一个Excel文件的方式,这一章讲述一下复杂的Excel文件生成,比如Excel中要插入图片,图片下方继续插入图片等。

其中插入图片的方式在之前的文章中已经讲过了,所以这一章着重描述设置带有格式的数据,以及获取最新的行号,避免插入数据的时候数据插入到错误行中。

插入一行有格式的标题

OutExcelUtil.oneTitleCell(wb, sheet, "测试一行数据", 0, true);

/**
 * 创建只有一行的数据标题
 *
 * @param wb     Excel的工作书册
 * @param sheet  Excel的工作sheet
 * @param value  插入的数据
 * @param rowNum 插入数据的行号
 * @param isBold 是否加粗
 */
public static void oneTitleCell(XSSFWorkbook wb, XSSFSheet sheet, String value, int rowNum, boolean isBold) {
    //创建一个字体
    Font font = wb.createFont();
    //设置字体的高度
    font.setFontHeightInPoints((short) 10);
    //设置是否加粗
    font.setBold(isBold);

    //通过创建CellStyle的方式将字体及字体格式放入Excel中
    CellStyle style = wb.createCellStyle();
    style.setFont(font);

    XSSFRow row = sheet.createRow(rowNum);
    XSSFCell cell = row.createCell(0);
    //设置这一行的值及对应的格式
    cell.setCellValue(value);
    cell.setCellStyle(style);
}

当下方插入多条数据后想获取最新的行号,则使用

//获取最新的行号
int size = sheet.getLastRowNum();

需要引入的jar包

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.0</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>4.1.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
        </exclusion>
    </exclusions>
</dependency>

使用Apache poi的方式生成文件比较繁琐且复杂,但灵活性高,可以生成各种格式的Excel,并且可以随意在下方插入各种格式的数据,而使用easyExcel则是使用简单,但不支持在Excel中插入图片等数据,可以按照自己的需求选择使用哪种方式生成Excel文件。