Easy Excel 框架
简述
Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。 easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,改用easyexcel可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便
如何使用这个框架进行一个下载功能呢
添加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.3</version>
</dependency>
pojo层
package com.hh.pojo;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.NumberFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
@Data
@TableName(value = "drug")
public class Drug {
@TableId
@ExcelProperty(value = "编号",index = 0)
@ColumnWidth(20)
private Integer id;
@ExcelProperty(value = "药品编号",index = 1)
@ColumnWidth(20)
private Integer drugId;
@NotBlank(message = "请查看名字是否为空")
@ColumnWidth(20)
@ExcelProperty(value = "药品名称",index = 2)
private String drugName;
@Min(value = 0,message = "商品价格不能低于0元")
@ExcelProperty(value = "药品价格(元)",index = 3)
@ColumnWidth(20)
private Double drugPrice;
@Min(value = 0,message = "商品数量不能是负数")
@ExcelProperty(value = "药品数量",index = 4)
@ColumnWidth(20)
private Integer drugNumber;
@Range(min = 0,max = 1,message = "请确认好商品目前状态")
@ExcelProperty(value = "药品状态",index = 5)
@ColumnWidth(20)
private Integer status;
@Override
public String toString() {
return "Drug{" +
"id=" + id +
", drugId=" + drugId +
", drugName='" + drugName + '\'' +
", drugPrice=" + drugPrice +
", drugNumber=" + drugNumber +
", status=" + status +
'}';
}
}
注解讲解:
@ExcelProperty:用来表示列名
参数(列名,索引位置) 索引位置从0开始
@ColumnWidth:用来表示宽度
参数(宽度的具体数值)
controller层
@RequestMapping("download/drugExcel")
public void DrugExcelDownLoad(HttpServletResponse response)throws Exception {
List<com.hh.pojo.Drug> drugList = drugService.findAllDrug();
//设置响应头
response.setContentType("application/vnd.ms-excel");
String fileName = "药品信息表.xlsx";
String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
EasyExcel.write(response.getOutputStream(), Drug.class)
.sheet("sheet1")
.doWrite(drugList);
}