easy-poi列求和

874 阅读1分钟

一、前言 easy-poi和easy-excel性能对比 \

  • 为什么要用easy-poi 因为用了半年有了自己的一套工具模板懒得换,后来看来阿里的easy-excel在并发和线程处理上比easy-poi处理速度快了很多。具体原因没有去深挖,毕竟只是个工具,如果可选可以去选easy-excel。
    对比链接: www.jianshu.com/p/4e56a1a1d…

二、依赖说明

<properties>
    <easy-poi-version>4.4.0</easy-poi-version>
</properties>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-spring-boot-starter</artifactId>
    <version>${easy-poi-version}</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>${easy-poi-version}</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-web</artifactId>
    <version>${easy-poi-version}</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-annotation</artifactId>
    <version>${easy-poi-version}</version>
</dependency>

三、列求和

//设计样式
Cell cell;// 单元格
CellStyle cellStyle = workbook.createCellStyle();// 单元格样式
cellStyle.setWrapText(true);// 自动换行
cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
Font font = workbook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 12);
cellStyle.setFont(font);


//获取第0页的sheet表,要读取所有加个循环遍历
Sheet sheet = workbook.getSheetAt(0);
//获取第一个,有内容行的下标
int firstRowNum = sheet.getFirstRowNum();
Row firstRow = sheet.getRow(firstRowNum);
//获取最后一个,有内容列的下标
int lastCellNum = firstRow.getLastCellNum();
//最后一行+1用于合计行
int lastRowNum = sheet.getLastRowNum()+1;
//最后一行创建合计行单元格
Row row = sheet.createRow(lastRowNum);
cell = row.createCell(0);// 创建单元格
cell.setCellValue("合计:");
cell.setCellStyle(cellStyle);// 设置单元格样式
if (lastCellNum > 1) {
    for (int j = 1; j < lastCellNum; j++) {
        //创建第J列的单元格
        cell = row.createCell(j);
        cell.setCellStyle(cellStyle);
        //将长度转换为Excel的单元格列如A1,B1,C1,D1
        String colString2 = CellReference.convertNumToColString(j); 
        String sumstring = "SUM(" + colString2 + "3:" + colString2 + lastRowNum + ")";//求和公式
        sheet.getRow(lastRowNum).getCell(j).setCellFormula(sumstring);
    }
}
workbook.setForceFormulaRecalculation(true);// 执行公式
workbook.write(response.getOutputStream());

完~