ReportUtils.java
29.1 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
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
package com.bsth.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.bsth.common.ResponseCode;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
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.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import com.bsth.entity.Line;
import com.bsth.entity.realcontrol.ScheduleRealInfo;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
public class ReportUtils {
// private final String packaegName = "com.bsth.entity.";
private final String packaegName = "com.bsth.entity.realcontrol.";
/**
* /**
*
* @param list
* 模板中,需要重复显示的行所需的数据
* @param map
* 模板中除以上list外所有的数据
* @param index
* 需要重复的行号,该值为行号减1
* @param sourcePath
* 模板路径
* @param targetPath
* 生成路径
*/
public void excelReplace(List<Iterator<?>> list, Object[] tArray,
String sourcePath, String targetPath) {
try {
// 把源文件放入流中
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(
sourcePath));
HSSFWorkbook wb = new HSSFWorkbook(fs);
if(tArray.length != 0 && tArray[0] instanceof java.util.Map){
Map<String, Object> m = (Map<String, Object>)tArray[0];
if(m.containsKey("sheetName") && m.get("sheetName")!=null
&& m.get("sheetName").toString().trim().length()!=0)
wb.setSheetName(0, m.get("sheetName").toString());
}
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell = null;
String key;
// 取得总行数
int rowNum = sheet.getLastRowNum();
// 取得总列数
int cellNum = sheet.getRow(0).getLastCellNum();
// 遍历行
for (int i = 0; i < rowNum; i++) {
row = sheet.getRow(i);
// 遍历列
for (int j = 0; j < cellNum; j++) {
if (row == null) {
continue;
}
cell = row.getCell(j);
if (cell == null) {
continue;
}
// 取得每列的内容,如果列内容是$key$格式,则替换内容
key = getCellValue(cell);
if (key != null && (key.indexOf("$") != -1 || key.indexOf("#list#") != -1)) {
// * 列中内容有#list#,则表示该行为模板行,需要以该行为模板
// * 例如:模板行格式 #list#0_0 $Car.id$
// * 第一个0表示需要在list中取iterator的索引值
// * 第二个0表示在iterator中取的第几个对象,如果不为0,则取下一个对象,而不是沿用前面获取的对象
// * $Car.id$表示所取的对象为Car的对象,并且取值为id的值
if (key.indexOf("#list#") != -1) {
key = key.replace("#list#", "").trim();
String[] lists = key.split(" ");
// 取得list中的索引值
int listIndex = Integer
.valueOf(lists[0].split("_")[0]);
Iterator<?> iterator = list.get(listIndex);
// 根据模板创建行并填弃数据,返回增加的行数
int rowCount = iteratorFillCellValue(wb, sheet,
cell, iterator, i, rowNum, key);
rowNum += rowCount;
i += rowCount;
break;
} else {
// 直接填充数据的列,从对象数组中取得值,这里的数组不传值
getValueAndSetCellValue(cell, key, tArray, new String[]{""});
}
}
}
}
// 创建目标文件夹
createFolder(targetPath);
// 输出文件
FileOutputStream fileOut = new FileOutputStream(targetPath);
wb.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param sheetList 多sheet模板中,需要重复显示的行所需的数据
* @param tArray
* @param sourcePath 模板路径
* @param targetPath 生成路径
*/
public void excelMoreSheetReplace(List<List<Iterator<?>>> sheetList, Object[] tArray,
String sourcePath, String targetPath) {
try {
// 把源文件放入流中
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(
sourcePath));
HSSFWorkbook wb = new HSSFWorkbook(fs);
for (int s=0; s<sheetList.size(); s++){
List<Iterator<?>> list = sheetList.get(s);
if(tArray.length != 0 && tArray[0] instanceof java.util.Map){
Map<String, Object> m = (Map<String, Object>)tArray[0];
if(m.containsKey("sheetName"+s+1) && m.get("sheetName"+s+1)!=null
&& m.get("sheetName"+s+1).toString().trim().length()!=0)
wb.setSheetName(0, m.get("sheetName"+s+1).toString());
}
HSSFSheet sheet = wb.getSheetAt(s);
HSSFRow row;
HSSFCell cell = null;
String key;
// 取得总行数
int rowNum = sheet.getLastRowNum();
// 取得总列数
int cellNum = sheet.getRow(0).getLastCellNum();
// 遍历行
for (int i = 0; i <= rowNum; i++) {
row = sheet.getRow(i);
// 遍历列
for (int j = 0; j < cellNum; j++) {
if (row == null) {
continue;
}
cell = row.getCell(j);
if (cell == null) {
continue;
}
// 取得每列的内容,如果列内容是$key$格式,则替换内容
key = getCellValue(cell);
if (key != null && (key.indexOf("$") != -1 || key.indexOf("#list#") != -1)) {
// * 列中内容有#list#,则表示该行为模板行,需要以该行为模板
// * 例如:模板行格式 #list#0_0 $Car.id$
// * 第一个0表示需要在list中取iterator的索引值
// * 第二个0表示在iterator中取的第几个对象,如果不为0,则取下一个对象,而不是沿用前面获取的对象
// * $Car.id$表示所取的对象为Car的对象,并且取值为id的值
if (key.indexOf("#list#") != -1) {
key = key.replace("#list#", "").trim();
String[] lists = key.split(" ");
// 取得list中的索引值
int listIndex = Integer
.valueOf(lists[0].split("_")[0]);
Iterator<?> iterator = list.get(listIndex);
// 根据模板创建行并填充数据,返回增加的行数
int rowCount = iteratorFillCellValue(wb, sheet,
cell, iterator, i, rowNum, key);
rowNum += rowCount;
i += rowCount;
break;
} else {
// 直接填充数据的列,从对象数组中取得值,这里的数组不传值
getValueAndSetCellValue(cell, key, tArray, new String[]{""});
}
}
}
}
}
// 创建目标文件夹
createFolder(targetPath);
// 输出文件
FileOutputStream fileOut = new FileOutputStream(targetPath);
wb.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将file1中的一页sheet复制到file2中
*
* @param file1
* 原sheet所在的excel文件
* @param file2
* 目标excel文件
* @param page
* 原excel中要被复制的sheet的位置(从0开始)
* @param rate
* 调整复制后的缩放倍率(列如:145,则为缩放145%)
*/
public void copySheetByFile(File file1, File file2, int page, int rate) {
try {
// 把源文件放入流中
POIFSFileSystem fs1 = new POIFSFileSystem(new FileInputStream(file1));
HSSFWorkbook wb1 = new HSSFWorkbook(fs1);
HSSFSheet sheet = wb1.getSheetAt(page);
POIFSFileSystem fs2 = new POIFSFileSystem(new FileInputStream(file2));
HSSFWorkbook wb2 = new HSSFWorkbook(fs2);
HSSFSheet createSheet = wb2.createSheet(sheet.getSheetName());
HSSFCellStyle createCellStyle = wb2.createCellStyle();
HSSFRow row;
createSheet.setZoom(rate, 100);
for(int i = 0; i < sheet.getRow(0).getPhysicalNumberOfCells(); i++){
createSheet.setColumnWidth(i, sheet.getColumnWidth(i));
}
List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
for(int l = 0; l < mergedRegions.size(); l++){
//复制源表中的合并单元格
createSheet.addMergedRegion(mergedRegions.get(l));
}
int firstRow = sheet.getFirstRowNum();
int lastRow = sheet.getLastRowNum();
for(int k = firstRow; k <= lastRow; k++){
// 创建新建excel Sheet的行
HSSFRow rowCreat = createSheet.createRow(k);
// 取得源有excel Sheet的行
row = sheet.getRow(k);
// rowCreat.setHeight(row.getHeight()); //设置行高
// 单元格式样
int firstCell = row.getFirstCellNum();
int lastCell = row.getLastCellNum();
for (int j = firstCell; j < lastCell; j++) {
// 自动适应列宽 貌似不起作用
// createSheet.autoSizeColumn(j);
// System.out.println(row.getCell(j));
rowCreat.createCell(j);
String strVal = "";
if (row.getCell(j)==null) {
} else {
strVal = row.getCell(j).getStringCellValue();
rowCreat.getCell(j).setCellValue(strVal);
copyCellStyle(wb1, row.getCell(j).getCellStyle(), createCellStyle);
createCellStyle.setBorderTop((short)1);
createCellStyle.setBorderLeft((short)1);
createCellStyle.setBorderRight((short)1);
createCellStyle.setBorderBottom((short)1);
rowCreat.getCell(j).setCellStyle(createCellStyle);
}
}
}
// int firstRowNum = createSheet.getFirstRowNum();
// int lastRowNum = createSheet.getLastRowNum();
// int test = 0;
// for(int k = firstRowNum; k <= lastRowNum; k++){
// HSSFRow createRow = createSheet.getRow(k);
// int firstCellNum = createRow.getFirstCellNum();
// int lastCellNum = createRow.getLastCellNum();
// for(int i = firstCellNum; i < lastCellNum; i++){
// HSSFCell cell = createRow.getCell(i);
// cell.getCellStyle().setBorderTop(HSSFCellStyle.BORDER_THIN);
// cell.getCellStyle().setBorderLeft(HSSFCellStyle.BORDER_THIN);
// cell.getCellStyle().setBorderRight(HSSFCellStyle.BORDER_THIN);
// cell.getCellStyle().setBorderBottom(HSSFCellStyle.BORDER_THIN);
// test ++;
// }
// }
// System.out.println("test = " + test);
FileOutputStream fileOut = new FileOutputStream(file2);
wb2.write(fileOut);
fileOut.close();
wb2.close();
wb1.close();
fs2.close();
fs1.close();
file1.delete();
// // 创建目标文件夹
// createFolder(targetPath);
// 输出文件
} catch (Exception e) {
e.printStackTrace();
}
}
public void test(File file){
POIFSFileSystem fs;
try {
fs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook wb = new HSSFWorkbook(fs);
for(int j = 0; j < wb.getNumberOfSheets(); j++){
HSSFSheet sheet = wb.getSheetAt(j);
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
int test = 0;
for(int k = firstRowNum; k <= lastRowNum; k++){
HSSFRow createRow = sheet.getRow(k);
int firstCellNum = createRow.getFirstCellNum();
int lastCellNum = createRow.getLastCellNum();
for(int i = firstCellNum; i < lastCellNum; i++){
HSSFCell cell = createRow.getCell(i);
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cell.setCellStyle(cellStyle);
test ++;
}
}
System.out.println("test = " + test);
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getCellValue(HSSFCell cell) {
int cellType = 0;
String result = "";
double d;
if(cell != null) {
// 获取列数据类型
cellType = cell.getCellType();
// 不同列数据类型,取值方法不同
switch(cellType) {
// String
case HSSFCell.CELL_TYPE_STRING:
result = cell.getStringCellValue().toString();
break;
// numeric类型,excel中,日期格式会转成数字格式存储
case HSSFCell.CELL_TYPE_NUMERIC:
result = cell.getNumericCellValue()+"";
break;
// 公式类型
case HSSFCell.CELL_TYPE_FORMULA:
result = cell.getCellFormula() + "";
break;
// boolean类型
case HSSFCell.CELL_TYPE_BOOLEAN:
result = cell.getBooleanCellValue() + "";
break;
// 空格
case HSSFCell.CELL_TYPE_BLANK:
result = null;
break;
// 错误值
case HSSFCell.CELL_TYPE_ERROR:
result = null;
break;
default :
System.out.println("其它");
break;
}
}
return result;
}
/**
* 根据iterator,以及模板中的标识,填充模板
*
* @param wb
* @param sheet
* @param cell
* @param iterator
* iterator
* @param index
* 模板行索引
* @param rowNum
* 表格总行数
* @param key
* 表格内容
* @return
*/
private int iteratorFillCellValue(HSSFWorkbook wb, HSSFSheet sheet,
HSSFCell cell, Iterator<?> iterator, int index, int rowNum,
String key) {
int rowCount = 0;
Object obj = null;
int p = 0;
int i = index;
HSSFRow newRow = null;
int tmpCellNum = 0;
int k = 0;
int listIndex = 0;
// 取得模板行
HSSFRow orgRow = sheet.getRow(index);
HSSFCellStyle style= wb.createCellStyle();
try {
while (iterator.hasNext()) {
// 取得iterator的对象
obj = iterator.next();
// 移动当前编辑行以下的所有行
if (p != 0) {
rowNum += 1;
i += 1;
rowCount += 1;// 增加的总行数
// 把当前行以下的所有行往下移动1行
sheet.shiftRows(i, rowNum, 1);
}
p = 1;
// 创建新行
newRow = sheet.createRow(index + k++);
// 把新行的内容换成和模板行一样
copyRow(wb, orgRow, newRow, true,style);
tmpCellNum = newRow.getLastCellNum();
for (int l = 0; l < tmpCellNum; l++) {
cell = newRow.getCell(l);
key = getCellValue(cell);
/**
* 如果单无格内容为#list#,表示该行是模板行 #list#0_0
* 第一个0表示需要在list中取iterator的索引值
* 第二个0表示在iterator中取的第几个对象,如果不为0,则取下一个对象,而不是沿用前面获取的对象
*/
if(key == null || key.equals("")){
obj = iterator.next();
}
if (key.indexOf("#list#") != -1 && key.indexOf("_0") == -1) {
if (iterator.hasNext()) {
obj = iterator.next();
} else {
obj = null;
}
}
if (key.trim().indexOf(" ") != -1) {
key = key.split(" ")[1];
}
getValueAndSetCellValue(cell, key, obj,new String[]{listIndex+""});
}
// list的数量
listIndex ++;
}
} catch (Exception e) {
e.printStackTrace();
}
return rowCount;
}
/**
* 取到相应的值并填入相应的列中
*
* @param cell 列
* @param key 列内容
* @param obj 数据源对象
* @param args 其他参数 数组
* 数组内容:
* 0位:在list中的第几条数据
*/
private void getValueAndSetCellValue(HSSFCell cell, String key, Object obj, String[] args) {
try {
// 保有存单元格的内容
String cellValue = key = key.replace("\\n", "");
String tmpKey;
// 判断单元格内容是否是公式
if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
Pattern p=Pattern.compile("(\\d+)"); //
Matcher m=p.matcher(key);
if(m.find()){
cellValue = key.replace(m.group(1),
Integer.valueOf(m.group(1))+Integer.valueOf(args[0])+"");
cell.setCellFormula(cellValue);
return;
}
}else{//其他格式
// 循环截取两个$中间的内容,反射出值
while (key.indexOf("$") != -1) {
key = key.substring(key.indexOf("$") + 1);
// 取两个$中间的内容
tmpKey = key.substring(0, key.indexOf("$"));
key = key.substring(key.indexOf("$") + 1);
// 如果内容是如下格式Cars.id,则从obj中值得相应的对象的值
if (tmpKey.indexOf(".") != -1) {
String className = tmpKey.substring(0, tmpKey.indexOf("."));
// 取得类的全限定名
String classWholeName = packaegName + className;
String fieldName = tmpKey.substring(tmpKey.indexOf(".") + 1);
// 如果obj是数组,循环判断哪个对象是对应的
if (obj instanceof Object[]) {
Object[] objs = (Object[]) obj;
for (int k = 0; k < objs.length; k++) {
if (objs[k].getClass().getName().equals(classWholeName)) {
cellValue = cellValue.replace("$" + tmpKey
+ "$", getKeyValue(objs[k], fieldName)
+ "");
} else if(objs[k].getClass().getName().equals("java.util.HashMap")){
Map<String,Object> map = (HashMap<String,Object>)objs[k];
cellValue = cellValue.replace("$" + tmpKey + "$",map.get(fieldName)+"");
}
}
} else if (obj.getClass().getName().equals(classWholeName)) {
cellValue = cellValue.replace("$" + tmpKey + "$",getKeyValue(obj, fieldName) + "");
} else if (obj.getClass().getName().equals("java.util.HashMap")){
Map<String,Object> map = (HashMap<String,Object>)obj;
cellValue = cellValue.replace("$" + tmpKey + "$",map.get(fieldName)+"");
}
}
}
}
cell.setCellValue(cellValue);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 给列填充数据
*
* @param cell
* 列
* @param obj
* 数据源对象
* @param fieldName
* 需要取数据的字段
*/
private Object getKeyValue(Object obj, String fieldName) {
Object value = "";
try {
if (obj != null) {
ReportRelatedUtils test = new ReportRelatedUtils();
value = test.getValue(obj, fieldName) == null ? "" : test .getValue(obj, fieldName);
}
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
public static void main(String[] args) {
try {
ReportUtils ee = new ReportUtils();
List<Iterator<?>> list = new ArrayList<Iterator<?>>();
Line line = new Line();
line.setId(1);
line.setName("line1");
List<Object> dataList = new ArrayList<Object>();
ScheduleRealInfo srr = new ScheduleRealInfo();
srr.setId((long) 111);
srr.setXlName("abc11");
ScheduleRealInfo sr = new ScheduleRealInfo();
sr.setZdsj("06:10");
sr.setZdsjActual("06:25");
dataList.add(sr);
sr = new ScheduleRealInfo();
sr.setZdsj("06:20");
sr.setZdsjActual("");
dataList.add(sr);
list.add(dataList.iterator());
ee.excelReplace(list, new Object[] { srr }, "F:/waybill.xls",
"F:/22.xls");
System.out.println("ok");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 行复制功能
*
* @param fromRow
* @param toRow
*/
private void copyRow(HSSFWorkbook wb, HSSFRow fromRow, HSSFRow toRow,
boolean copyValueFlag, HSSFCellStyle style) {
for (Iterator<Cell> cellIt = fromRow.cellIterator(); cellIt.hasNext();) {
HSSFCell tmpCell = (HSSFCell) cellIt.next();
HSSFCell newCell = toRow.createCell(tmpCell.getColumnIndex(), 0);
copyCell(wb, tmpCell, newCell, copyValueFlag, tmpCell.getCellStyle());
}
}
/**
* 复制单元格
*
* @param srcCell
* @param distCell
* @param copyValueFlag
* true则连同cell的内容一起复制
*/
public void copyCell(HSSFWorkbook wb, HSSFCell srcCell, HSSFCell distCell,
boolean copyValueFlag, HSSFCellStyle newstyle) {
// HSSFCellStyle newstyle = wb.createCellStyle();
copyCellStyle(wb, srcCell.getCellStyle(), newstyle);
// 样式
distCell.setCellStyle(newstyle);
// 评论
if (srcCell.getCellComment() != null) {
distCell.setCellComment(srcCell.getCellComment());
}
// 不同数据类型处理
int srcCellType = srcCell.getCellType();
distCell.setCellType(srcCellType);
if (copyValueFlag) {
if (srcCellType == HSSFCell.CELL_TYPE_NUMERIC) {
distCell.setCellValue(srcCell.getDateCellValue());
} else if (srcCellType == HSSFCell.CELL_TYPE_STRING) {
distCell.setCellValue(srcCell.getRichStringCellValue());
} else if (srcCellType == HSSFCell.CELL_TYPE_BLANK) {
} else if (srcCellType == HSSFCell.CELL_TYPE_BOOLEAN) {
distCell.setCellValue(srcCell.getBooleanCellValue());
} else if (srcCellType == HSSFCell.CELL_TYPE_ERROR) {
distCell.setCellErrorValue(srcCell.getErrorCellValue());
} else if (srcCellType == HSSFCell.CELL_TYPE_FORMULA) {
distCell.setCellFormula(srcCell.getCellFormula());
} else {
}
}
}
/**
* 复制一个单元格样式到目的单元格样式
*
* @param fromStyle
* @param toStyle
*/
public void copyCellStyle(HSSFWorkbook wb, HSSFCellStyle fromStyle,
HSSFCellStyle toStyle) {
toStyle.setAlignment(fromStyle.getAlignment());
// 边框和边框颜色
toStyle.setBorderBottom(fromStyle.getBorderBottom());
toStyle.setBorderLeft(fromStyle.getBorderLeft());
toStyle.setBorderRight(fromStyle.getBorderRight());
toStyle.setBorderTop(fromStyle.getBorderTop());
toStyle.setTopBorderColor(fromStyle.getTopBorderColor());
toStyle.setBottomBorderColor(fromStyle.getBottomBorderColor());
toStyle.setRightBorderColor(fromStyle.getRightBorderColor());
toStyle.setLeftBorderColor(fromStyle.getLeftBorderColor());
// 背景和前景
toStyle.setFillBackgroundColor(fromStyle.getFillBackgroundColor());
toStyle.setFillForegroundColor(fromStyle.getFillForegroundColor());
toStyle.setDataFormat(fromStyle.getDataFormat());
toStyle.setFillPattern(fromStyle.getFillPattern());
toStyle.setHidden(fromStyle.getHidden());
toStyle.setIndention(fromStyle.getIndention());// 首行缩进
toStyle.setLocked(fromStyle.getLocked());
toStyle.setRotation(fromStyle.getRotation());// 旋转
toStyle.setVerticalAlignment(fromStyle.getVerticalAlignment());
toStyle.setWrapText(fromStyle.getWrapText());
// 字体
toStyle.setFont(fromStyle.getFont(wb));
}
/**
* 创建文件夹,并删除原有文件
*
* @param path
*/
private void createFolder(String path) {
File targetFile = null;
targetFile = new File(path);
if (targetFile.exists()) {// 删除原有文件
targetFile.delete();
}
// 创建目标文件夹
targetFile = new File(path.substring(0, path.lastIndexOf("/")));
if (!targetFile.exists()) {
targetFile.mkdirs();
}
}
public void createFlie(List<List<String>> list, String name, String type){
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
// style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
// style.setFillPattern(HSSFCellStyle.BORDER_THIN);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一个字体
HSSFFont font = workbook.createFont();
// font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
HSSFCellStyle cellStyle =workbook.createCellStyle();
cellStyle.setFont(font);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平布局:居中
cellStyle.setWrapText(true);
//设置wordsheet名
HSSFSheet sheetYS = workbook.createSheet();//设置wordsheet名
HSSFRow row = sheetYS.createRow(0);
setCellStyleAndValue(row, style, 0, name);
CellRangeAddress callRangeAddress = new CellRangeAddress(0,0,0,list.get(0).size()-1);
sheetYS.addMergedRegion(callRangeAddress);
// 样式
setMergeCellStyle (callRangeAddress, sheetYS, workbook);
try{
for(int i=0; i<list.size(); i++){
HSSFRow rowYSi = sheetYS.createRow(i+1);
List<String> stringList = list.get(i);
int num = 4;
if("xl".equals(type))
num = 2;
else if("cl".equals(type))
num = 5;
for(int j=0; j<stringList.size(); j++){
String str = stringList.get(j);
if(i == list.size()-1){
if(j==0) {
setCellStyleAndValue(rowYSi, style, j, str);
CellRangeAddress callRangeAddressYSi = new CellRangeAddress(i+1,i+1,0,num);
sheetYS.addMergedRegion(callRangeAddressYSi);
// 样式
setMergeCellStyle (callRangeAddressYSi, sheetYS, workbook);
}else
setCellStyleAndValue(rowYSi,style,j+num,str);
} else {
setCellStyleAndValue(rowYSi,style,j,str);
}
}
}
// 给列设置宽度自适应
setSizeColumn1(sheetYS,1,list.get(0).size());
String path = this.getClass().getResource("/").getPath() + "static/pages/forms/export/";
String targetPath = path+name+".xls";
createFolder(targetPath);
FileOutputStream fout = new FileOutputStream(targetPath);
//5.输出
workbook.write(fout);
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 自适应宽度(中文支持)
* @param sheet
* @param size
*/
private static void setSizeColumn(HSSFSheet sheet, int size) {
for (int columnNum = 0; columnNum < size; columnNum++) {
int columnWidth = sheet.getColumnWidth(columnNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(columnNum) != null) {
HSSFCell currentCell = currentRow.getCell(columnNum);
if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
sheet.setColumnWidth(columnNum, columnWidth * 300);
// sheet.setColumnWidth(columnNum, columnWidth * 256);
}
}
/**
* 自适应宽度(中文支持)
* @param sheet
* @param index 从那一行开始自适应
* @param size
*/
private static void setSizeColumn1(HSSFSheet sheet,int index, int size) {
for (int columnNum = index; columnNum < size; columnNum++) {
int columnWidth = sheet.getColumnWidth(columnNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(columnNum) != null) {
HSSFCell currentCell = currentRow.getCell(columnNum);
if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
sheet.setColumnWidth(columnNum, columnWidth * 300);
// sheet.setColumnWidth(columnNum, columnWidth * 256);
}
}
/**
* 设置单元格值和样式
* @param row
* @param style
* @param index
* @param value
*/
public static void setCellStyleAndValue(HSSFRow row,HSSFCellStyle style,int index,String value){
HSSFCell cell = row.createCell(index);
cell.setCellValue(value);
cell.setCellStyle(style);
}
/**
* 设置合并单元格样式
* @param cra
* @param sheet
* @param workbook
*/
public static void setMergeCellStyle (CellRangeAddress cra, HSSFSheet sheet, Workbook workbook){
// 使用RegionUtil类为合并后的单元格添加边框
RegionUtil.setBorderBottom(1, cra, sheet, workbook); // 下边框
RegionUtil.setBorderLeft(1, cra, sheet, workbook); // 左边框
RegionUtil.setBorderRight(1, cra, sheet, workbook); // 有边框
RegionUtil.setBorderTop(1, cra, sheet, workbook); // 上边框
}
}