需要用到的依赖
<!-- excel导入导出 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
实体类
@Data
public class Depts {
/**
* 部门编号
*/
@ColumnWidth(20) //设置单元格的宽度
@ExcelProperty(value = "部门编号",index = 0) // 属性value是导出对应的字段;index 是下标
private Integer deptno;
/**
* 部门名称
*/
@ColumnWidth(20)
@ExcelProperty(value = "部门名称",index = 1)
private String dname;
}
使用注解自定义样式(这里就不再演示,感兴趣的伙伴可以自行测试)
@ContentRowHeight(10) // 文本行高度
@HeadRowHeight(20) // 标题高度
@ColumnWidth(25) // 默认列宽度
// 头背景设置成红色 IndexedColors.RED.getIndex()
@HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 10)
// 头字体设置成20
@HeadFontStyle(fontHeightInPoints = 20)
// 内容的背景设置成绿色 IndexedColors.GREEN.getIndex()
@ContentStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 17)
// 内容字体设置成20
@ContentFontStyle(fontHeightInPoints = 20)
代码示例(这里直接写在了控制层,方便演示)
@GetMapping("/getexcel")
public void get(HttpServletResponse response) throws IOException{
// 设置 header 和 contentType。
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("模板.xls", "UTF-8"));
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("utf-8");
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
// 获取sheet0对象
WriteSheet writeSheet = EasyExcel.writerSheet(0, "部门").head(Depts.class).build();
List<Depts> list = deptMapper.selectDepts();
// 写入sheet0对象
excelWriter.write(list,writeSheet);
// 获取sheet1对象
WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "部门1").head(Dept.class).build();
List<Dept> list1 = new ArrayList<>();
Dept dept = new Dept();
dept.setDeptno(1);
dept.setDname("好人");
list1.add(dept);
dept = new Dept();
dept.setDeptno(2);
dept.setDname("坏人");
list1.add(dept);
// 写入sheet1对象
excelWriter.write(list1,writeSheet1);
// 关闭流
excelWriter.finish();
}
结果
从结果来看,部门编号是红色,并且是两个sheet,可以添加多个sheet。