AttachmentExportUtil.java
1.94 KB
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
package vion.utils.excel;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* @author vion
* @date 2024/2/26
*/
public class AttachmentExportUtil {
public static void export(Workbook workbook, String fileName, HttpServletResponse response) {
try {
String suffix = ".xlsx";
if (workbook instanceof HSSFWorkbook) {
if (fileName.endsWith(suffix)) {
fileName = fileName.substring(0, fileName.length() - 1);
}
suffix = ".xls";
response.setContentType("application/vnd.ms-excel");
} else {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
if (!fileName.endsWith(suffix)) {
fileName = fileName + suffix;
}
setAttachmentConfig(fileName, response);
workbook.write(response.getOutputStream());
} catch (IOException var7) {
throw new RuntimeException(var7);
} finally {
clear(workbook);
}
}
private static void clear(Workbook workbook) {
if (workbook instanceof SXSSFWorkbook) {
((SXSSFWorkbook) workbook).dispose();
}
try {
workbook.close();
} catch (IOException var2) {
var2.printStackTrace();
}
}
private static void setAttachmentConfig(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8").replace("+", "%20"));
}
}