springBoot整合easyExcel
时间: 2023-06-26 09:07:44 浏览: 109
案例实战-SpringBoot整合EasyExcel实现列表导出功能
Spring Boot整合EasyExcel可以使得我们在使用Java编程语言操作Excel文件时更加方便快捷,无需手动处理Excel的复杂格式和数据类型转换问题。下面是一个简单的示例:
1. 引入EasyExcel依赖
在pom.xml文件中添加以下依赖:
```xml
<!-- EasyExcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
```
2. 创建Excel模板类
```java
@Data
public class ExcelData {
@ExcelProperty(value = "姓名", index = 0)
private String name;
@ExcelProperty(value = "年龄", index = 1)
private Integer age;
@ExcelProperty(value = "性别", index = 2)
private String gender;
}
```
3. 编写Excel读取代码
```java
@Service
public class ExcelService {
public List<ExcelData> readExcel(MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
List<ExcelData> list = new ArrayList<>();
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, new AnalysisEventListener<ExcelData>() {
@Override
public void invoke(ExcelData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
});
reader.read(new Sheet(1, 1, ExcelData.class));
return list;
}
}
```
4. 编写Excel导出代码
```java
@Service
public class ExcelService {
public void writeExcel(HttpServletResponse response, List<ExcelData> list) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("测试文件.xlsx", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
EasyExcel.write(response.getOutputStream(), ExcelData.class).sheet("测试").doWrite(list);
}
}
```
以上就是Spring Boot整合EasyExcel的基本示例,可以根据自己的需求进行修改和扩展。
阅读全文