平常工作经常遇到excel导入导出,easyExcel也是基于poi开发的,但是相对来说内存占用比较小,功能也更丰富,根据本人日常工作需要,抽取了excel导入导出的工具类,若有不足,请指出一起成长~
<dependency>
<groupId>com.alibabagroupId>
<artifactId>easyexcelartifactId>
<version>2.1.7version>
dependency>
package cn.itcast.boot.entity;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ColumnWidth(40)
@HeadRowHeight(25)
public class Student {
/**
* 年龄
*/
@ColumnWidth(20)
@ExcelProperty("年龄")
private int age;
/**
* 名字
*/
@ExcelProperty("名字")
private String name;
/**
* 年级
*/
@ExcelIgnore
private String classes;
/**
* 分数
*/
@ExcelProperty("分数")
private BigDecimal score;
/**
* 维护日期
*/
//此注解作用:将数据库查询的日期,以指定格式转换为字符串格式传给前端 Date->json
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
//Excel导出时,日期字段按照指定字段导出
@DateTimeFormat("yyyy-MM-dd")
//controller层接收参数将字符串转为日期 json->Date
@org.springframework.format.annotation.DateTimeFormat(pattern = "yyyy-MM-dd")
private Date mntDte;
}
package cn.itcast.boot.ExcelUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.function.Consumer;
import static com.alibaba.excel.EasyExcelFactory.write;
public class EasyExcelUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(EasyExcelUtils.class);
public static <T> AnalysisEventListener<T> getListener(Consumer<List<T>> consumer,int threshold){
return new AnalysisEventListener<T>() {
/**
* 存储数据集合
*/
private List<T> list = new LinkedList<T>();
/**
* 这个每一条数据解析都会调用一次
* @param t
* @param analysisContext
*/
@Override
public void invoke(T t, AnalysisContext analysisContext) {
list.add(t);
if (list.size() == threshold){
consumer.accept(list);
list.clear();
}
}
/**
* 所有数据解析完成 自动调用此方法
* @param analysisContext
*/
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
if (list.size()>0){
consumer.accept(list);
}
}
};
}
/**
* 根据指定字段导出数据
* @param response
* @param colums
* @param dataList
* @param aClass
*/
public static void exportExcel(HttpServletResponse response,String[] colums, List<?> dataList,Class<?> aClass){
try {
//添加要导出的字段
Set<String> includeList = new HashSet<>();
Collections.addAll(includeList,colums);
//设置返回类型及编码类型
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setCharacterEncoding("UTF-8");
//写出
write(new BufferedOutputStream(response.getOutputStream()),aClass)
.autoCloseStream(true)
.excelType(ExcelTypeEnum.XLSX)
.includeColumnFiledNames(includeList)
.sheet().doWrite(dataList);
}catch (IOException e){
LOGGER.error(e.getMessage());
}
}
/**
* 不指定导出字段
* 不需要导出的字段需要使用注解标记@ExcelIgnore
* 按照实体类中注解标记顺序导出
*
* @param response
* @param dataList
* @param aClass
*/
public static void exportExcel(HttpServletResponse response,List<?> dataList,Class<?> aClass){
try {
//设置返回类型及编码类型
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setCharacterEncoding("UTF-8");
//写出
write(new BufferedOutputStream(response.getOutputStream()),aClass)
.autoCloseStream(true)
.excelType(ExcelTypeEnum.XLSX)
.sheet().doWrite(dataList);
}catch (IOException e){
LOGGER.error(e.getMessage());
}
}
}
/**
* 注: 逻辑代码尽量不要写在controller层,此处仅为方便演示
*
* easyExcel自定义工具类excel批量导入
* @param file
*/
@PostMapping("/excelAppend")
public void excelAppend(@RequestParam MultipartFile file) throws IOException {
AnalysisEventListener<Object> listener =
EasyExcelUtils.getListener(list -> excelBatchAppendService.excelAppend(list), 10000);
EasyExcelFactory.read(new BufferedInputStream(file.getInputStream()), Student.class,listener);
}
service层
/**
* excel批量导入
* @param list
*/
@Override
public void excelAppend(List<Object> list) {
//TODO 处理excel中数据 list
}
@PostMapping("/batchExport")
public void batchExport(HttpServletResponse response){
List<Student> dateList = getDateList();
EasyExcelUtils.exportExcel(response,dateList,Student.class);
}
public List<Student> getDateList(){
List<Student> students = new ArrayList<>();
Collections.addAll(students,
new Student(10,"小红","三年二班",new BigDecimal(100),new Date()),
new Student(12,"小蓝","三年二班",new BigDecimal(80.50),new Date()),
new Student(11,"小绿","三年二班",new BigDecimal(22.30),new Date()),
new Student(11,"小紫","三年二班",new BigDecimal(65.66),new Date())
);
return students;
}