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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package com.yanzuoguang.cloud.excel;
import com.yanzuoguang.cloud.helper.HttpFileHelper;
import com.yanzuoguang.excel.ExcelConsole;
import com.yanzuoguang.excel.ExcelRow;
import com.yanzuoguang.excel.ExportBase;
import com.yanzuoguang.excel.ExportData;
import com.yanzuoguang.util.helper.StringHelper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* HTTP方式下载Excel文件
*
* @param <T> 行数据的类型
* @author 颜佐光
*/
public class ExcelHttp<T extends Object> extends ExcelConsole<T> {
/**
* 导出成Excel
*
* @param exportData 导出信息
*/
public ExcelHttp(ExportData exportData) {
super(exportData);
}
/**
* 导出成Excel
*
* @param config 导出信息
* @param rowHandle 导出下载信息
*/
public ExcelHttp(ExportData config, ExcelRow<T> rowHandle) {
super(config, rowHandle);
}
/**
* 下载文件
*
* @param response 输出流
*/
public ExcelHttp down(HttpServletResponse response) throws IOException {
return this.down(response, StringHelper.EMPTY);
}
/**
* 下载文件
*
* @param response 输出流
* @param downFileName 下载文件名
*/
public ExcelHttp down(HttpServletResponse response, String downFileName) throws IOException {
if (StringHelper.isEmpty(downFileName)) {
downFileName = this.getConfig().getDownFileName();
}
if (StringHelper.isEmpty(downFileName)) {
downFileName = this.getConfig().getFileName();
}
HttpFileHelper.localToDown(this.getFileName(), downFileName, response);
return this;
}
/**
* 导出数据
*
* @param req 请求对接
* @param response 输出结果
* @param excelDao dao层实现接口
*/
public static <T extends Object, M extends Object> void export(ExportBase<T> req, HttpServletResponse response, ExcelDao<T, M> excelDao) {
ExportData config = req.getConfig();
if (config == null) {
throw new RuntimeException("导出时请传入配置信息");
}
if (StringHelper.isEmpty(config.getServerPath())) {
config.setServerPath("/home/cache/");
}
if (StringHelper.isEmpty(config.getFileName())) {
config.setFileName(String.format("%s.xlsx", StringHelper.getNewID()));
}
if (StringHelper.isEmpty(config.getDownFileName())) {
config.setDownFileName(String.format("%s-%s.xlsx", config.getTitle(), config.getSubTitle()));
}
ExcelHttp<M> excel = new ExcelHttp<>(config);
try {
excel.open();
excelDao.export(excel, req.getCond());
excel.save();
excel.down(response);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("下载失败", e);
} finally {
// 删除生成的临时文件
excel.remove();
}
}
}