EasyExcel技术,是Alibaba集团开源的,该技术是针对Apache POI技术的封装和优化,主要解决了POI技术的耗内存问题,并且提供了较好的API使用。不需要大量的代码就可以实现excel的操作功能。
pom文件新增:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
实体类: 注意这6个注解,都是需要的,少的话测试的时候会报错的
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
@HeadRowHeight(20)
@ColumnWidth(20)
@ContentRowHeight(15)
public class StudentDo {
@ExcelProperty(index = 0, value = "学号")
private String sno;
@ExcelProperty(index = 1, value = "姓名")
private String name;
@ExcelProperty(index = 2, value = "年龄")
private Integer age;
@ExcelProperty(index = 3, value = "性别")
private String gender;
@ExcelProperty(index = 4, value = "籍贯")
private String nativePlace;
@ExcelProperty(index = 5, value = "入学时间")
private Date enrollmentTime;
}
监听类:监听实体类
public class StudentListener extends AnalysisEventListener<StudentDo> {
@Getter
private List<StudentDo> studentList = new ArrayList<StudentDo>();
public StudentListener() {
super();
studentList.clear();
}
/**
* 每一条数据解析都会调用
*/
@Override
public void invoke(StudentDo student, AnalysisContext context) {
studentList.add(student);
}
/**
* 所有数据解析完成都会调用
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
studentList.forEach(System.out::println);
}
}
interface文件:
@GetMapping("/export")
public void exportStudentInfos(HttpServletResponse response, HttpServletRequest request)
throws IOException, ParseException;
@RequestMapping(value = "import")
public void importStudentInfos(MultipartFile file) throws IOException;
interfaceImpl文件:
@Override
public void exportStudentInfos(HttpServletResponse response, HttpServletRequest request) throws IOException, ParseException {
// 设置响应类型
response.setContentType("application/vnd.ms-excel");
// 设置字符编码
response.setCharacterEncoding("utf-8");
// 设置响应头信息
response.setHeader("Content-disposition",
"attachment;filename*=utf-8''" + URLEncoder.encode("学生花名册", "UTF-8") + ".xlsx");
List<StudentDo> studentList = new ArrayList<StudentDo>() {
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
add(new StudentDo("1001", "张三", 23, "男", "陕西西安", dateFormat.parse("2020-09-01")));
add(new StudentDo("1002", "李四", 22, "女", "陕西渭南", dateFormat.parse("2020-09-01")));
}
};
// 写入文件
EasyExcel.write(response.getOutputStream(), StudentDo.class).sheet("学生信息").doWrite(studentList);
}
@Override
public void importStudentInfos(MultipartFile file) throws IOException {
StudentListener studentListener = new StudentListener();
EasyExcel.read(file.getInputStream(), StudentDo.class, studentListener).sheet().doRead();
studentListener.getStudentList();
}
启动项目,去postman测试,即可导出文件
测试导入,把刚才导出的文件导入进来
打上断点就能看到导入的数据了