最近因为公司需要做一份excel的模板导入导出,但是之前用poi每一行创建一个Row 很是繁琐,然后找到了阿里的开源框架easyExcel 记录下使用导出功能的心得
1.依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beat1</version>
</dependency>
2. 使用 分为两种模式
-
不使用模板
1.初始化sheet
//第一个参数代表sheet编号从1开始 第二个代表从第几行开始写
Sheet sheet = new Sheet(1, 0);
sheet.setSheetName("sheet");
//设置自适应宽度
sheet.setAutoWidth(Boolean.TRUE);
2.表头数据
这里的每一个String代表每一列的表头,head的索引代表着表的列的索引
我们开始定义一个存放表头的数据
// 存放表头数据,直接add表头数据即可
List<String> head = new ArrayList<>();
//也可以多定义几个head 进行多行表头
//将head填装到list 即可
List<List<String>> list = new ArrayList<>();
head.forEach(h -> list.add(Collections.singletonList(h)));
sheet.setHead(list);
3.表内数据
//定义一个data数据里面每一个list代表一行,List<Object>的索引就是
//每一行的索引
List<List<Object>> data = new ArrayList<>();
//填充数据进去即可,可以从数据库表查询等等
4.写数据
OutputStream outputStream = null;
ExcelWriter writer = null;
// 这里输出流可以是文件流也可是response 留作浏览器下载
outputStream = response.getOutputStream();
writer = EasyExcelFactory.getWriter(outputStream);
writer.write1(data,sheet);
writer.finish();
outputStream.close();
5.合并单元格和一些样式
// 四个参数定义好即可,注意不要冲突
writer.merge(startRow,endRow,StartCol,EndCol)
//设每一列的宽度 256等于excel里的1
Map columnWidth = new HashMap();
columnWidth.put(1, 5 * 256);
columnWidth.put(2, 10 * 256);
columnWidth.put(3, 5 * 256);
columnWidth.put(4, 5 * 256);
columnWidth.put(5, 10 * 256);
columnWidth.put(6, 10 * 256);
sheet.setColumnWidthMap(columnWidth);
//设置一些样式 我觉得功能很少
sheet.setTableStyle(TableStyle style)
-
使用模板
如果我们使用模板那就更方便了
1.定义模板类 -继承BaseRowModel
public static class PersonModel extends BaseRowModel {
// value 代表表头名,index 代表列的索引
@ExcelProperty(value = "姓名", index = 0)
private String name;
@ExcelProperty(value = "年龄", index = 1)
private String age;
}
2.导出
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
Sheet sheet1 = new Sheet(1, 0, ExcelPropertyIndexModel.class);
sheet1.setSheetName("sheet1");
//用于存放每一行数据
List<ExcelPropertyIndexModel> data = new ArrayList<>();
/* ....从数据库查询数据 映射到每一个字段上.... */
writer.write(data, sheet1);
writer.finish();