数据导出成Excel表格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
js复制代码//Controller层
@PostMapping(value = "/exportPlanDemandList")
@ApiOperation("需求条目导出")
@AdviceLog(value = "需求条目导出", type = LogType.OPERATE, operateType = LogOperateType.EXPORT)
public void exportDemandList(@RequestBody DemandPlanListVo vo, OutputStream out) {
try {
String sheetName = "需求条目";
// 获取所需数据的分页
Pager pager = demandPlanListService.getDemandListPage(vo);
// 将查询出的数据集合传入
List<Map<String, Object>> list = ConvertUtils.listConvert(pager.getRows());
String[] excelTilte = BasisFormationConstant.excelDemandList2;
String[] headerTitle = Arrays.stream(excelTilte).map(e -> e.split(":")[1]).toArray(size -> new String[size]);
String[] headerValues = Arrays.stream(excelTilte).map(e -> e.split(":")[0]).toArray(size -> new String[size]);
ExcelUtil.exportExcel2007WithSXSSF(sheetName, headerTitle, headerValues, list, out, null);
} catch (Exception e) {
e.printStackTrace();
}
}
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
js复制代码
public class ConvertUtils {
private static final String CHINA_GREEN = "绿色";
private static final String ENG_GREEN = "green";

private static final String CHINA_RED = "红色";
private static final String ENG_RED = "red";

private static final String CHINA_ORANGE = "橙色";
private static final String ENG_ORANGE = "orange";

private static final String CHINA_PURPLE = "紫色";
private static final String ENG_PURPLE = "purple";

private static final String CHINA_YELLOW = "黄色";
private static final String ENG_YELLOW = "yellow";

private static final String CHINA_BLUE = "蓝色";
private static final String ENG_BLUE = "#0c60aa";





/**
* list克隆
*
* @param sources
* @param c
* @param <E>
* @param <T>
* @return
*/
public static <E, T> List<T> convertList(List<E> sources, Class<T> c) {
if (CollectionUtils.isEmpty(sources)) {
return new ArrayList<T>();
}
List<T> list = new ArrayList<T>();
for (E source : sources) {
list.add(convertBean(source, c));
}
return list;
}
/**
* param convert entity
* @param param
* @param tClass
* @param <T>
* @param <E>
* @return
*/
public static <T, E> T convertBean(E param, Class<T> tClass) {
try {
if (param == null) {
return tClass.newInstance();
}
T instance = tClass.newInstance();
BeanUtils.copyProperties(param, instance);
return instance;
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
return null;
}
}

public static <T> List<Map<String, Object>> listConvert(List<T> list) {
// 定义List<Map<String, Object>>数组<br>          
// list为外部传进来的list集合
List<Map<String, Object>> list_map = new ArrayList<Map<String, Object>>();
if (org.apache.commons.collections.CollectionUtils.isNotEmpty(list)) {
//PropertyUtils.describe(Object)转换
list.forEach(item -> {
Map<String, Object> map = null;
try {
map = (Map<String, Object>) PropertyUtils.describe(item);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
list_map.add(map);
});
}
return list_map;
}

public static String convertBinaryColor(String color){
if(StringUtil.isNotEmpty(color)){
color=color.replace(CHINA_GREEN,ENG_GREEN);
color=color.replace(CHINA_RED,ENG_RED);
color=color.replace(CHINA_ORANGE,ENG_ORANGE);
color=color.replace(CHINA_PURPLE,ENG_PURPLE);
color=color.replace(CHINA_YELLOW,ENG_YELLOW);
color=color.replace(CHINA_BLUE,ENG_BLUE);
}
return color;
}


/**
* 特殊将字符串转义
* @param value
* @return
*/
public static String escapeStr(String value)
{
StringBuffer result=new StringBuffer();
if(value == null){
return null;
}else{
char content[] = new char[value.length()];
value.getChars(0, value.length(), content, 0);
result = new StringBuffer(content.length + 50);
for(int i = 0; i < content.length; i++)
switch(content[i])
{
case 34: // '"'
result.append("&quot;");
break;

case 38: // '&'
result.append("&amp;");
break;

case 39: // '''
result.append("&#39;");
break;

case 60: // '<'
result.append("&lt;");
break;

case 62: // '>'
result.append("&gt;");
break;

default:
result.append(content[i]);
break;
}
}
return result.toString();
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
js复制代码// 常量类(表格的类名)
public class BasisFormationConstant {
public static final String[] excelDemandList2 = new String[] {
"num:编号",
"demandName:需求名称",
"demandCategoryName:需求类别",
"demandLevel:对应层级",
"demandTypeName:需求验证类型",
"demandProduct:承接产品",
"remark:说明",
"resourceName:需求来源",
"verifyStatus:验证状态",
"demandStatus:需求状态",
"isIcon:是否包含图标",
"createTime:创建时间"
};
}
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
js复制代码public class ExcelUtil {

// 2003 版本 最大支持65536 行
public final static String EXCEL_FILE_2003 = "2003";
// 2007 版本以上 最大支持1048576行
public final static String EXCEl_FILE_2007 = "2007";
// 2007 版本以上 大数据量导出
public final static String EXCEl_FILE_2007_SXSSF = "2007_SXSSF";

/**
* <p>
* 导出无头部标题行Excel <br>
* 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
* </p>
*
* @param title 表格标题
* @param headersField 表格字段集合
* @param dataList 数据集合
* @param out 输出流
* @param version 2003 或者 2007,不传时默认生成2003版本
* @throws IOException
*/
public static void exportExcel(String title, String[] headersField, List<Map<String, Object>> dataList, OutputStream out,
String version) throws IOException {
if (StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())) {
exportExcel2003(title, null, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss");
} else if(EXCEl_FILE_2007_SXSSF.equals(version.trim())) {
exportExcel2007WithSXSSF(title, null, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss");
} else {
exportExcel2007(title, null, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss");
}
}

/**
* <p>
* 导出带有头部标题行的Excel <br>
* 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
* </p>
*
* @param title 表格标题
* @param headers 头部标题集合
* @param headersField 表格头部标题对应的字段集合
* @param dataList 数据集合
* @param out 输出流
* @param version 2003 或者 2007,不传时默认生成2003版本
* @throws IOException
*/
public static void exportExcel(String title, String[] headers, String[] headersField, List<Map<String, Object>> dataList,
OutputStream out, String version) throws IOException {
if (StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())) {
exportExcel2003(title, headers, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss");
} else if(EXCEl_FILE_2007_SXSSF.equals(version.trim())) {
exportExcel2007WithSXSSF(title, headers, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss");
} else {
exportExcel2007(title, headers, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss");
}
}

/**
* <p>
* 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
* 此版本生成2007以上版本的文件 (文件后缀:xlsx)
* </p>
*
* @param title
* 表格标题名
* @param headers
* 表格头部标题集合
* @param headersField
* 表格头部标题对应的字段集合
* @param dataList
* 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
* JavaBean属性的数据类型有基本数据类型及String,Date
* @param out
* 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
* @throws IOException
*/
public static void exportExcel2007WithSXSSF(String title, String[] headers, String[] headersField,
List<Map<String, Object>> dataList, OutputStream out, String pattern) throws IOException {

SXSSFWorkbook workbook = null;
try {
// 声明一个工作薄
workbook = new SXSSFWorkbook();
// 生成一个表格
Sheet sheet = workbook.createSheet(title);
sheet.setDefaultColumnWidth(30);
// 生成一个样式
CellStyle headerStyle = workbook.createCellStyle();
// 设置这些样式
headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
// 生成一个字体
org.apache.poi.ss.usermodel.Font font = workbook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 16);
headerStyle.setFont(font);

// 生成并设置另一个样式
CellStyle dataStyle = workbook.createCellStyle();
/* dataStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
dataStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);*/
// 生成另一个字体
org.apache.poi.ss.usermodel.Font font2 = workbook.createFont();
dataStyle.setFont(font2);

// 产生表格标题行
Row row = sheet.createRow(0);
Cell cellHeader;
if(headers!=null){
for (int i = 0; i < headers.length; i++) {
cellHeader = row.createCell(i);
cellHeader.setCellStyle(headerStyle);
cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
}
}

// 遍历集合数据,产生数据行
Iterator<Map<String, Object>> it = dataList.iterator();
Map<String, Object> map;
int index = 0;
Object value;
String textValue;
Cell cell;
Matcher matcher;
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
SimpleDateFormat sdf=null;
if(StringUtils.isNotEmpty(pattern)){
sdf = new SimpleDateFormat(pattern);
}else{
sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
}
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
map = (Map<String,Object>) it.next();
for (int n = 0; n < headersField.length; n++) {
cell = row.createCell(n);
cell.setCellStyle(dataStyle);
value = map.get(headersField[n]);
// 判断值的类型后进行强制类型转换
textValue = null;
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Float) {
textValue = String.valueOf((Float) value);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
textValue = String.valueOf((Double) value);
cell.setCellValue(textValue);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
}
if (value instanceof Boolean) {
textValue = "是";
if (!(Boolean) value) {
textValue = "否";
}
} else if (value instanceof Date) {
textValue = sdf.format((Date) value);
} else {
// 其它数据类型都当作字符串简单处理
if (value != null) {
textValue = value.toString();
}
}
if (textValue != null) {
matcher = p.matcher(textValue);
if (matcher.matches()) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
cell.setCellValue(textValue);
}
}
}
}

workbook.write(out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
throw e;
}finally {
if(workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* <p>
* 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
* 此版本生成2007以上版本的文件 (文件后缀:xlsx)
* </p>
*
* @param title
* 表格标题名
* @param headers
* 表格头部标题集合
* @param headersField
* 表格头部标题对应的字段集合
* @param dataList
* 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
* JavaBean属性的数据类型有基本数据类型及String,Date
* @param out
* 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
* @throws IOException
*/
public static void exportExcel2007(String title, String[] headers, String[] headersField,
List<Map<String, Object>> dataList, OutputStream out, String pattern) throws IOException {

XSSFWorkbook workbook = null;
try {
// 声明一个工作薄
workbook = new XSSFWorkbook();
// 生成一个表格
XSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为30个字节
sheet.setDefaultColumnWidth(30);
// 生成一个样式
XSSFCellStyle headerStyle = workbook.createCellStyle();
// 设置这些样式
headerStyle.setFillForegroundColor(new XSSFColor(new Color(217, 217, 217)));
// 生成一个字体
XSSFFont font = workbook.createFont();
font.setFontName("宋体");
font.setColor(new XSSFColor(Color.BLACK));
font.setFontHeightInPoints((short) 16);
// 把字体应用到当前的样式
headerStyle.setFont(font);

// 生成并设置另一个样式
XSSFCellStyle dataStyle = workbook.createCellStyle();
/* dataStyle.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
dataStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);*/
// 生成另一个字体
XSSFFont font2 = workbook.createFont();
// 把字体应用到当前的样式
dataStyle.setFont(font2);

// 产生表格标题行
XSSFRow row = sheet.createRow(0);
XSSFCell cellHeader;
if(headers!=null){
for (int i = 0; i < headers.length; i++) {
cellHeader = row.createCell(i);
cellHeader.setCellStyle(headerStyle);
cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
}
}


// 遍历集合数据,产生数据行
Iterator<Map<String, Object>> it = dataList.iterator();
Map<String, Object> map;
int index = 0;
Object value;
String textValue;
XSSFCell cell;
XSSFRichTextString richString;
Matcher matcher;
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
SimpleDateFormat sdf=null;
if(StringUtils.isNotEmpty(pattern)){
sdf = new SimpleDateFormat(pattern);
}else{
sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
}
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
map = (Map<String,Object>) it.next();
for (int n = 0; n < headersField.length; n++) {
cell = row.createCell(n);
cell.setCellStyle(dataStyle);
value = map.get(headersField[n]);
// 判断值的类型后进行强制类型转换
textValue = null;
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Float) {
textValue = String.valueOf((Float) value);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
textValue = String.valueOf((Double) value);
cell.setCellValue(textValue);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
}
if (value instanceof Boolean) {
textValue = "是";
if (!(Boolean) value) {
textValue = "否";
}
} else if (value instanceof Date) {
textValue = sdf.format((Date) value);
} else {
// 其它数据类型都当作字符串简单处理
if (value != null) {
textValue = value.toString();
}
}
if (textValue != null) {
matcher = p.matcher(textValue);
if (matcher.matches()) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
richString = new XSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
}
}

workbook.write(out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
throw e;
}finally {
if(workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* <p>
* 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
* 此方法生成2003版本的excel,文件名后缀:xls <br>
* </p>
*
* @param title
* 表格标题名
* @param headers
* 表格头部标题集合
* @param headersField
* 表格头部标题对应的字段集合
* @param dataList
* 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
* JavaBean属性的数据类型有基本数据类型及String,Date
* @param out
* 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
* @throws IOException
*/
public static void exportExcel2003(String title, String[] headers, String[] headersField,
List<Map<String, Object>> dataList, OutputStream out, String pattern) throws IOException {

HSSFWorkbook workbook = null;
try {
// 声明一个工作薄
workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为20个字节
sheet.setDefaultColumnWidth(20);
// 生成一个样式
HSSFCellStyle headerStyle = workbook.createCellStyle();
// 设置这些样式
// 生成一个字体
HSSFFont font = workbook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 11);
// 把字体应用到当前的样式
headerStyle.setFont(font);

// 生成并设置另一个样式
HSSFCellStyle dataStyle = workbook.createCellStyle();
// 生成另一个字体
HSSFFont font2 = workbook.createFont();
// 把字体应用到当前的样式
dataStyle.setFont(font2);

// 产生表格标题行
HSSFRow row = sheet.createRow(0);
HSSFCell cellHeader;
if(headers!=null && headers.length>0){
for (int i = 0; i < headers.length; i++) {
cellHeader = row.createCell(i);
cellHeader.setCellStyle(headerStyle);
cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
}
}

// 遍历集合数据,产生数据行
Iterator<Map<String,Object>> it = dataList.iterator();
Map<String,Object> map;
int index = 0;
Object value;
String textValue;
HSSFCell cell;
HSSFRichTextString richString;
Matcher matcher;
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
map = (Map<String,Object>) it.next();
for (int n = 0; n < headersField.length; n++) {
cell = row.createCell(n);
cell.setCellStyle(dataStyle);
value = map.get(headersField[n]);
// 判断值的类型后进行强制类型转换
textValue = null;
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Float) {
textValue = String.valueOf((Float) value);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
textValue = String.valueOf((Double) value);
cell.setCellValue(textValue);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
}
if (value instanceof Boolean) {
textValue = "是";
if (!(Boolean) value) {
textValue = "否";
}
} else if (value instanceof Date) {
textValue = sdf.format((Date) value);
} else {
// 其它数据类型都当作字符串简单处理
if (value != null) {
textValue = value.toString();
}
}
if (textValue != null) {
matcher = p.matcher(textValue);
if (matcher.matches()) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
richString = new HSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
}
}

workbook.write(out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
throw e;
}finally {
if(workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%