通用excel导出demo

通用excel导出demo(利用反射)

最近项目后台管理系统好多地方都要用到excel导出。考虑到一次次修改原代码太无聊,各方面拼拼凑凑写出个通用类,传几个参数设定下表头就ok了。对反射的概念和相关api了解又加深了点…代码记录如下:

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
103
104
105
106
107
108
109
110
111
112
113
import org.apache.poi.hssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class PoiTool {
/**
*
* @param list 数据源list
* @param beanClass list中Object的Class对象
* @param map 表头名与对应字段集合(需预定义,例{<用户名,username><密码,password>})
* @param response 响应对象
* @throws IllegalAccessException
* @throws InstantiationException
* @throws InvocationTargetException
*/
public static void exportExcel(List list, Class beanClass, LinkedHashMap<String, String> map, HttpServletResponse response)
throws IllegalAccessException, InstantiationException, InvocationTargetException {
int j = 0;
String valueStr = "";
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("sheet1");
HSSFCellStyle style = wb.createCellStyle();//样式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFRow row = sheet.createRow(0);//第一行
for (Map.Entry<String, String> m : map.entrySet()) {//导入excel表头
HSSFCell cell = row.createCell(j);
cell.setCellValue(m.getKey());
cell.setCellStyle(style);
sheet.autoSizeColumn(j);
valueStr += m.getValue() + "|";//filed字符串
j++;
}
valueStr = valueStr.substring(0, valueStr.length() - 1);
System.out.println(valueStr);
String[] valueArray = valueStr.split("\\|");//filed数组
//通过反射获取对应beanClass中的字段
//并将其转为get方法置入集合中
Field field[] = beanClass.getDeclaredFields();
List<Method> methodlist = new ArrayList<>();
for (int i = 0; i < field.length; i++) {
String fieldName = field[i].getName();
StringBuffer methodName = new StringBuffer("get");
methodName.append(fieldName.substring(0, 1).toUpperCase());
methodName.append(fieldName.substring(1));
Method getMethod = null;
try {
getMethod = beanClass.getMethod(methodName.toString());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
methodlist.add(getMethod);
}
//遍历list,并插入数据
for (int i = 0; i < list.size(); i++) {
row = sheet.createRow(i + 1);//创建行,从第二行开始
for (int k = 0; k < valueArray.length; k++) {//遍历column
Method getMethod = getCurrentMethod(valueArray[k], methodlist);//获取colunm对应的get方法
if (getMethod.getReturnType().toString().indexOf("int") >= 0) {
row.createCell(k).setCellValue((int) getMethod.invoke(list.get(i), new Object[]{}));
} else if (getMethod.getReturnType().toString().indexOf("String") >= 0) {
row.createCell(k).setCellValue((String) getMethod.invoke(list.get(i), new Object[]{}));
} else if (getMethod.getReturnType().toString().indexOf("double") >= 0) {
row.createCell(k).setCellValue((double) getMethod.invoke(list.get(i), new Object[]{}));
} else if (getMethod.getReturnType().toString().indexOf("float") >= 0) {
row.createCell(k).setCellValue((float) getMethod.invoke(list.get(i), new Object[]{}));
}
}
sheet.autoSizeColumn(i);
}
response.reset();
response.setContentType("application/vnd.ms-excel;charset=gb2312");
response.setHeader("Content-disposition", "attachment;filename=excel.xls");
try {
OutputStream outputStream = response.getOutputStream();
wb.write(outputStream);
wb.close();
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//获取当前column的get方法
public static Method getCurrentMethod(String valueArray, List<Method> methodlist) {
if (valueArray != null && methodlist.size() > 0) {
for (int i = 0; i < methodlist.size(); i++) {
if (methodName(methodlist.get(i).getName()).equals(valueArray)) {
return methodlist.get(i);
}
}
}
return null;
}
//处理methodName
public static String methodName(String str) {
if (str != null) {
str = str.substring(3).substring(0, 1).toLowerCase() + str.substring(3).substring(1);
return str;
}
return null;
}
}