今天看到了一篇文章说了
POI
和EasyExcel
的区别(说的是EasyExcel
是基于java的简单、省内存的Excel),因为我只用过POI
,所以想试一下EasyExcel
如何使用,所以才有了这篇文章
EasyExcel
的官方文档地址:https://www.yuque.com/easyexcel/doc/easyexcel
1、引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--MybatisPlus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!--EasyExcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
2、配置mysql数据库信息并使用代码生成器生成dao文件
2.1 在application.yml
中配置数据库信息
spring:
datasource:
url: jdbc:mysql://ip:port/dbName?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&allowMultiQueries=true&rewriteBatchedStatements=true
username: username #你自己的用户名
password: password #你自己的密码
application:
name: excel-demo
server:
port: 8081
# xml的位置
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
2.2 使用mybatisPlus的代码生成器生成service
、dao
、mapper
等文件
详情请看我上一篇文章《MybatisPlus 代码生成器》
结果:
3、测试导出excel的功能
3.1、TestController.java
/**
* @author miao
*/
@RestController
@RequestMapping("/test")
public class TestController {
@Resource
private IUserService userService;
@RequestMapping("/request")
private String test() {
return "ok";
}
@RequestMapping("/download")
private void download(HttpServletResponse response) {
List<User> list = userService.list();
// 写法1
String fileName = System.currentTimeMillis() + ".xlsx";
try {
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
ServletOutputStream out = response.getOutputStream();
EasyExcel.write(response.getOutputStream(), UserVo.class)
.sheet("sheet")
.doWrite(list);
} catch (IOException e) {
throw new RuntimeException("导出文件失败!");
}
}
}
3.2 请求地址 http://localhost:8081/test/request
结果: