Commit 441126ca2d25bf4bcae33c1c551b5a781a798a60

Authored by 娄高锋
1 parent 276a4623

复制到后面一页时,转换为string格式单元格会报错。

src/main/java/com/bsth/util/ReportUtils.java
1 -package com.bsth.util;  
2 -  
3 -import java.io.File;  
4 -import java.io.FileInputStream;  
5 -import java.io.FileOutputStream;  
6 -import java.util.ArrayList;  
7 -import java.util.HashMap;  
8 -import java.util.Iterator;  
9 -import java.util.List;  
10 -import java.util.Map;  
11 -import java.util.TreeMap;  
12 -import java.util.regex.Matcher;  
13 -import java.util.regex.Pattern;  
14 -  
15 -import com.bsth.common.ResponseCode;  
16 -import org.apache.commons.lang3.StringUtils;  
17 -import org.apache.poi.hssf.usermodel.HSSFCell;  
18 -import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
19 -import org.apache.poi.hssf.usermodel.HSSFFont;  
20 -import org.apache.poi.hssf.usermodel.HSSFRow;  
21 -import org.apache.poi.hssf.usermodel.HSSFSheet;  
22 -import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
23 -import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
24 -import org.apache.poi.ss.usermodel.Cell;  
25 -import org.apache.poi.ss.usermodel.Workbook;  
26 -import org.apache.poi.ss.util.CellRangeAddress;  
27 -  
28 -import com.bsth.entity.Line;  
29 -import com.bsth.entity.realcontrol.ScheduleRealInfo;  
30 -import org.apache.poi.ss.util.RegionUtil;  
31 -import org.apache.poi.xssf.usermodel.XSSFCell;  
32 -  
33 -public class ReportUtils {  
34 - // private final String packaegName = "com.bsth.entity.";  
35 - private final String packaegName = "com.bsth.entity.realcontrol.";  
36 -  
37 - private final Pattern pattern = Pattern.compile("^\\d+(\\.\\d*)?$");  
38 -  
39 - /**  
40 - * /**  
41 - *  
42 - * @param list  
43 - * 模板中,需要重复显示的行所需的数据  
44 - * @param map  
45 - * 模板中除以上list外所有的数据  
46 - * @param index  
47 - * 需要重复的行号,该值为行号减1  
48 - * @param sourcePath  
49 - * 模板路径  
50 - * @param targetPath  
51 - * 生成路径  
52 - */  
53 - public void excelReplace(List<Iterator<?>> list, Object[] tArray,  
54 - String sourcePath, String targetPath) {  
55 - try {  
56 - // 把源文件放入流中  
57 - POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(  
58 - sourcePath));  
59 - HSSFWorkbook wb = new HSSFWorkbook(fs);  
60 - if(tArray.length != 0 && tArray[0] instanceof java.util.Map){  
61 - Map<String, Object> m = (Map<String, Object>)tArray[0];  
62 - if(m.containsKey("sheetName") && m.get("sheetName")!=null  
63 - && m.get("sheetName").toString().trim().length()!=0)  
64 - wb.setSheetName(0, m.get("sheetName").toString());  
65 - }  
66 - HSSFSheet sheet = wb.getSheetAt(0);  
67 - HSSFRow row;  
68 - HSSFCell cell = null;  
69 - String key;  
70 - // 取得总行数  
71 - int rowNum = sheet.getLastRowNum();  
72 - // 取得总列数  
73 - int cellNum = sheet.getRow(0).getLastCellNum();  
74 -  
75 - // 遍历行  
76 - for (int i = 0; i < rowNum; i++) {  
77 - row = sheet.getRow(i);  
78 - // 遍历列  
79 - for (int j = 0; j < cellNum; j++) {  
80 - if (row == null) {  
81 - continue;  
82 - }  
83 - cell = row.getCell(j);  
84 - if (cell == null) {  
85 - continue;  
86 - }  
87 - // 取得每列的内容,如果列内容是$key$格式,则替换内容  
88 - key = getCellValue(cell);  
89 - if (key != null && (key.indexOf("$") != -1 || key.indexOf("#list#") != -1)) {  
90 - // * 列中内容有#list#,则表示该行为模板行,需要以该行为模板  
91 - // * 例如:模板行格式 #list#0_0 $Car.id$  
92 - // * 第一个0表示需要在list中取iterator的索引值  
93 - // * 第二个0表示在iterator中取的第几个对象,如果不为0,则取下一个对象,而不是沿用前面获取的对象  
94 - // * $Car.id$表示所取的对象为Car的对象,并且取值为id的值  
95 - if (key.indexOf("#list#") != -1) {  
96 - key = key.replace("#list#", "").trim();  
97 - String[] lists = key.split(" ");  
98 - // 取得list中的索引值  
99 - int listIndex = Integer  
100 - .valueOf(lists[0].split("_")[0]);  
101 - Iterator<?> iterator = list.get(listIndex);  
102 - // 根据模板创建行并填弃数据,返回增加的行数  
103 - int rowCount = iteratorFillCellValue(wb, sheet,  
104 - cell, iterator, i, rowNum, key);  
105 - rowNum += rowCount;  
106 - i += rowCount;  
107 - break;  
108 - } else {  
109 - // 直接填充数据的列,从对象数组中取得值,这里的数组不传值  
110 - getValueAndSetCellValue(cell, key, tArray, new String[]{""});  
111 - }  
112 - }  
113 -  
114 - }  
115 - }  
116 - // 创建目标文件夹  
117 - createFolder(targetPath);  
118 - // 输出文件  
119 - FileOutputStream fileOut = new FileOutputStream(targetPath);  
120 - wb.write(fileOut);  
121 - fileOut.close();  
122 - } catch (Exception e) {  
123 - e.printStackTrace();  
124 - }  
125 - }  
126 -  
127 -  
128 - /**  
129 - *  
130 - * @param sheetList 多sheet模板中,需要重复显示的行所需的数据  
131 - * @param tArray  
132 - * @param sourcePath 模板路径  
133 - * @param targetPath 生成路径  
134 - */  
135 - public void excelMoreSheetReplace(List<List<Iterator<?>>> sheetList, Object[] tArray,  
136 - String sourcePath, String targetPath) {  
137 - try {  
138 - // 把源文件放入流中  
139 - POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(  
140 - sourcePath));  
141 - HSSFWorkbook wb = new HSSFWorkbook(fs);  
142 - for (int s=0; s<sheetList.size(); s++){  
143 - List<Iterator<?>> list = sheetList.get(s);  
144 - if(tArray.length != 0 && tArray[0] instanceof java.util.Map){  
145 - Map<String, Object> m = (Map<String, Object>)tArray[0];  
146 - if(m.containsKey("sheetName"+s+1) && m.get("sheetName"+s+1)!=null  
147 - && m.get("sheetName"+s+1).toString().trim().length()!=0)  
148 - wb.setSheetName(0, m.get("sheetName"+s+1).toString());  
149 - }  
150 - HSSFSheet sheet = wb.getSheetAt(s);  
151 - HSSFRow row;  
152 - HSSFCell cell = null;  
153 - String key;  
154 - // 取得总行数  
155 - int rowNum = sheet.getLastRowNum();  
156 - // 取得总列数  
157 - int cellNum = sheet.getRow(0).getLastCellNum();  
158 -  
159 - // 遍历行  
160 - for (int i = 0; i <= rowNum; i++) {  
161 - row = sheet.getRow(i);  
162 - // 遍历列  
163 - for (int j = 0; j < cellNum; j++) {  
164 - if (row == null) {  
165 - continue;  
166 - }  
167 - cell = row.getCell(j);  
168 - if (cell == null) {  
169 - continue;  
170 - }  
171 - // 取得每列的内容,如果列内容是$key$格式,则替换内容  
172 - key = getCellValue(cell);  
173 - if (key != null && (key.indexOf("$") != -1 || key.indexOf("#list#") != -1)) {  
174 - // * 列中内容有#list#,则表示该行为模板行,需要以该行为模板  
175 - // * 例如:模板行格式 #list#0_0 $Car.id$  
176 - // * 第一个0表示需要在list中取iterator的索引值  
177 - // * 第二个0表示在iterator中取的第几个对象,如果不为0,则取下一个对象,而不是沿用前面获取的对象  
178 - // * $Car.id$表示所取的对象为Car的对象,并且取值为id的值  
179 - if (key.indexOf("#list#") != -1) {  
180 - key = key.replace("#list#", "").trim();  
181 - String[] lists = key.split(" ");  
182 - // 取得list中的索引值  
183 - int listIndex = Integer  
184 - .valueOf(lists[0].split("_")[0]);  
185 - Iterator<?> iterator = list.get(listIndex);  
186 - // 根据模板创建行并填充数据,返回增加的行数  
187 - int rowCount = iteratorFillCellValue(wb, sheet,  
188 - cell, iterator, i, rowNum, key);  
189 - rowNum += rowCount;  
190 - i += rowCount;  
191 - break;  
192 - } else {  
193 - // 直接填充数据的列,从对象数组中取得值,这里的数组不传值  
194 - getValueAndSetCellValue(cell, key, tArray, new String[]{""});  
195 - }  
196 - }  
197 -  
198 - }  
199 - }  
200 - }  
201 -  
202 - // 创建目标文件夹  
203 - createFolder(targetPath);  
204 - // 输出文件  
205 - FileOutputStream fileOut = new FileOutputStream(targetPath);  
206 - wb.write(fileOut);  
207 - fileOut.close();  
208 - } catch (Exception e) {  
209 - e.printStackTrace();  
210 - }  
211 - }  
212 -  
213 - /**  
214 - * 将file1中的一页sheet复制到file2中  
215 - *  
216 - * @param file1  
217 - * 原sheet所在的excel文件  
218 - * @param file2  
219 - * 目标excel文件  
220 - * @param page  
221 - * 原excel中要被复制的sheet的位置(从0开始)  
222 - * @param rate  
223 - * 调整复制后的缩放倍率(列如:145,则为缩放145%)  
224 - */  
225 - public void copySheetByFile(File file1, File file2, int page, int rate) {  
226 - try {  
227 - // 把源文件放入流中  
228 - POIFSFileSystem fs1 = new POIFSFileSystem(new FileInputStream(file1));  
229 - HSSFWorkbook wb1 = new HSSFWorkbook(fs1);  
230 - HSSFSheet sheet = wb1.getSheetAt(page);  
231 - POIFSFileSystem fs2 = new POIFSFileSystem(new FileInputStream(file2));  
232 - HSSFWorkbook wb2 = new HSSFWorkbook(fs2);  
233 - HSSFSheet createSheet = wb2.createSheet(sheet.getSheetName());  
234 - HSSFCellStyle createCellStyle = wb2.createCellStyle();  
235 - HSSFRow row;  
236 -  
237 - createSheet.setZoom(rate, 100);  
238 - for(int i = 0; i < sheet.getRow(0).getPhysicalNumberOfCells(); i++){  
239 - createSheet.setColumnWidth(i, sheet.getColumnWidth(i));  
240 - }  
241 -  
242 - List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();  
243 - for(int l = 0; l < mergedRegions.size(); l++){  
244 - //复制源表中的合并单元格  
245 - createSheet.addMergedRegion(mergedRegions.get(l));  
246 - }  
247 - int firstRow = sheet.getFirstRowNum();  
248 - int lastRow = sheet.getLastRowNum();  
249 - for(int k = firstRow; k <= lastRow; k++){  
250 - // 创建新建excel Sheet的行  
251 - HSSFRow rowCreat = createSheet.createRow(k);  
252 - // 取得源有excel Sheet的行  
253 - row = sheet.getRow(k);  
254 -// rowCreat.setHeight(row.getHeight()); //设置行高  
255 - // 单元格式样  
256 - int firstCell = row.getFirstCellNum();  
257 - int lastCell = row.getLastCellNum();  
258 - for (int j = firstCell; j < lastCell; j++) {  
259 - // 自动适应列宽 貌似不起作用  
260 -// createSheet.autoSizeColumn(j);  
261 -// System.out.println(row.getCell(j));  
262 - rowCreat.createCell(j);  
263 - String strVal = "";  
264 - if (row.getCell(j)==null) {  
265 -  
266 - } else {  
267 - strVal = row.getCell(j).getStringCellValue();  
268 - rowCreat.getCell(j).setCellValue(strVal);  
269 - copyCellStyle(wb1, row.getCell(j).getCellStyle(), createCellStyle);  
270 - createCellStyle.setBorderTop((short)1);  
271 - createCellStyle.setBorderLeft((short)1);  
272 - createCellStyle.setBorderRight((short)1);  
273 - createCellStyle.setBorderBottom((short)1);  
274 - rowCreat.getCell(j).setCellStyle(createCellStyle);  
275 - }  
276 - }  
277 - }  
278 -  
279 -// int firstRowNum = createSheet.getFirstRowNum();  
280 -// int lastRowNum = createSheet.getLastRowNum();  
281 -// int test = 0;  
282 -// for(int k = firstRowNum; k <= lastRowNum; k++){  
283 -// HSSFRow createRow = createSheet.getRow(k);  
284 -// int firstCellNum = createRow.getFirstCellNum();  
285 -// int lastCellNum = createRow.getLastCellNum();  
286 -// for(int i = firstCellNum; i < lastCellNum; i++){  
287 -// HSSFCell cell = createRow.getCell(i);  
288 -// cell.getCellStyle().setBorderTop(HSSFCellStyle.BORDER_THIN);  
289 -// cell.getCellStyle().setBorderLeft(HSSFCellStyle.BORDER_THIN);  
290 -// cell.getCellStyle().setBorderRight(HSSFCellStyle.BORDER_THIN);  
291 -// cell.getCellStyle().setBorderBottom(HSSFCellStyle.BORDER_THIN);  
292 -// test ++;  
293 -// }  
294 -// }  
295 -// System.out.println("test = " + test);  
296 -  
297 - FileOutputStream fileOut = new FileOutputStream(file2);  
298 - wb2.write(fileOut);  
299 - fileOut.close();  
300 - wb2.close();  
301 - wb1.close();  
302 - fs2.close();  
303 - fs1.close();  
304 - file1.delete();  
305 -// // 创建目标文件夹  
306 -// createFolder(targetPath);  
307 - // 输出文件  
308 - } catch (Exception e) {  
309 - e.printStackTrace();  
310 - }  
311 - }  
312 -  
313 - public void test(File file){  
314 - POIFSFileSystem fs;  
315 - try {  
316 - fs = new POIFSFileSystem(new FileInputStream(file));  
317 - HSSFWorkbook wb = new HSSFWorkbook(fs);  
318 - for(int j = 0; j < wb.getNumberOfSheets(); j++){  
319 - HSSFSheet sheet = wb.getSheetAt(j);  
320 - int firstRowNum = sheet.getFirstRowNum();  
321 - int lastRowNum = sheet.getLastRowNum();  
322 - int test = 0;  
323 - for(int k = firstRowNum; k <= lastRowNum; k++){  
324 - HSSFRow createRow = sheet.getRow(k);  
325 - int firstCellNum = createRow.getFirstCellNum();  
326 - int lastCellNum = createRow.getLastCellNum();  
327 - for(int i = firstCellNum; i < lastCellNum; i++){  
328 - HSSFCell cell = createRow.getCell(i);  
329 - HSSFCellStyle cellStyle = wb.createCellStyle();  
330 -  
331 - cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);  
332 - cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
333 - cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);  
334 - cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
335 - cell.setCellStyle(cellStyle);  
336 - test ++;  
337 - }  
338 - }  
339 - System.out.println("test = " + test);  
340 -  
341 - FileOutputStream fileOut = new FileOutputStream(file);  
342 - wb.write(fileOut);  
343 - fileOut.close();  
344 - }  
345 - } catch (Exception e) {  
346 - // TODO Auto-generated catch block  
347 - e.printStackTrace();  
348 - }  
349 -  
350 - }  
351 -  
352 - public String getCellValue(HSSFCell cell) {  
353 - int cellType = 0;  
354 - String result = "";  
355 - double d;  
356 - if(cell != null) {  
357 - // 获取列数据类型  
358 - cellType = cell.getCellType();  
359 - // 不同列数据类型,取值方法不同  
360 - switch(cellType) {  
361 - // String  
362 - case HSSFCell.CELL_TYPE_STRING:  
363 - result = cell.getStringCellValue().toString();  
364 - break;  
365 - // numeric类型,excel中,日期格式会转成数字格式存储  
366 - case HSSFCell.CELL_TYPE_NUMERIC:  
367 - result = cell.getNumericCellValue()+"";  
368 - break;  
369 - // 公式类型  
370 - case HSSFCell.CELL_TYPE_FORMULA:  
371 - result = cell.getCellFormula() + "";  
372 - break;  
373 - // boolean类型  
374 - case HSSFCell.CELL_TYPE_BOOLEAN:  
375 - result = cell.getBooleanCellValue() + "";  
376 - break;  
377 - // 空格  
378 - case HSSFCell.CELL_TYPE_BLANK:  
379 - result = null;  
380 - break;  
381 - // 错误值  
382 - case HSSFCell.CELL_TYPE_ERROR:  
383 - result = null;  
384 - break;  
385 - default :  
386 - System.out.println("其它");  
387 - break;  
388 - }  
389 - }  
390 - return result;  
391 - }  
392 -  
393 - /**  
394 - * 根据iterator,以及模板中的标识,填充模板  
395 - *  
396 - * @param wb  
397 - * @param sheet  
398 - * @param cell  
399 - * @param iterator  
400 - * iterator  
401 - * @param index  
402 - * 模板行索引  
403 - * @param rowNum  
404 - * 表格总行数  
405 - * @param key  
406 - * 表格内容  
407 - * @return  
408 - */  
409 - private int iteratorFillCellValue(HSSFWorkbook wb, HSSFSheet sheet,  
410 - HSSFCell cell, Iterator<?> iterator, int index, int rowNum,  
411 - String key) {  
412 - int rowCount = 0;  
413 - Object obj = null;  
414 - int p = 0;  
415 - int i = index;  
416 - HSSFRow newRow = null;  
417 - int tmpCellNum = 0;  
418 - int k = 0;  
419 - int listIndex = 0;  
420 - // 取得模板行  
421 - HSSFRow orgRow = sheet.getRow(index);  
422 - HSSFCellStyle style= wb.createCellStyle();  
423 - try {  
424 - while (iterator.hasNext()) {  
425 - // 取得iterator的对象  
426 - obj = iterator.next();  
427 - // 移动当前编辑行以下的所有行  
428 - if (p != 0) {  
429 - rowNum += 1;  
430 - i += 1;  
431 - rowCount += 1;// 增加的总行数  
432 - // 把当前行以下的所有行往下移动1行  
433 - sheet.shiftRows(i, rowNum, 1);  
434 - }  
435 - p = 1;  
436 - // 创建新行  
437 - newRow = sheet.createRow(index + k++);  
438 - // 把新行的内容换成和模板行一样  
439 - copyRow(wb, orgRow, newRow, true,style);  
440 - tmpCellNum = newRow.getLastCellNum();  
441 - for (int l = 0; l < tmpCellNum; l++) {  
442 - cell = newRow.getCell(l);  
443 - key = getCellValue(cell);  
444 - /**  
445 - * 如果单无格内容为#list#,表示该行是模板行 #list#0_0  
446 - * 第一个0表示需要在list中取iterator的索引值  
447 - * 第二个0表示在iterator中取的第几个对象,如果不为0,则取下一个对象,而不是沿用前面获取的对象  
448 - */  
449 - if(key == null || key.equals("")){  
450 - obj = iterator.next();  
451 - }  
452 - if (key.indexOf("#list#") != -1 && key.indexOf("_0") == -1) {  
453 - if (iterator.hasNext()) {  
454 - obj = iterator.next();  
455 - } else {  
456 - obj = null;  
457 - }  
458 - }  
459 - if (key.trim().indexOf(" ") != -1) {  
460 - key = key.split(" ")[1];  
461 - }  
462 - getValueAndSetCellValue(cell, key, obj,new String[]{listIndex+""});  
463 - }  
464 - // list的数量  
465 - listIndex ++;  
466 - }  
467 - } catch (Exception e) {  
468 - e.printStackTrace();  
469 - }  
470 - return rowCount;  
471 - }  
472 -  
473 - /**  
474 - * 取到相应的值并填入相应的列中  
475 - *  
476 - * @param cell 列  
477 - * @param key 列内容  
478 - * @param obj 数据源对象  
479 - * @param args 其他参数 数组  
480 - * 数组内容:  
481 - * 0位:在list中的第几条数据  
482 - */  
483 - private void getValueAndSetCellValue(HSSFCell cell, String key, Object obj, String[] args) {  
484 - try {  
485 - // 保有存单元格的内容  
486 - String cellValue = key = key.replace("\\n", "");  
487 - String tmpKey;  
488 - // 判断单元格内容是否是公式  
489 - if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){  
490 - Pattern p=Pattern.compile("(\\d+)"); //  
491 - Matcher m=p.matcher(key);  
492 - if(m.find()){  
493 - cellValue = key.replace(m.group(1),  
494 - Integer.valueOf(m.group(1))+Integer.valueOf(args[0])+"");  
495 - cell.setCellFormula(cellValue);  
496 - return;  
497 - }  
498 - }else{//其他格式  
499 -  
500 - // 循环截取两个$中间的内容,反射出值  
501 - while (key.indexOf("$") != -1) {  
502 - key = key.substring(key.indexOf("$") + 1);  
503 - // 取两个$中间的内容  
504 - tmpKey = key.substring(0, key.indexOf("$"));  
505 - key = key.substring(key.indexOf("$") + 1);  
506 - // 如果内容是如下格式Cars.id,则从obj中值得相应的对象的值  
507 - if (tmpKey.indexOf(".") != -1) {  
508 - String className = tmpKey.substring(0, tmpKey.indexOf("."));  
509 - // 取得类的全限定名  
510 - String classWholeName = packaegName + className;  
511 - String fieldName = tmpKey.substring(tmpKey.indexOf(".") + 1);  
512 - // 如果obj是数组,循环判断哪个对象是对应的  
513 - if (obj instanceof Object[]) {  
514 - Object[] objs = (Object[]) obj;  
515 - for (int k = 0; k < objs.length; k++) {  
516 - if (objs[k].getClass().getName().equals(classWholeName)) {  
517 - cellValue = cellValue.replace("$" + tmpKey  
518 - + "$", getKeyValue(objs[k], fieldName)  
519 - + "");  
520 - } else if(objs[k].getClass().getName().equals("java.util.HashMap")){  
521 - Map<String,Object> map = (HashMap<String,Object>)objs[k];  
522 - cellValue = cellValue.replace("$" + tmpKey + "$",map.get(fieldName)+"");  
523 - }  
524 - }  
525 - } else if (obj.getClass().getName().equals(classWholeName)) {  
526 - cellValue = cellValue.replace("$" + tmpKey + "$",getKeyValue(obj, fieldName) + "");  
527 - } else if (obj.getClass().getName().equals("java.util.HashMap")){  
528 - Map<String,Object> map = (HashMap<String,Object>)obj;  
529 - cellValue = cellValue.replace("$" + tmpKey + "$",map.get(fieldName)+"");  
530 - }  
531 - }  
532 - }  
533 - }  
534 - cell.setCellValue(cellValue);  
535 - Matcher matcher = pattern.matcher(cellValue);  
536 - if (matcher.matches()) {  
537 - if (cellValue.indexOf(".") > -1) {  
538 - cell.setCellValue(Double.parseDouble(cellValue));  
539 - } else {  
540 - cell.setCellValue(Integer.parseInt(cellValue));  
541 - }  
542 - }  
543 - } catch (Exception e) {  
544 - e.printStackTrace();  
545 - }  
546 -  
547 - }  
548 -  
549 - /**  
550 - * 给列填充数据  
551 - *  
552 - * @param cell  
553 - * 列  
554 - * @param obj  
555 - * 数据源对象  
556 - * @param fieldName  
557 - * 需要取数据的字段  
558 - */  
559 - private Object getKeyValue(Object obj, String fieldName) {  
560 - Object value = "";  
561 - try {  
562 - if (obj != null) {  
563 - ReportRelatedUtils test = new ReportRelatedUtils();  
564 - value = test.getValue(obj, fieldName) == null ? "" : test .getValue(obj, fieldName);  
565 - }  
566 - } catch (Exception e) {  
567 - e.printStackTrace();  
568 - }  
569 - return value;  
570 - }  
571 -  
572 - public static void main(String[] args) {  
573 -  
574 - try {  
575 - ReportUtils ee = new ReportUtils();  
576 - List<Iterator<?>> list = new ArrayList<Iterator<?>>();  
577 - Line line = new Line();  
578 - line.setId(1);  
579 - line.setName("line1");  
580 -  
581 - List<Object> dataList = new ArrayList<Object>();  
582 -  
583 -  
584 - ScheduleRealInfo srr = new ScheduleRealInfo();  
585 - srr.setId((long) 111);  
586 - srr.setXlName("abc11");  
587 -  
588 - ScheduleRealInfo sr = new ScheduleRealInfo();  
589 - sr.setZdsj("06:10");  
590 - sr.setZdsjActual("06:25");  
591 - dataList.add(sr);  
592 - sr = new ScheduleRealInfo();  
593 - sr.setZdsj("06:20");  
594 - sr.setZdsjActual("");  
595 - dataList.add(sr);  
596 - list.add(dataList.iterator());  
597 -  
598 - ee.excelReplace(list, new Object[] { srr }, "D:/waybill.xls",  
599 - "D:/22.xls");  
600 - System.out.println("ok");  
601 - } catch (Exception e) {  
602 - e.printStackTrace();  
603 - }  
604 - }  
605 -  
606 - /**  
607 - * 行复制功能  
608 - *  
609 - * @param fromRow  
610 - * @param toRow  
611 - */  
612 - private void copyRow(HSSFWorkbook wb, HSSFRow fromRow, HSSFRow toRow,  
613 - boolean copyValueFlag, HSSFCellStyle style) {  
614 - for (Iterator<Cell> cellIt = fromRow.cellIterator(); cellIt.hasNext();) {  
615 - HSSFCell tmpCell = (HSSFCell) cellIt.next();  
616 - HSSFCell newCell = toRow.createCell(tmpCell.getColumnIndex(), 0);  
617 - copyCell(wb, tmpCell, newCell, copyValueFlag, tmpCell.getCellStyle());  
618 - }  
619 - }  
620 -  
621 - /**  
622 - * 复制单元格  
623 - *  
624 - * @param srcCell  
625 - * @param distCell  
626 - * @param copyValueFlag  
627 - * true则连同cell的内容一起复制  
628 - */  
629 - public void copyCell(HSSFWorkbook wb, HSSFCell srcCell, HSSFCell distCell,  
630 - boolean copyValueFlag, HSSFCellStyle newstyle) {  
631 -// HSSFCellStyle newstyle = wb.createCellStyle();  
632 - copyCellStyle(wb, srcCell.getCellStyle(), newstyle);  
633 - // 样式  
634 - distCell.setCellStyle(newstyle);  
635 - // 评论  
636 - if (srcCell.getCellComment() != null) {  
637 - distCell.setCellComment(srcCell.getCellComment());  
638 - }  
639 - // 不同数据类型处理  
640 - int srcCellType = srcCell.getCellType();  
641 - distCell.setCellType(srcCellType);  
642 - if (copyValueFlag) {  
643 - if (srcCellType == HSSFCell.CELL_TYPE_NUMERIC) {  
644 - distCell.setCellValue(srcCell.getDateCellValue());  
645 - } else if (srcCellType == HSSFCell.CELL_TYPE_STRING) {  
646 - distCell.setCellValue(srcCell.getRichStringCellValue());  
647 - } else if (srcCellType == HSSFCell.CELL_TYPE_BLANK) {  
648 -  
649 - } else if (srcCellType == HSSFCell.CELL_TYPE_BOOLEAN) {  
650 - distCell.setCellValue(srcCell.getBooleanCellValue());  
651 - } else if (srcCellType == HSSFCell.CELL_TYPE_ERROR) {  
652 - distCell.setCellErrorValue(srcCell.getErrorCellValue());  
653 - } else if (srcCellType == HSSFCell.CELL_TYPE_FORMULA) {  
654 - distCell.setCellFormula(srcCell.getCellFormula());  
655 - } else {  
656 - }  
657 - }  
658 - }  
659 -  
660 - /**  
661 - * 复制一个单元格样式到目的单元格样式  
662 - *  
663 - * @param fromStyle  
664 - * @param toStyle  
665 - */  
666 - public void copyCellStyle(HSSFWorkbook wb, HSSFCellStyle fromStyle,  
667 - HSSFCellStyle toStyle) {  
668 - toStyle.setAlignment(fromStyle.getAlignment());  
669 - // 边框和边框颜色  
670 - toStyle.setBorderBottom(fromStyle.getBorderBottom());  
671 - toStyle.setBorderLeft(fromStyle.getBorderLeft());  
672 - toStyle.setBorderRight(fromStyle.getBorderRight());  
673 - toStyle.setBorderTop(fromStyle.getBorderTop());  
674 - toStyle.setTopBorderColor(fromStyle.getTopBorderColor());  
675 - toStyle.setBottomBorderColor(fromStyle.getBottomBorderColor());  
676 - toStyle.setRightBorderColor(fromStyle.getRightBorderColor());  
677 - toStyle.setLeftBorderColor(fromStyle.getLeftBorderColor());  
678 -  
679 - // 背景和前景  
680 - toStyle.setFillBackgroundColor(fromStyle.getFillBackgroundColor());  
681 - toStyle.setFillForegroundColor(fromStyle.getFillForegroundColor());  
682 -  
683 - toStyle.setDataFormat(fromStyle.getDataFormat());  
684 - toStyle.setFillPattern(fromStyle.getFillPattern());  
685 - toStyle.setHidden(fromStyle.getHidden());  
686 - toStyle.setIndention(fromStyle.getIndention());// 首行缩进  
687 - toStyle.setLocked(fromStyle.getLocked());  
688 - toStyle.setRotation(fromStyle.getRotation());// 旋转  
689 - toStyle.setVerticalAlignment(fromStyle.getVerticalAlignment());  
690 - toStyle.setWrapText(fromStyle.getWrapText());  
691 - // 字体  
692 - toStyle.setFont(fromStyle.getFont(wb));  
693 -  
694 - }  
695 -  
696 - /**  
697 - * 创建文件夹,并删除原有文件  
698 - *  
699 - * @param path  
700 - */  
701 - private void createFolder(String path) {  
702 - File targetFile = null;  
703 - targetFile = new File(path);  
704 - if (targetFile.exists()) {// 删除原有文件  
705 - targetFile.delete();  
706 - }  
707 - // 创建目标文件夹  
708 - targetFile = new File(path.substring(0, path.lastIndexOf("/")));  
709 - if (!targetFile.exists()) {  
710 - targetFile.mkdirs();  
711 - }  
712 - }  
713 -  
714 - public void createFlie(List<List<String>> list, String name, String type){  
715 - HSSFWorkbook workbook = new HSSFWorkbook();  
716 - // 生成一个样式  
717 - HSSFCellStyle style = workbook.createCellStyle();  
718 - // 设置这些样式  
719 -// style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);  
720 -// style.setFillPattern(HSSFCellStyle.BORDER_THIN);  
721 - style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
722 - style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
723 - style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
724 - style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
725 - style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
726 - // 生成一个字体  
727 - HSSFFont font = workbook.createFont();  
728 -// font.setColor(HSSFColor.VIOLET.index);  
729 - font.setFontHeightInPoints((short) 12);  
730 - font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
731 - // 把字体应用到当前的样式  
732 - style.setFont(font);  
733 - HSSFCellStyle cellStyle =workbook.createCellStyle();  
734 - cellStyle.setFont(font);  
735 - cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平布局:居中  
736 - cellStyle.setWrapText(true);  
737 -  
738 - //设置wordsheet名  
739 - HSSFSheet sheetYS = workbook.createSheet();//设置wordsheet名  
740 - HSSFRow row = sheetYS.createRow(0);  
741 - setCellStyleAndValue(row, style, 0, name);  
742 - CellRangeAddress callRangeAddress = new CellRangeAddress(0,0,0,list.get(0).size()-1);  
743 - sheetYS.addMergedRegion(callRangeAddress);  
744 - // 样式  
745 - setMergeCellStyle (callRangeAddress, sheetYS, workbook);  
746 -  
747 - try{  
748 - for(int i=0; i<list.size(); i++){  
749 - HSSFRow rowYSi = sheetYS.createRow(i+1);  
750 - List<String> stringList = list.get(i);  
751 - int num = 4;  
752 - if("xl".equals(type))  
753 - num = 2;  
754 - else if("cl".equals(type))  
755 - num = 5;  
756 - for(int j=0; j<stringList.size(); j++){  
757 - String str = stringList.get(j);  
758 - if(i == list.size()-1){  
759 - if(j==0) {  
760 - setCellStyleAndValue(rowYSi, style, j, str);  
761 - CellRangeAddress callRangeAddressYSi = new CellRangeAddress(i+1,i+1,0,num);  
762 - sheetYS.addMergedRegion(callRangeAddressYSi);  
763 - // 样式  
764 - setMergeCellStyle (callRangeAddressYSi, sheetYS, workbook);  
765 - }else  
766 - setCellStyleAndValue(rowYSi,style,j+num,str);  
767 - } else {  
768 - setCellStyleAndValue(rowYSi,style,j,str);  
769 - }  
770 - }  
771 - }  
772 -  
773 - // 给列设置宽度自适应  
774 - setSizeColumn1(sheetYS,1,list.get(0).size());  
775 - String path = this.getClass().getResource("/").getPath() + "static/pages/forms/export/";  
776 - String targetPath = path+name+".xls";  
777 - createFolder(targetPath);  
778 - FileOutputStream fout = new FileOutputStream(targetPath);  
779 - //5.输出  
780 - workbook.write(fout);  
781 - fout.close();  
782 - } catch (Exception e) {  
783 - e.printStackTrace();  
784 - }  
785 - }  
786 -  
787 - /**  
788 - * 自适应宽度(中文支持)  
789 - * @param sheet  
790 - * @param size  
791 - */  
792 - private static void setSizeColumn(HSSFSheet sheet, int size) {  
793 - for (int columnNum = 0; columnNum < size; columnNum++) {  
794 - int columnWidth = sheet.getColumnWidth(columnNum) / 256;  
795 - for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {  
796 - HSSFRow currentRow;  
797 - //当前行未被使用过  
798 - if (sheet.getRow(rowNum) == null) {  
799 - currentRow = sheet.createRow(rowNum);  
800 - } else {  
801 - currentRow = sheet.getRow(rowNum);  
802 - }  
803 - if (currentRow.getCell(columnNum) != null) {  
804 - HSSFCell currentCell = currentRow.getCell(columnNum);  
805 - if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {  
806 - int length = currentCell.getStringCellValue().getBytes().length;  
807 - if (columnWidth < length) {  
808 - columnWidth = length;  
809 - }  
810 - }  
811 - }  
812 - }  
813 - sheet.setColumnWidth(columnNum, columnWidth * 300);  
814 -// sheet.setColumnWidth(columnNum, columnWidth * 256);  
815 - }  
816 - }  
817 -  
818 - /**  
819 - * 自适应宽度(中文支持)  
820 - * @param sheet  
821 - * @param index 从那一行开始自适应  
822 - * @param size  
823 - */  
824 - private static void setSizeColumn1(HSSFSheet sheet,int index, int size) {  
825 - for (int columnNum = index; columnNum < size; columnNum++) {  
826 - int columnWidth = sheet.getColumnWidth(columnNum) / 256;  
827 - for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {  
828 - HSSFRow currentRow;  
829 - //当前行未被使用过  
830 - if (sheet.getRow(rowNum) == null) {  
831 - currentRow = sheet.createRow(rowNum);  
832 - } else {  
833 - currentRow = sheet.getRow(rowNum);  
834 - }  
835 - if (currentRow.getCell(columnNum) != null) {  
836 - HSSFCell currentCell = currentRow.getCell(columnNum);  
837 - if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {  
838 - int length = currentCell.getStringCellValue().getBytes().length;  
839 - if (columnWidth < length) {  
840 - columnWidth = length;  
841 - }  
842 - }  
843 - }  
844 - }  
845 - sheet.setColumnWidth(columnNum, columnWidth * 300);  
846 -// sheet.setColumnWidth(columnNum, columnWidth * 256);  
847 - }  
848 - }  
849 -  
850 - /**  
851 - * 设置单元格值和样式  
852 - * @param row  
853 - * @param style  
854 - * @param index  
855 - * @param value  
856 - */  
857 - public static void setCellStyleAndValue(HSSFRow row,HSSFCellStyle style,int index,String value){  
858 - HSSFCell cell = row.createCell(index);  
859 - cell.setCellValue(value);  
860 - cell.setCellStyle(style);  
861 - }  
862 - /**  
863 - * 设置合并单元格样式  
864 - * @param cra  
865 - * @param sheet  
866 - * @param workbook  
867 - */  
868 - public static void setMergeCellStyle (CellRangeAddress cra, HSSFSheet sheet, Workbook workbook){  
869 - // 使用RegionUtil类为合并后的单元格添加边框  
870 - RegionUtil.setBorderBottom(1, cra, sheet, workbook); // 下边框  
871 - RegionUtil.setBorderLeft(1, cra, sheet, workbook); // 左边框  
872 - RegionUtil.setBorderRight(1, cra, sheet, workbook); // 有边框  
873 - RegionUtil.setBorderTop(1, cra, sheet, workbook); // 上边框  
874 - }  
875 -} 1 +package com.bsth.util;
  2 +
  3 +import java.io.File;
  4 +import java.io.FileInputStream;
  5 +import java.io.FileOutputStream;
  6 +import java.util.ArrayList;
  7 +import java.util.HashMap;
  8 +import java.util.Iterator;
  9 +import java.util.List;
  10 +import java.util.Map;
  11 +import java.util.TreeMap;
  12 +import java.util.regex.Matcher;
  13 +import java.util.regex.Pattern;
  14 +
  15 +import com.bsth.common.ResponseCode;
  16 +import org.apache.commons.lang3.StringUtils;
  17 +import org.apache.poi.hssf.usermodel.HSSFCell;
  18 +import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  19 +import org.apache.poi.hssf.usermodel.HSSFFont;
  20 +import org.apache.poi.hssf.usermodel.HSSFRow;
  21 +import org.apache.poi.hssf.usermodel.HSSFSheet;
  22 +import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  23 +import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  24 +import org.apache.poi.ss.usermodel.Cell;
  25 +import org.apache.poi.ss.usermodel.Workbook;
  26 +import org.apache.poi.ss.util.CellRangeAddress;
  27 +
  28 +import com.bsth.entity.Line;
  29 +import com.bsth.entity.realcontrol.ScheduleRealInfo;
  30 +import org.apache.poi.ss.util.RegionUtil;
  31 +import org.apache.poi.xssf.usermodel.XSSFCell;
  32 +
  33 +public class ReportUtils {
  34 + // private final String packaegName = "com.bsth.entity.";
  35 + private final String packaegName = "com.bsth.entity.realcontrol.";
  36 +
  37 + private final Pattern pattern = Pattern.compile("^\\d+(\\.\\d*)?$");
  38 +
  39 + /**
  40 + * /**
  41 + *
  42 + * @param list
  43 + * 模板中,需要重复显示的行所需的数据
  44 + * @param map
  45 + * 模板中除以上list外所有的数据
  46 + * @param index
  47 + * 需要重复的行号,该值为行号减1
  48 + * @param sourcePath
  49 + * 模板路径
  50 + * @param targetPath
  51 + * 生成路径
  52 + */
  53 + public void excelReplace(List<Iterator<?>> list, Object[] tArray,
  54 + String sourcePath, String targetPath) {
  55 + try {
  56 + // 把源文件放入流中
  57 + POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(
  58 + sourcePath));
  59 + HSSFWorkbook wb = new HSSFWorkbook(fs);
  60 + if(tArray.length != 0 && tArray[0] instanceof java.util.Map){
  61 + Map<String, Object> m = (Map<String, Object>)tArray[0];
  62 + if(m.containsKey("sheetName") && m.get("sheetName")!=null
  63 + && m.get("sheetName").toString().trim().length()!=0)
  64 + wb.setSheetName(0, m.get("sheetName").toString());
  65 + }
  66 + HSSFSheet sheet = wb.getSheetAt(0);
  67 + HSSFRow row;
  68 + HSSFCell cell = null;
  69 + String key;
  70 + // 取得总行数
  71 + int rowNum = sheet.getLastRowNum();
  72 + // 取得总列数
  73 + int cellNum = sheet.getRow(0).getLastCellNum();
  74 +
  75 + // 遍历行
  76 + for (int i = 0; i < rowNum; i++) {
  77 + row = sheet.getRow(i);
  78 + // 遍历列
  79 + for (int j = 0; j < cellNum; j++) {
  80 + if (row == null) {
  81 + continue;
  82 + }
  83 + cell = row.getCell(j);
  84 + if (cell == null) {
  85 + continue;
  86 + }
  87 + // 取得每列的内容,如果列内容是$key$格式,则替换内容
  88 + key = getCellValue(cell);
  89 + if (key != null && (key.indexOf("$") != -1 || key.indexOf("#list#") != -1)) {
  90 + // * 列中内容有#list#,则表示该行为模板行,需要以该行为模板
  91 + // * 例如:模板行格式 #list#0_0 $Car.id$
  92 + // * 第一个0表示需要在list中取iterator的索引值
  93 + // * 第二个0表示在iterator中取的第几个对象,如果不为0,则取下一个对象,而不是沿用前面获取的对象
  94 + // * $Car.id$表示所取的对象为Car的对象,并且取值为id的值
  95 + if (key.indexOf("#list#") != -1) {
  96 + key = key.replace("#list#", "").trim();
  97 + String[] lists = key.split(" ");
  98 + // 取得list中的索引值
  99 + int listIndex = Integer
  100 + .valueOf(lists[0].split("_")[0]);
  101 + Iterator<?> iterator = list.get(listIndex);
  102 + // 根据模板创建行并填弃数据,返回增加的行数
  103 + int rowCount = iteratorFillCellValue(wb, sheet,
  104 + cell, iterator, i, rowNum, key);
  105 + rowNum += rowCount;
  106 + i += rowCount;
  107 + break;
  108 + } else {
  109 + // 直接填充数据的列,从对象数组中取得值,这里的数组不传值
  110 + getValueAndSetCellValue(cell, key, tArray, new String[]{""});
  111 + }
  112 + }
  113 +
  114 + }
  115 + }
  116 + // 创建目标文件夹
  117 + createFolder(targetPath);
  118 + // 输出文件
  119 + FileOutputStream fileOut = new FileOutputStream(targetPath);
  120 + wb.write(fileOut);
  121 + fileOut.close();
  122 + } catch (Exception e) {
  123 + e.printStackTrace();
  124 + }
  125 + }
  126 +
  127 +
  128 + /**
  129 + *
  130 + * @param sheetList 多sheet模板中,需要重复显示的行所需的数据
  131 + * @param tArray
  132 + * @param sourcePath 模板路径
  133 + * @param targetPath 生成路径
  134 + */
  135 + public void excelMoreSheetReplace(List<List<Iterator<?>>> sheetList, Object[] tArray,
  136 + String sourcePath, String targetPath) {
  137 + try {
  138 + // 把源文件放入流中
  139 + POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(
  140 + sourcePath));
  141 + HSSFWorkbook wb = new HSSFWorkbook(fs);
  142 + for (int s=0; s<sheetList.size(); s++){
  143 + List<Iterator<?>> list = sheetList.get(s);
  144 + if(tArray.length != 0 && tArray[0] instanceof java.util.Map){
  145 + Map<String, Object> m = (Map<String, Object>)tArray[0];
  146 + if(m.containsKey("sheetName"+s+1) && m.get("sheetName"+s+1)!=null
  147 + && m.get("sheetName"+s+1).toString().trim().length()!=0)
  148 + wb.setSheetName(0, m.get("sheetName"+s+1).toString());
  149 + }
  150 + HSSFSheet sheet = wb.getSheetAt(s);
  151 + HSSFRow row;
  152 + HSSFCell cell = null;
  153 + String key;
  154 + // 取得总行数
  155 + int rowNum = sheet.getLastRowNum();
  156 + // 取得总列数
  157 + int cellNum = sheet.getRow(0).getLastCellNum();
  158 +
  159 + // 遍历行
  160 + for (int i = 0; i <= rowNum; i++) {
  161 + row = sheet.getRow(i);
  162 + // 遍历列
  163 + for (int j = 0; j < cellNum; j++) {
  164 + if (row == null) {
  165 + continue;
  166 + }
  167 + cell = row.getCell(j);
  168 + if (cell == null) {
  169 + continue;
  170 + }
  171 + // 取得每列的内容,如果列内容是$key$格式,则替换内容
  172 + key = getCellValue(cell);
  173 + if (key != null && (key.indexOf("$") != -1 || key.indexOf("#list#") != -1)) {
  174 + // * 列中内容有#list#,则表示该行为模板行,需要以该行为模板
  175 + // * 例如:模板行格式 #list#0_0 $Car.id$
  176 + // * 第一个0表示需要在list中取iterator的索引值
  177 + // * 第二个0表示在iterator中取的第几个对象,如果不为0,则取下一个对象,而不是沿用前面获取的对象
  178 + // * $Car.id$表示所取的对象为Car的对象,并且取值为id的值
  179 + if (key.indexOf("#list#") != -1) {
  180 + key = key.replace("#list#", "").trim();
  181 + String[] lists = key.split(" ");
  182 + // 取得list中的索引值
  183 + int listIndex = Integer
  184 + .valueOf(lists[0].split("_")[0]);
  185 + Iterator<?> iterator = list.get(listIndex);
  186 + // 根据模板创建行并填充数据,返回增加的行数
  187 + int rowCount = iteratorFillCellValue(wb, sheet,
  188 + cell, iterator, i, rowNum, key);
  189 + rowNum += rowCount;
  190 + i += rowCount;
  191 + break;
  192 + } else {
  193 + // 直接填充数据的列,从对象数组中取得值,这里的数组不传值
  194 + getValueAndSetCellValue(cell, key, tArray, new String[]{""});
  195 + }
  196 + }
  197 +
  198 + }
  199 + }
  200 + }
  201 +
  202 + // 创建目标文件夹
  203 + createFolder(targetPath);
  204 + // 输出文件
  205 + FileOutputStream fileOut = new FileOutputStream(targetPath);
  206 + wb.write(fileOut);
  207 + fileOut.close();
  208 + } catch (Exception e) {
  209 + e.printStackTrace();
  210 + }
  211 + }
  212 +
  213 + /**
  214 + * 将file1中的一页sheet复制到file2中
  215 + *
  216 + * @param file1
  217 + * 原sheet所在的excel文件
  218 + * @param file2
  219 + * 目标excel文件
  220 + * @param page
  221 + * 原excel中要被复制的sheet的位置(从0开始)
  222 + * @param rate
  223 + * 调整复制后的缩放倍率(列如:145,则为缩放145%)
  224 + */
  225 + public void copySheetByFile(File file1, File file2, int page, int rate) {
  226 + try {
  227 + // 把源文件放入流中
  228 + POIFSFileSystem fs1 = new POIFSFileSystem(new FileInputStream(file1));
  229 + HSSFWorkbook wb1 = new HSSFWorkbook(fs1);
  230 + HSSFSheet sheet = wb1.getSheetAt(page);
  231 + POIFSFileSystem fs2 = new POIFSFileSystem(new FileInputStream(file2));
  232 + HSSFWorkbook wb2 = new HSSFWorkbook(fs2);
  233 + HSSFSheet createSheet = wb2.createSheet(sheet.getSheetName());
  234 + HSSFCellStyle createCellStyle = wb2.createCellStyle();
  235 + HSSFRow row;
  236 +
  237 + createSheet.setZoom(rate, 100);
  238 + for(int i = 0; i < sheet.getRow(0).getPhysicalNumberOfCells(); i++){
  239 + createSheet.setColumnWidth(i, sheet.getColumnWidth(i));
  240 + }
  241 +
  242 + List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
  243 + for(int l = 0; l < mergedRegions.size(); l++){
  244 + //复制源表中的合并单元格
  245 + createSheet.addMergedRegion(mergedRegions.get(l));
  246 + }
  247 + int firstRow = sheet.getFirstRowNum();
  248 + int lastRow = sheet.getLastRowNum();
  249 + for(int k = firstRow; k <= lastRow; k++){
  250 + // 创建新建excel Sheet的行
  251 + HSSFRow rowCreat = createSheet.createRow(k);
  252 + // 取得源有excel Sheet的行
  253 + row = sheet.getRow(k);
  254 +// rowCreat.setHeight(row.getHeight()); //设置行高
  255 + // 单元格式样
  256 + int firstCell = row.getFirstCellNum();
  257 + int lastCell = row.getLastCellNum();
  258 + for (int j = firstCell; j < lastCell; j++) {
  259 + // 自动适应列宽 貌似不起作用
  260 +// createSheet.autoSizeColumn(j);
  261 +// System.out.println(row.getCell(j));
  262 + rowCreat.createCell(j);
  263 + String strVal = "";
  264 + if (row.getCell(j)==null) {
  265 +
  266 + } else {
  267 +// strVal = getCellValue(row.getCell(j));
  268 + switch(row.getCell(j).getCellType()) {
  269 + // String
  270 + case HSSFCell.CELL_TYPE_STRING:
  271 + rowCreat.getCell(j).setCellValue(row.getCell(j).getStringCellValue().toString());
  272 + break;
  273 + // numeric类型,excel中,日期格式会转成数字格式存储
  274 + case HSSFCell.CELL_TYPE_NUMERIC:
  275 + rowCreat.getCell(j).setCellValue(row.getCell(j).getNumericCellValue());
  276 + break;
  277 + // 公式类型
  278 + case HSSFCell.CELL_TYPE_FORMULA:
  279 + rowCreat.getCell(j).setCellValue(row.getCell(j).getCellFormula());
  280 + break;
  281 + // boolean类型
  282 + case HSSFCell.CELL_TYPE_BOOLEAN:
  283 + rowCreat.getCell(j).setCellValue(row.getCell(j).getBooleanCellValue());
  284 + break;
  285 + // 空格
  286 + case HSSFCell.CELL_TYPE_BLANK:
  287 + rowCreat.getCell(j).setCellValue("");
  288 + break;
  289 + // 错误值
  290 + case HSSFCell.CELL_TYPE_ERROR:
  291 + rowCreat.getCell(j).setCellValue("");
  292 + break;
  293 + default :
  294 + rowCreat.getCell(j).setCellValue("");
  295 + break;
  296 + }
  297 +// strVal = row.getCell(j).getStringCellValue();
  298 +// rowCreat.getCell(j).setCellValue(strVal);
  299 + copyCellStyle(wb1, row.getCell(j).getCellStyle(), createCellStyle);
  300 + createCellStyle.setBorderTop((short)1);
  301 + createCellStyle.setBorderLeft((short)1);
  302 + createCellStyle.setBorderRight((short)1);
  303 + createCellStyle.setBorderBottom((short)1);
  304 + rowCreat.getCell(j).setCellStyle(createCellStyle);
  305 + }
  306 + }
  307 + }
  308 +
  309 +// int firstRowNum = createSheet.getFirstRowNum();
  310 +// int lastRowNum = createSheet.getLastRowNum();
  311 +// int test = 0;
  312 +// for(int k = firstRowNum; k <= lastRowNum; k++){
  313 +// HSSFRow createRow = createSheet.getRow(k);
  314 +// int firstCellNum = createRow.getFirstCellNum();
  315 +// int lastCellNum = createRow.getLastCellNum();
  316 +// for(int i = firstCellNum; i < lastCellNum; i++){
  317 +// HSSFCell cell = createRow.getCell(i);
  318 +// cell.getCellStyle().setBorderTop(HSSFCellStyle.BORDER_THIN);
  319 +// cell.getCellStyle().setBorderLeft(HSSFCellStyle.BORDER_THIN);
  320 +// cell.getCellStyle().setBorderRight(HSSFCellStyle.BORDER_THIN);
  321 +// cell.getCellStyle().setBorderBottom(HSSFCellStyle.BORDER_THIN);
  322 +// test ++;
  323 +// }
  324 +// }
  325 +// System.out.println("test = " + test);
  326 +
  327 + FileOutputStream fileOut = new FileOutputStream(file2);
  328 + wb2.write(fileOut);
  329 + fileOut.close();
  330 + wb2.close();
  331 + wb1.close();
  332 + fs2.close();
  333 + fs1.close();
  334 + file1.delete();
  335 +// // 创建目标文件夹
  336 +// createFolder(targetPath);
  337 + // 输出文件
  338 + } catch (Exception e) {
  339 + e.printStackTrace();
  340 + }
  341 + }
  342 +
  343 + public void test(File file){
  344 + POIFSFileSystem fs;
  345 + try {
  346 + fs = new POIFSFileSystem(new FileInputStream(file));
  347 + HSSFWorkbook wb = new HSSFWorkbook(fs);
  348 + for(int j = 0; j < wb.getNumberOfSheets(); j++){
  349 + HSSFSheet sheet = wb.getSheetAt(j);
  350 + int firstRowNum = sheet.getFirstRowNum();
  351 + int lastRowNum = sheet.getLastRowNum();
  352 + int test = 0;
  353 + for(int k = firstRowNum; k <= lastRowNum; k++){
  354 + HSSFRow createRow = sheet.getRow(k);
  355 + int firstCellNum = createRow.getFirstCellNum();
  356 + int lastCellNum = createRow.getLastCellNum();
  357 + for(int i = firstCellNum; i < lastCellNum; i++){
  358 + HSSFCell cell = createRow.getCell(i);
  359 + HSSFCellStyle cellStyle = wb.createCellStyle();
  360 +
  361 + cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
  362 + cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  363 + cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
  364 + cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  365 + cell.setCellStyle(cellStyle);
  366 + test ++;
  367 + }
  368 + }
  369 + System.out.println("test = " + test);
  370 +
  371 + FileOutputStream fileOut = new FileOutputStream(file);
  372 + wb.write(fileOut);
  373 + fileOut.close();
  374 + }
  375 + } catch (Exception e) {
  376 + // TODO Auto-generated catch block
  377 + e.printStackTrace();
  378 + }
  379 +
  380 + }
  381 +
  382 + public String getCellValue(HSSFCell cell) {
  383 + int cellType = 0;
  384 + String result = "";
  385 + double d;
  386 + if(cell != null) {
  387 + // 获取列数据类型
  388 + cellType = cell.getCellType();
  389 + // 不同列数据类型,取值方法不同
  390 + switch(cellType) {
  391 + // String
  392 + case HSSFCell.CELL_TYPE_STRING:
  393 + result = cell.getStringCellValue().toString();
  394 + break;
  395 + // numeric类型,excel中,日期格式会转成数字格式存储
  396 + case HSSFCell.CELL_TYPE_NUMERIC:
  397 + result = cell.getNumericCellValue()+"";
  398 + break;
  399 + // 公式类型
  400 + case HSSFCell.CELL_TYPE_FORMULA:
  401 + result = cell.getCellFormula() + "";
  402 + break;
  403 + // boolean类型
  404 + case HSSFCell.CELL_TYPE_BOOLEAN:
  405 + result = cell.getBooleanCellValue() + "";
  406 + break;
  407 + // 空格
  408 + case HSSFCell.CELL_TYPE_BLANK:
  409 + result = null;
  410 + break;
  411 + // 错误值
  412 + case HSSFCell.CELL_TYPE_ERROR:
  413 + result = null;
  414 + break;
  415 + default :
  416 + System.out.println("其它");
  417 + break;
  418 + }
  419 + }
  420 + return result;
  421 + }
  422 +
  423 + /**
  424 + * 根据iterator,以及模板中的标识,填充模板
  425 + *
  426 + * @param wb
  427 + * @param sheet
  428 + * @param cell
  429 + * @param iterator
  430 + * iterator
  431 + * @param index
  432 + * 模板行索引
  433 + * @param rowNum
  434 + * 表格总行数
  435 + * @param key
  436 + * 表格内容
  437 + * @return
  438 + */
  439 + private int iteratorFillCellValue(HSSFWorkbook wb, HSSFSheet sheet,
  440 + HSSFCell cell, Iterator<?> iterator, int index, int rowNum,
  441 + String key) {
  442 + int rowCount = 0;
  443 + Object obj = null;
  444 + int p = 0;
  445 + int i = index;
  446 + HSSFRow newRow = null;
  447 + int tmpCellNum = 0;
  448 + int k = 0;
  449 + int listIndex = 0;
  450 + // 取得模板行
  451 + HSSFRow orgRow = sheet.getRow(index);
  452 + HSSFCellStyle style= wb.createCellStyle();
  453 + try {
  454 + while (iterator.hasNext()) {
  455 + // 取得iterator的对象
  456 + obj = iterator.next();
  457 + // 移动当前编辑行以下的所有行
  458 + if (p != 0) {
  459 + rowNum += 1;
  460 + i += 1;
  461 + rowCount += 1;// 增加的总行数
  462 + // 把当前行以下的所有行往下移动1行
  463 + sheet.shiftRows(i, rowNum, 1);
  464 + }
  465 + p = 1;
  466 + // 创建新行
  467 + newRow = sheet.createRow(index + k++);
  468 + // 把新行的内容换成和模板行一样
  469 + copyRow(wb, orgRow, newRow, true,style);
  470 + tmpCellNum = newRow.getLastCellNum();
  471 + for (int l = 0; l < tmpCellNum; l++) {
  472 + cell = newRow.getCell(l);
  473 + key = getCellValue(cell);
  474 + /**
  475 + * 如果单无格内容为#list#,表示该行是模板行 #list#0_0
  476 + * 第一个0表示需要在list中取iterator的索引值
  477 + * 第二个0表示在iterator中取的第几个对象,如果不为0,则取下一个对象,而不是沿用前面获取的对象
  478 + */
  479 + if(key == null || key.equals("")){
  480 + obj = iterator.next();
  481 + }
  482 + if (key.indexOf("#list#") != -1 && key.indexOf("_0") == -1) {
  483 + if (iterator.hasNext()) {
  484 + obj = iterator.next();
  485 + } else {
  486 + obj = null;
  487 + }
  488 + }
  489 + if (key.trim().indexOf(" ") != -1) {
  490 + key = key.split(" ")[1];
  491 + }
  492 + getValueAndSetCellValue(cell, key, obj,new String[]{listIndex+""});
  493 + }
  494 + // list的数量
  495 + listIndex ++;
  496 + }
  497 + } catch (Exception e) {
  498 + e.printStackTrace();
  499 + }
  500 + return rowCount;
  501 + }
  502 +
  503 + /**
  504 + * 取到相应的值并填入相应的列中
  505 + *
  506 + * @param cell 列
  507 + * @param key 列内容
  508 + * @param obj 数据源对象
  509 + * @param args 其他参数 数组
  510 + * 数组内容:
  511 + * 0位:在list中的第几条数据
  512 + */
  513 + private void getValueAndSetCellValue(HSSFCell cell, String key, Object obj, String[] args) {
  514 + try {
  515 + // 保有存单元格的内容
  516 + String cellValue = key = key.replace("\\n", "");
  517 + String tmpKey;
  518 + // 判断单元格内容是否是公式
  519 + if(cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
  520 + Pattern p=Pattern.compile("(\\d+)"); //
  521 + Matcher m=p.matcher(key);
  522 + if(m.find()){
  523 + cellValue = key.replace(m.group(1),
  524 + Integer.valueOf(m.group(1))+Integer.valueOf(args[0])+"");
  525 + cell.setCellFormula(cellValue);
  526 + return;
  527 + }
  528 + }else{//其他格式
  529 +
  530 + // 循环截取两个$中间的内容,反射出值
  531 + while (key.indexOf("$") != -1) {
  532 + key = key.substring(key.indexOf("$") + 1);
  533 + // 取两个$中间的内容
  534 + tmpKey = key.substring(0, key.indexOf("$"));
  535 + key = key.substring(key.indexOf("$") + 1);
  536 + // 如果内容是如下格式Cars.id,则从obj中值得相应的对象的值
  537 + if (tmpKey.indexOf(".") != -1) {
  538 + String className = tmpKey.substring(0, tmpKey.indexOf("."));
  539 + // 取得类的全限定名
  540 + String classWholeName = packaegName + className;
  541 + String fieldName = tmpKey.substring(tmpKey.indexOf(".") + 1);
  542 + // 如果obj是数组,循环判断哪个对象是对应的
  543 + if (obj instanceof Object[]) {
  544 + Object[] objs = (Object[]) obj;
  545 + for (int k = 0; k < objs.length; k++) {
  546 + if (objs[k].getClass().getName().equals(classWholeName)) {
  547 + cellValue = cellValue.replace("$" + tmpKey
  548 + + "$", getKeyValue(objs[k], fieldName)
  549 + + "");
  550 + } else if(objs[k].getClass().getName().equals("java.util.HashMap")){
  551 + Map<String,Object> map = (HashMap<String,Object>)objs[k];
  552 + cellValue = cellValue.replace("$" + tmpKey + "$",map.get(fieldName)+"");
  553 + }
  554 + }
  555 + } else if (obj.getClass().getName().equals(classWholeName)) {
  556 + cellValue = cellValue.replace("$" + tmpKey + "$",getKeyValue(obj, fieldName) + "");
  557 + } else if (obj.getClass().getName().equals("java.util.HashMap")){
  558 + Map<String,Object> map = (HashMap<String,Object>)obj;
  559 + cellValue = cellValue.replace("$" + tmpKey + "$",map.get(fieldName)+"");
  560 + }
  561 + }
  562 + }
  563 + }
  564 + cell.setCellValue(cellValue);
  565 + Matcher matcher = pattern.matcher(cellValue);
  566 + if (matcher.matches()) {
  567 + if (cellValue.indexOf(".") > -1) {
  568 + cell.setCellValue(Double.parseDouble(cellValue));
  569 + } else {
  570 + cell.setCellValue(Integer.parseInt(cellValue));
  571 + }
  572 + }
  573 + } catch (Exception e) {
  574 + e.printStackTrace();
  575 + }
  576 +
  577 + }
  578 +
  579 + /**
  580 + * 给列填充数据
  581 + *
  582 + * @param cell
  583 + * 列
  584 + * @param obj
  585 + * 数据源对象
  586 + * @param fieldName
  587 + * 需要取数据的字段
  588 + */
  589 + private Object getKeyValue(Object obj, String fieldName) {
  590 + Object value = "";
  591 + try {
  592 + if (obj != null) {
  593 + ReportRelatedUtils test = new ReportRelatedUtils();
  594 + value = test.getValue(obj, fieldName) == null ? "" : test .getValue(obj, fieldName);
  595 + }
  596 + } catch (Exception e) {
  597 + e.printStackTrace();
  598 + }
  599 + return value;
  600 + }
  601 +
  602 + public static void main(String[] args) {
  603 +
  604 + try {
  605 + ReportUtils ee = new ReportUtils();
  606 + List<Iterator<?>> list = new ArrayList<Iterator<?>>();
  607 + Line line = new Line();
  608 + line.setId(1);
  609 + line.setName("line1");
  610 +
  611 + List<Object> dataList = new ArrayList<Object>();
  612 +
  613 +
  614 + ScheduleRealInfo srr = new ScheduleRealInfo();
  615 + srr.setId((long) 111);
  616 + srr.setXlName("abc11");
  617 +
  618 + ScheduleRealInfo sr = new ScheduleRealInfo();
  619 + sr.setZdsj("06:10");
  620 + sr.setZdsjActual("06:25");
  621 + dataList.add(sr);
  622 + sr = new ScheduleRealInfo();
  623 + sr.setZdsj("06:20");
  624 + sr.setZdsjActual("");
  625 + dataList.add(sr);
  626 + list.add(dataList.iterator());
  627 +
  628 + ee.excelReplace(list, new Object[] { srr }, "D:/waybill.xls",
  629 + "D:/22.xls");
  630 + System.out.println("ok");
  631 + } catch (Exception e) {
  632 + e.printStackTrace();
  633 + }
  634 + }
  635 +
  636 + /**
  637 + * 行复制功能
  638 + *
  639 + * @param fromRow
  640 + * @param toRow
  641 + */
  642 + private void copyRow(HSSFWorkbook wb, HSSFRow fromRow, HSSFRow toRow,
  643 + boolean copyValueFlag, HSSFCellStyle style) {
  644 + for (Iterator<Cell> cellIt = fromRow.cellIterator(); cellIt.hasNext();) {
  645 + HSSFCell tmpCell = (HSSFCell) cellIt.next();
  646 + HSSFCell newCell = toRow.createCell(tmpCell.getColumnIndex(), 0);
  647 + copyCell(wb, tmpCell, newCell, copyValueFlag, tmpCell.getCellStyle());
  648 + }
  649 + }
  650 +
  651 + /**
  652 + * 复制单元格
  653 + *
  654 + * @param srcCell
  655 + * @param distCell
  656 + * @param copyValueFlag
  657 + * true则连同cell的内容一起复制
  658 + */
  659 + public void copyCell(HSSFWorkbook wb, HSSFCell srcCell, HSSFCell distCell,
  660 + boolean copyValueFlag, HSSFCellStyle newstyle) {
  661 +// HSSFCellStyle newstyle = wb.createCellStyle();
  662 + copyCellStyle(wb, srcCell.getCellStyle(), newstyle);
  663 + // 样式
  664 + distCell.setCellStyle(newstyle);
  665 + // 评论
  666 + if (srcCell.getCellComment() != null) {
  667 + distCell.setCellComment(srcCell.getCellComment());
  668 + }
  669 + // 不同数据类型处理
  670 + int srcCellType = srcCell.getCellType();
  671 + distCell.setCellType(srcCellType);
  672 + if (copyValueFlag) {
  673 + if (srcCellType == HSSFCell.CELL_TYPE_NUMERIC) {
  674 + distCell.setCellValue(srcCell.getDateCellValue());
  675 + } else if (srcCellType == HSSFCell.CELL_TYPE_STRING) {
  676 + distCell.setCellValue(srcCell.getRichStringCellValue());
  677 + } else if (srcCellType == HSSFCell.CELL_TYPE_BLANK) {
  678 +
  679 + } else if (srcCellType == HSSFCell.CELL_TYPE_BOOLEAN) {
  680 + distCell.setCellValue(srcCell.getBooleanCellValue());
  681 + } else if (srcCellType == HSSFCell.CELL_TYPE_ERROR) {
  682 + distCell.setCellErrorValue(srcCell.getErrorCellValue());
  683 + } else if (srcCellType == HSSFCell.CELL_TYPE_FORMULA) {
  684 + distCell.setCellFormula(srcCell.getCellFormula());
  685 + } else {
  686 + }
  687 + }
  688 + }
  689 +
  690 + /**
  691 + * 复制一个单元格样式到目的单元格样式
  692 + *
  693 + * @param fromStyle
  694 + * @param toStyle
  695 + */
  696 + public void copyCellStyle(HSSFWorkbook wb, HSSFCellStyle fromStyle,
  697 + HSSFCellStyle toStyle) {
  698 + toStyle.setAlignment(fromStyle.getAlignment());
  699 + // 边框和边框颜色
  700 + toStyle.setBorderBottom(fromStyle.getBorderBottom());
  701 + toStyle.setBorderLeft(fromStyle.getBorderLeft());
  702 + toStyle.setBorderRight(fromStyle.getBorderRight());
  703 + toStyle.setBorderTop(fromStyle.getBorderTop());
  704 + toStyle.setTopBorderColor(fromStyle.getTopBorderColor());
  705 + toStyle.setBottomBorderColor(fromStyle.getBottomBorderColor());
  706 + toStyle.setRightBorderColor(fromStyle.getRightBorderColor());
  707 + toStyle.setLeftBorderColor(fromStyle.getLeftBorderColor());
  708 +
  709 + // 背景和前景
  710 + toStyle.setFillBackgroundColor(fromStyle.getFillBackgroundColor());
  711 + toStyle.setFillForegroundColor(fromStyle.getFillForegroundColor());
  712 +
  713 + toStyle.setDataFormat(fromStyle.getDataFormat());
  714 + toStyle.setFillPattern(fromStyle.getFillPattern());
  715 + toStyle.setHidden(fromStyle.getHidden());
  716 + toStyle.setIndention(fromStyle.getIndention());// 首行缩进
  717 + toStyle.setLocked(fromStyle.getLocked());
  718 + toStyle.setRotation(fromStyle.getRotation());// 旋转
  719 + toStyle.setVerticalAlignment(fromStyle.getVerticalAlignment());
  720 + toStyle.setWrapText(fromStyle.getWrapText());
  721 + // 字体
  722 + toStyle.setFont(fromStyle.getFont(wb));
  723 +
  724 + }
  725 +
  726 + /**
  727 + * 创建文件夹,并删除原有文件
  728 + *
  729 + * @param path
  730 + */
  731 + private void createFolder(String path) {
  732 + File targetFile = null;
  733 + targetFile = new File(path);
  734 + if (targetFile.exists()) {// 删除原有文件
  735 + targetFile.delete();
  736 + }
  737 + // 创建目标文件夹
  738 + targetFile = new File(path.substring(0, path.lastIndexOf("/")));
  739 + if (!targetFile.exists()) {
  740 + targetFile.mkdirs();
  741 + }
  742 + }
  743 +
  744 + public void createFlie(List<List<String>> list, String name, String type){
  745 + HSSFWorkbook workbook = new HSSFWorkbook();
  746 + // 生成一个样式
  747 + HSSFCellStyle style = workbook.createCellStyle();
  748 + // 设置这些样式
  749 +// style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
  750 +// style.setFillPattern(HSSFCellStyle.BORDER_THIN);
  751 + style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  752 + style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  753 + style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  754 + style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  755 + style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  756 + // 生成一个字体
  757 + HSSFFont font = workbook.createFont();
  758 +// font.setColor(HSSFColor.VIOLET.index);
  759 + font.setFontHeightInPoints((short) 12);
  760 + font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  761 + // 把字体应用到当前的样式
  762 + style.setFont(font);
  763 + HSSFCellStyle cellStyle =workbook.createCellStyle();
  764 + cellStyle.setFont(font);
  765 + cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平布局:居中
  766 + cellStyle.setWrapText(true);
  767 +
  768 + //设置wordsheet名
  769 + HSSFSheet sheetYS = workbook.createSheet();//设置wordsheet名
  770 + HSSFRow row = sheetYS.createRow(0);
  771 + setCellStyleAndValue(row, style, 0, name);
  772 + CellRangeAddress callRangeAddress = new CellRangeAddress(0,0,0,list.get(0).size()-1);
  773 + sheetYS.addMergedRegion(callRangeAddress);
  774 + // 样式
  775 + setMergeCellStyle (callRangeAddress, sheetYS, workbook);
  776 +
  777 + try{
  778 + for(int i=0; i<list.size(); i++){
  779 + HSSFRow rowYSi = sheetYS.createRow(i+1);
  780 + List<String> stringList = list.get(i);
  781 + int num = 4;
  782 + if("xl".equals(type))
  783 + num = 2;
  784 + else if("cl".equals(type))
  785 + num = 5;
  786 + for(int j=0; j<stringList.size(); j++){
  787 + String str = stringList.get(j);
  788 + if(i == list.size()-1){
  789 + if(j==0) {
  790 + setCellStyleAndValue(rowYSi, style, j, str);
  791 + CellRangeAddress callRangeAddressYSi = new CellRangeAddress(i+1,i+1,0,num);
  792 + sheetYS.addMergedRegion(callRangeAddressYSi);
  793 + // 样式
  794 + setMergeCellStyle (callRangeAddressYSi, sheetYS, workbook);
  795 + }else
  796 + setCellStyleAndValue(rowYSi,style,j+num,str);
  797 + } else {
  798 + setCellStyleAndValue(rowYSi,style,j,str);
  799 + }
  800 + }
  801 + }
  802 +
  803 + // 给列设置宽度自适应
  804 + setSizeColumn1(sheetYS,1,list.get(0).size());
  805 + String path = this.getClass().getResource("/").getPath() + "static/pages/forms/export/";
  806 + String targetPath = path+name+".xls";
  807 + createFolder(targetPath);
  808 + FileOutputStream fout = new FileOutputStream(targetPath);
  809 + //5.输出
  810 + workbook.write(fout);
  811 + fout.close();
  812 + } catch (Exception e) {
  813 + e.printStackTrace();
  814 + }
  815 + }
  816 +
  817 + /**
  818 + * 自适应宽度(中文支持)
  819 + * @param sheet
  820 + * @param size
  821 + */
  822 + private static void setSizeColumn(HSSFSheet sheet, int size) {
  823 + for (int columnNum = 0; columnNum < size; columnNum++) {
  824 + int columnWidth = sheet.getColumnWidth(columnNum) / 256;
  825 + for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
  826 + HSSFRow currentRow;
  827 + //当前行未被使用过
  828 + if (sheet.getRow(rowNum) == null) {
  829 + currentRow = sheet.createRow(rowNum);
  830 + } else {
  831 + currentRow = sheet.getRow(rowNum);
  832 + }
  833 + if (currentRow.getCell(columnNum) != null) {
  834 + HSSFCell currentCell = currentRow.getCell(columnNum);
  835 + if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
  836 + int length = currentCell.getStringCellValue().getBytes().length;
  837 + if (columnWidth < length) {
  838 + columnWidth = length;
  839 + }
  840 + }
  841 + }
  842 + }
  843 + sheet.setColumnWidth(columnNum, columnWidth * 300);
  844 +// sheet.setColumnWidth(columnNum, columnWidth * 256);
  845 + }
  846 + }
  847 +
  848 + /**
  849 + * 自适应宽度(中文支持)
  850 + * @param sheet
  851 + * @param index 从那一行开始自适应
  852 + * @param size
  853 + */
  854 + private static void setSizeColumn1(HSSFSheet sheet,int index, int size) {
  855 + for (int columnNum = index; columnNum < size; columnNum++) {
  856 + int columnWidth = sheet.getColumnWidth(columnNum) / 256;
  857 + for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
  858 + HSSFRow currentRow;
  859 + //当前行未被使用过
  860 + if (sheet.getRow(rowNum) == null) {
  861 + currentRow = sheet.createRow(rowNum);
  862 + } else {
  863 + currentRow = sheet.getRow(rowNum);
  864 + }
  865 + if (currentRow.getCell(columnNum) != null) {
  866 + HSSFCell currentCell = currentRow.getCell(columnNum);
  867 + if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
  868 + int length = currentCell.getStringCellValue().getBytes().length;
  869 + if (columnWidth < length) {
  870 + columnWidth = length;
  871 + }
  872 + }
  873 + }
  874 + }
  875 + sheet.setColumnWidth(columnNum, columnWidth * 300);
  876 +// sheet.setColumnWidth(columnNum, columnWidth * 256);
  877 + }
  878 + }
  879 +
  880 + /**
  881 + * 设置单元格值和样式
  882 + * @param row
  883 + * @param style
  884 + * @param index
  885 + * @param value
  886 + */
  887 + public static void setCellStyleAndValue(HSSFRow row,HSSFCellStyle style,int index,String value){
  888 + HSSFCell cell = row.createCell(index);
  889 + cell.setCellValue(value);
  890 + cell.setCellStyle(style);
  891 + }
  892 + /**
  893 + * 设置合并单元格样式
  894 + * @param cra
  895 + * @param sheet
  896 + * @param workbook
  897 + */
  898 + public static void setMergeCellStyle (CellRangeAddress cra, HSSFSheet sheet, Workbook workbook){
  899 + // 使用RegionUtil类为合并后的单元格添加边框
  900 + RegionUtil.setBorderBottom(1, cra, sheet, workbook); // 下边框
  901 + RegionUtil.setBorderLeft(1, cra, sheet, workbook); // 左边框
  902 + RegionUtil.setBorderRight(1, cra, sheet, workbook); // 有边框
  903 + RegionUtil.setBorderTop(1, cra, sheet, workbook); // 上边框
  904 + }
  905 +}