EasyExcel的学习
由黑马课程整理所得 参考资料: EasyExcel公开课资料/EasyExcel.md · LT-Xu/EasyExcelDemo - 码云 - 开源中国 (gitee.com) 我的笔记:moan.oss-cn-shanghai.aliyuncs.com/document/16…
1. 需要导入的依赖坐标
<!-- EasyExcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.6</version>
</dependency>
<!-- lombok 优雅编程 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
2.关于读取
1. 最简单的例子
1. 需要的内容:
实体类(例如:student)、监听器(例如:StudentReadListener 需要继承AnalysisEventListener)、main方法
2. 重点:了解AnalysisEventListener需要继承的方法、基本语句:
```java
// 封装工作簿对象
ExcelReaderBuilder workBook = EasyExcel.read
("d:\杭州黑马在线202003班学员信息.xls", Student.class, new StudentReadListener());
// 封装工作表
ExcelReaderSheetBuilder sheet1 = workBook.sheet();
// 读取
sheet1.doRead();
```
2. 文件上传
- 监听器需要声明为多例
- 主要response head里的声明
3. 读取注释
-
@ExcelPoperty(value,index,converter)
-
@ExcelIgnore
-
@DateTimeFormat
-
@NumberFormat
-
@ExcelIgnoreUnannotated
关于写
1. 最简单的情况
List<Student> students = initData();
/*
String pathName 写入文件的路径
Class head 写入文件的对象类型
默认写入到07的xlsx中,如果想要写入xls,可以指定类型(待验证)
*/
ExcelWriterBuilder workBook = EasyExcel.write("d:\杭州黑马学员表.xlsx", Student.class);
// sheet方法参数: 工作表的顺序号(从0开始)或者工作表的名字
workBook.sheet().doWrite(students);
2. 文件下载
public class WebUploadAndDownload {
/**
* 文件下载
* 1. 编写实体类并创建对象以便写入表格
* 2. 设置响应参数:文件的ContentType和文件名,同时设置编码避免乱码
* 3. 直接写,内部会调用finish方法自动关闭OutputStream
*/
@GetMapping("download")
public void download(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// 防止中文乱码
String fileName = URLEncoder.encode("测试", "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");
ExcelWriterBuilder workBook = EasyExcel.write(response.getOutputStream(), Student.class);
ExcelWriterSheetBuilder sheet = workBook.sheet("模板");
sheet.doWrite(initData());
}
}