Skip to content

Commit 39edb2c

Browse files
committed
perf: 添加excel导出工具类(ExcelUtil.java)
1 parent f6161c5 commit 39edb2c

File tree

2 files changed

+128
-11
lines changed

2 files changed

+128
-11
lines changed

springboot-aop/src/main/java/com/study/module/controller/StuController.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,14 @@
55
import com.study.module.enums.BusinessType;
66
import com.study.module.service.StuService;
77
import com.study.module.util.office.CsvUtil;
8+
import com.study.module.util.office.ExcelUtil;
89
import org.springframework.util.ObjectUtils;
910
import org.springframework.web.bind.annotation.*;
1011
import org.springframework.web.multipart.MultipartFile;
12+
import org.springframework.web.servlet.ModelAndView;
1113

1214
import javax.annotation.Resource;
15+
import javax.servlet.http.HttpServletResponse;
1316
import java.util.Map;
1417

1518
/**
@@ -38,6 +41,14 @@ public Map<String, Object> readCSV(@RequestParam(value = "multipartFile") Multip
3841
return CsvUtil.readCsv(multipartFile, true);
3942
}
4043

44+
@GetMapping("exportDbToExcel")
45+
@ResponseBody
46+
public ModelAndView downloadFile(HttpServletResponse response) {
47+
ExcelUtil.testExportExcel(response);
48+
return null;
49+
}
50+
51+
4152
/**
4253
* 通过主键查询单条数据
4354
*

springboot-aop/src/main/java/com/study/module/util/office/ExcelUtil.java

Lines changed: 117 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
11
package com.study.module.util.office;
22

3+
import lombok.AllArgsConstructor;
4+
import lombok.Builder;
5+
import lombok.Data;
6+
import lombok.NoArgsConstructor;
37
import org.apache.poi.hssf.usermodel.*;
48
import org.apache.poi.ss.usermodel.BorderStyle;
59
import org.apache.poi.ss.usermodel.Cell;
610
import org.apache.poi.ss.usermodel.HorizontalAlignment;
711
import org.apache.poi.ss.usermodel.VerticalAlignment;
812
import org.apache.poi.ss.util.CellRangeAddress;
9-
import org.apache.poi.xssf.usermodel.XSSFRow;
10-
import org.apache.poi.xssf.usermodel.XSSFSheet;
11-
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
13+
import org.apache.poi.xssf.usermodel.*;
1214
import org.slf4j.Logger;
1315
import org.slf4j.LoggerFactory;
1416
import org.springframework.util.ObjectUtils;
1517

16-
import java.io.ByteArrayOutputStream;
17-
import java.io.FileInputStream;
18-
import java.io.FileOutputStream;
19-
import java.io.IOException;
18+
import javax.servlet.http.HttpServletResponse;
19+
import java.io.*;
2020
import java.lang.reflect.Field;
21+
import java.lang.reflect.Method;
2122
import java.text.SimpleDateFormat;
22-
import java.util.Date;
23-
import java.util.Iterator;
24-
import java.util.List;
23+
import java.util.*;
2524

2625
/**
2726
* <pre>
@@ -35,7 +34,114 @@ public class ExcelUtil {
3534
private Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
3635

3736
public static void main(String[] args) throws IOException {
38-
deleteBlankAndRow("D:\\file44.xlsx", "D:\\file4.xlsx");
37+
// deleteBlankAndRow("D:\\file44.xlsx", "D:\\file4.xlsx");
38+
}
39+
40+
@Data
41+
@NoArgsConstructor
42+
@Builder
43+
@AllArgsConstructor
44+
static class User {
45+
private int id;
46+
private String name;
47+
private String sex;
48+
private int age;
49+
}
50+
51+
public static void testExportExcel(HttpServletResponse response) {
52+
Collection userList = new ArrayList<>();
53+
User user = new User(1, "张三", "男", 39);
54+
userList.add(user);
55+
user = new User(2, "如花", "女", 21);
56+
userList.add(user);
57+
58+
String[] headers = {"序号", "姓名", "性别", "年龄"};
59+
String fileName = "用户信息表";
60+
61+
ExcelUtil.exportExcel(headers, userList, fileName, response);
62+
}
63+
64+
/**
65+
* 导出数据到 excel中
66+
*
67+
* @param headers 表头
68+
* @param dataset 需要输出到excel的数据
69+
* @param fileName 输出excel文件所在地址(例如:D:/454e.xls)
70+
* @param response 输出
71+
*/
72+
public static void exportExcel(String[] headers, Collection<Object> dataset, String fileName, HttpServletResponse response) {
73+
// 声明一个工作薄
74+
XSSFWorkbook workbook = new XSSFWorkbook();
75+
// 生成一个表格
76+
XSSFSheet sheet = workbook.createSheet(fileName);
77+
// 设置表格默认列宽度为15个字节
78+
sheet.setDefaultColumnWidth((short) 20);
79+
// 产生表格标题行
80+
XSSFRow row = sheet.createRow(0);
81+
for (short i = 0; i < headers.length; i++) {
82+
XSSFCell cell = row.createCell(i);
83+
XSSFRichTextString text = new XSSFRichTextString(headers[i]);
84+
cell.setCellValue(text);
85+
}
86+
try {
87+
// 遍历集合数据,产生数据行
88+
Iterator<Object> it = dataset.iterator();
89+
int index = 0;
90+
while (it.hasNext()) {
91+
index++;
92+
row = sheet.createRow(index);
93+
Object t = it.next();
94+
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
95+
Field[] fields = t.getClass().getDeclaredFields();
96+
for (short i = 0; i < headers.length; i++) {
97+
XSSFCell cell = row.createCell(i);
98+
Field field = fields[i];
99+
String fieldName = field.getName();
100+
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
101+
Class tCls = t.getClass();
102+
Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
103+
Object value = getMethod.invoke(t, new Object[]{});
104+
// 判断值的类型后进行强制类型转换
105+
String textValue = null;
106+
// 其它数据类型都当作字符串简单处理
107+
if (value != null && value != "") {
108+
textValue = value.toString();
109+
}
110+
if (textValue != null) {
111+
XSSFRichTextString richString = new XSSFRichTextString(textValue);
112+
cell.setCellValue(richString);
113+
}
114+
}
115+
}
116+
getExportedFile(workbook, fileName, response);
117+
} catch (Exception e) {
118+
e.printStackTrace();
119+
}
120+
}
121+
122+
/**
123+
* 产生输出
124+
*
125+
* @param workbook excel文件对象
126+
* @param name 文件名称
127+
* @param response 返回输出excel文件的二进制流
128+
* @throws Exception
129+
*/
130+
public static void getExportedFile(XSSFWorkbook workbook, String name, HttpServletResponse response) throws Exception {
131+
BufferedOutputStream fos = null;
132+
try {
133+
String fileName = name + ".xlsx";
134+
response.setContentType("application/x-msdownload");
135+
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
136+
fos = new BufferedOutputStream(response.getOutputStream());
137+
workbook.write(fos);
138+
} catch (Exception e) {
139+
e.printStackTrace();
140+
} finally {
141+
if (fos != null) {
142+
fos.close();
143+
}
144+
}
39145
}
40146

41147
/**

0 commit comments

Comments
 (0)