# Jxls 导出 Excel
Springboot 中使用 Jxls 导出 Excel
# 添加依赖
<!--Jxls Excel-->
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls</artifactId>
<version>2.8.1</version>
</dependency>
<!--To use Apache POI API based transformer implementation add the following dependency -->
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-poi</artifactId>
<version>2.8.1</version>
</dependency>
<!--To use Java Excel API based transformer implementation add the following dependency -->
<!-- https://mvnrepository.com/artifact/org.jxls/jxls-jexcel -->
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-jexcel</artifactId>
<version>1.0.9</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 定义导出实体类Fish.java
package com.gaolei.app.entity;
import lombok.Data;
/**
* @author DuebassLei
* @version 1.0
* @date 2020/10/12 17:07
*/
@Data
public class Fish {
/**
* 名称
* */
private String name;
/**
* 价格
**/
private String price;
/**
* 品种
* */
private String kind;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 定义excel
模板
# 定义控制器JxlsController.java
@Slf4j
@Controller
@RequestMapping(value = "/api/jxls")
public class JxlsController {
@PostMapping(value = "export")
public void jxlsExport(HttpServletRequest request,HttpServletResponse response) throws IOException {
log.info("Jxls 导出excel数据");
//模拟数据
List<Fish> fishList = new ArrayList<>();
for (int i = 0; i < 100 ; i++) {
Fish fish = new Fish();
fish.setName("小鲤鱼"+i);
fish.setKind("鲤鱼"+i);
fish.setPrice("20"+i);
fishList.add(fish);
}
InputStream is = new ClassPathResource("templates/fish.xls").getInputStream();
OutputStream os = null;
try {
os = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename=" + "fish.xls");
response.setContentType("application/octet-stream");
Context context = new Context();
context.putVar("fishList", fishList);
JxlsHelper.getInstance().processTemplate(is, os, context);
} catch (IOException e) {
e.printStackTrace();
}finally {
os.flush();
os.close();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Postman测试
测试接口地址:
http://localhost:9999/api/jxls/export
##导出数据效果
更多功能详见Jxls
官方Api