上篇讲到EasyPOI导出常规报表,本篇是在此基础上再增加新的东西-合并单元格,这个功能在需求中也很常见。
这里我直接贴逻辑代码:
EasyPOI工具类加上如下方法
/**
* @Description: excel导出-合并单元格
* @param[1] list 数据列表
* @param[2] title 报表标题
* @param[3] sheetName excel工作表名
* @param[4] pojoClass 导出实体类
* @param[5] fileName 导出excel文件名称
* @param[6] response
* @param[7] columns 需要进行合并的列
**/
public static void exportMerge(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
HttpServletResponse response, Integer[] columns)
throws IOException {
ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
//把数据添加到excel表格中
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
//设置单元格格式
setBorder(workbook);
//对单元格进行合并--对第一张工作表第2行第columns列开始合并
PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0),1,columns);
//下载excel文件
downLoadExcel(workbook,fileName, response);
}
实体类
package com.example.work.entity;
import java.math.BigDecimal;
import java.util.Date;
import cn.afterturn.easypoi.excel.annotation.Excel;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
@Data
public class Employee {
/**
* id
*/
private Integer id;
/**
* 姓名
*/
@Excel(name = "姓名")
private String name;
/**
* 性别 1-男;2-女
*/
@Excel(name = "性别",replace = {"男_1", "女_2"})
private Byte sex;
/**
* 所在部门
*/
@Excel(name = "所在部门")
private String dept;
/**
* 出生地
*/
@Excel(name = "出生地")
private String address;
/**
* 出生年月
*/
@Excel(name = "出生年月",exportFormat = "yyyy-MM-dd",width = 15)
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date birthDay;
/**
* 联系电话
*/
@Excel(name = "联系电话",width = 15)
private String phone;
/**
* 工资
*/
@Excel(name = "工资(单位:元)",width = 15)
private BigDecimal salary;
}
controller层
@GetMapping("/exportMerge")
public void exportMerge(HttpServletResponse response){
employeeService.exportMerge(response);
}
业务层
@Override
public void exportMerge(HttpServletResponse response) {
try {
//针对要合并的列所对应的字段进行排序
List<Employee> list = this.list(new LambdaQueryWrapper<Employee>()
.orderByDesc(Employee::getDept)
.orderByDesc(Employee::getAddress));
String fileName = "员工工资报表";
//需要合并的列
Integer []columns ={2,3};
EasyPoiUtils.exportMerge(list,null,fileName,Employee.class,fileName,response,columns);
}catch (Exception e){
throw new RuntimeException("导出失败");
}
}
数据库表数据
接下来启动程序并调用接口,导出结果如下
这里我是在上篇的基础上粘贴的主要代码,如有需要可先看EasyPOI导出报表第一篇(http://t.csdnimg.cn/2ndg2)