ExcelUtil.java
10.4 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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package com.framework.excel;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddressList;
import com.google.common.collect.Maps;
public class ExcelUtil<T> {
private Class<T> clazz;
public ExcelUtil(Class<T> clazz) {
this.clazz = clazz;
}
public List<T> importExcel(String sheetName, InputStream input) {
int maxCol = 0;
List<T> list = new ArrayList<T>();
try {
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sheet = null;
if (!"".equals(sheetName.trim())) {
sheet = wb.getSheet(sheetName);
} else {
sheet = wb.getSheetAt(0); // 如果不指定sheet名默认指向第一个sheet
}
int rows = sheet.getPhysicalNumberOfRows();
if (rows > 0) {
// 有数据时处理
Field[] fields = clazz.getDeclaredFields();
Map<Integer, Field> fieldsMap = Maps.newHashMap();
for (Field field : fields) {
if (field.isAnnotationPresent(ExcelAnnotation.class)) {
ExcelAnnotation attr = field.getAnnotation(ExcelAnnotation.class);
int col = getExcelCol(attr.column());
maxCol = Math.max(col, maxCol);
field.setAccessible(true);
fieldsMap.put(col, field);
}
}
for (int i = 0; i < rows; i++) {
HSSFRow row = sheet.getRow(i);
int cellNum = maxCol;
T entity = null;
for (int j = 0; j < cellNum; j++) {
HSSFCell cell = row.getCell(j);
if (cell == null) {
continue;
}
int cellType = cell.getCellType();
String c = "";
if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
c = String.valueOf(cell.getNumericCellValue());
} else if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) {
c = String.valueOf(cell.getBooleanCellValue());
} else {
c = cell.getStringCellValue();
}
if (c == null || "".equals(c)) {
continue;
}
entity = entity == null ? clazz.newInstance() : entity; // 如果不存在实例则新建.
Field field = fieldsMap.get(j); // 从map中得到对应列的field.
if (field == null) {
continue;
}
// 取得类型,并根据对象类型设置值.
Class<?> fieldType = field.getType();
if (String.class == fieldType) {
field.set(entity, String.valueOf(c));
} else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
field.set(entity, Integer.parseInt(c));
} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
field.set(entity, Long.valueOf(c));
} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
field.set(entity, Float.valueOf(c));
} else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {
field.set(entity, Short.valueOf(c));
} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
field.set(entity, Double.valueOf(c));
} else if (Character.TYPE == fieldType) {
if ((c != null) && (c.length() > 0)) {
field.set(entity, Character.valueOf(c.charAt(0)));
}
}
if (entity != null) {
list.add(entity);
}
}
}
}
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 对list数据源将其里面的数据导入到excel表单
*
* @param sheetNames 工作表的名称
* @param output java输出流
*/
public boolean exportExcel(List<T>[] lists, String[] sheetNames, OutputStream output) {
if (lists.length != sheetNames.length) {
return false;
}
HSSFWorkbook workbook = new HSSFWorkbook(); // 产生工作薄对象
HSSFCellStyle style = workbook.createCellStyle();
for (int ii = 0; ii < lists.length; ii++) {
List<T> list = lists[ii];
String sheetName = sheetNames[ii];
List<Field> fields = getMappedFiled(clazz, null, ExcelAnnotation.class);
HSSFSheet sheet = workbook.createSheet(); // 产生工作表对象
workbook.setSheetName(ii, sheetName);
HSSFRow row;
HSSFCell cell; // 产生单元格
row = sheet.createRow(0); // 产生一行
// 写入各个字段的列头名称
for (int i = 0; i < fields.size(); i++) {
Field field = fields.get(i);
ExcelAnnotation attr = field.getAnnotation(ExcelAnnotation.class);
int col = getExcelCol(attr.column()); // 获得列号
cell = row.createCell(col); // 创建列
cell.setCellType(attr.cellType()); // 设置列中写入内容为String类型
cell.setCellValue(attr.name()); // 写入列名
// 如果设置了提示信息则鼠标放上去提示.
if (!"".equals(attr.prompt().trim())) {
setHSSFPrompt(sheet, "", attr.prompt(), 1, 100, col, col); // 这里默认设了2-101列提示.
}
// 如果设置了combo属性则本列只能选择不能输入
if (attr.combo().length > 0) {
setHSSFValidation(sheet, attr.combo(), 1, 100, col, col); // 这里默认设了2-101列只能选择不能输入.
}
cell.setCellStyle(style);
}
int startNo = 0;
int endNo = list.size();
// 写入各条记录,每条记录对应excel表中的一行
for (int i = startNo; i < endNo; i++) {
row = sheet.createRow(i + 1 - startNo);
T vo = (T) list.get(i); // 得到导出对象.
for (int j = 0; j < fields.size(); j++) {
Field field = fields.get(j); // 获得field.
field.setAccessible(true); // 设置实体类私有属性可访问
ExcelAnnotation attr = field.getAnnotation(ExcelAnnotation.class);
try {
// 根据ExcelAnnotation中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
if (attr.isExport()) {
cell = row.createCell(getExcelCol(attr.column())); // 创建cell
cell.setCellType(attr.cellType());
if (attr.cellType() == 0) {
cell.setCellValue(Double.parseDouble(field.get(vo).toString()));
} else {
cell.setCellValue(field.get(vo) == null ? "" : String.valueOf(field.get(vo)));
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
try {
output.flush();
workbook.write(output);
workbook.close();
output.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 对list数据源将其里面的数据导入到excel表单
*
* @param sheetName 工作表的名称
* @param output java输出流
*/
@SuppressWarnings("unchecked")
public boolean exportExcel(List<T> list, String sheetName, OutputStream output) {
List<T>[] lists = new ArrayList[1];
lists[0] = list;
String[] sheetNames = new String[1];
sheetNames[0] = sheetName;
return exportExcel(lists, sheetNames, output);
}
/**
* 设置单元格上提示
*
* @param sheet 要设置的sheet.
* @param promptTitle 标题
* @param promptContent 内容
* @param firstRow 开始行
* @param endRow 结束行
* @param firstCol 开始列
* @param endCol 结束列
* @return 设置好的sheet.
*/
public static HSSFSheet setHSSFPrompt(HSSFSheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, int firstCol, int endCol) {
// 构造constraint对象
DVConstraint constraint = DVConstraint.createCustomFormulaConstraint("DD1");
// 四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
// 数据有效性对象
HSSFDataValidation dataValidationView = new HSSFDataValidation(regions, constraint);
dataValidationView.createPromptBox(promptTitle, promptContent);
sheet.addValidationData(dataValidationView);
return sheet;
}
/**
*
* @Title: setHSSFValidation
* @Description: 设置某些列的值只能输入预制的数据,显示下拉框.
* @param sheet
* @param textlist
* @param firstRow
* @param endRow
* @param firstCol
* @param endCol
* @param @return
* @return HSSFSheet
* @throws
*/
public static HSSFSheet setHSSFValidation(HSSFSheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
// 加载下拉列表内容
DVConstraint constraint = DVConstraint.createExplicitListConstraint(textlist);
// 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
// 数据有效性对象
HSSFDataValidation dataValidationList = new HSSFDataValidation(regions, constraint);
sheet.addValidationData(dataValidationList);
return sheet;
}
/**
*
* @Title: getExcelCol
* @Description: 将EXCEL中A,B,C,D,E列映射成0,1,2,3
* @param col
* @param @return
* @return int
* @throws
*/
public static int getExcelCol(String col) {
col = col.toUpperCase();
// 从-1开始计算,字母重1开始运算。这种总数下来算数正好相同。
int count = -1;
char[] cs = col.toCharArray();
for (int i = 0; i < cs.length; i++) {
count += (cs[i] - 64) * Math.pow(26, cs.length - 1 - i);
}
return count;
}
/**
* 得到实体类所有通过注解映射了数据表的字段
*
* @param map
* @return
*/
@SuppressWarnings({"rawtypes", "unchecked" })
private List<Field> getMappedFiled(Class clazz, List<Field> fields, Class annoclass) {
if (fields == null) {
fields = new ArrayList<Field>();
}
Field[] allFields = clazz.getDeclaredFields(); // 得到所有定义字段
// 得到所有field并存放到一个list中.
for (Field field : allFields) {
if (field.isAnnotationPresent(annoclass)) {
fields.add(field);
}
}
if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)) {
getMappedFiled(clazz.getSuperclass(), fields, annoclass);
}
return fields;
}
}