JAVA 的 EXCEL 数据导入导出—EasyExcel 的方法的实现
文 / 汝淉
因为最近项目用到 把数据库的数据导入到Excel中,所以就用了此工具… Apache 的 poi 导出内存占用非常高,尤其多人同时导出数据的时候,性能会收到冲击…所以采用更轻巧的EasyExcel工具.
EasyExcel 是阿里巴巴提供的.最大的特点就是使用内存少,易上手…使用简单…
第一步:导入EasyExcel所需依赖
<!-- 解析excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency><!-- 阿里巴巴EasyExcel-->
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beta4</version>
</dependency>
第二步:所需工具类
ExcelUtil | 主要的工具类,可以直接调用该工具类的方法完成 Excel 的读或者写 |
---|---|
ExcelListener | 监听类,可以根据需要与自己的情况,自定义处理获取到的数据,我这里只是简单地把数据添加到一个 List 里面 |
ExcelWriterFactroy | 用于导出多个 sheet 的 Excel,通过多次调用 write 方法写入多个 sheet |
ExcelException | 捕获相关 Exception |
三. 读取 Excel
读取 Excel 时只需要调用 ExcelUtil.readExcel() 方法
作为映射实体类,通过 @ExcelProperty 注解与 index 变量可以标注成员变量所映射的列,同时不可缺少 setter 方法
@GetMapping(value = "readExcel")
public Object readExcel(MultipartFile excel) {
return ExcelUtil.readExcel(excel, new OrderExcelVM());
}
导入的实体类代码
public class OrderExcelVM extends BaseRowModel {
@ExcelProperty(index = 0)
private String orderSn;
@ExcelProperty(index = 1)
//@DateTimeFormat( iso = DateTimeFormat.ISO.DATE_TIME)
private String addTime;
@ExcelProperty(index = 2)
private BigDecimal orderAmount;
@ExcelProperty(index = 3)
private BigDecimal orderActivityMoney;
.
四. 导出 Excel
导出的 Excel 只拥有一个 sheet 只需要调用 ExcelUtil.writeExcel() 方法:
@GetMapping(value = "writeExcel")
public void writeExcel(HttpServletResponse response) throws IOException {
List<OrderExcelVM> list = orderService.getList();//获取的订单数据
String time = DateUtils.stampToDate(new Long(System.currentTimeMillis()/1000).intValue());
time = time.replaceAll("-","");
time = time.replaceAll(":","");
time = time.replaceAll(" ","");
//excel的名称
String fileName =