fwq
2024-09-29 9e4fb13fec8bf2732f4567e7e72eeb9fd94c840c
提交 | 用户 | age
826b66 1 package com.hx.util;
C 2
3 import com.hx.exception.TipsException;
4 import com.monitorjbl.xlsx.StreamingReader;
5 import org.apache.poi.hssf.usermodel.*;
6 import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException;
7 import org.apache.poi.ss.usermodel.*;
8 import org.apache.poi.xssf.streaming.SXSSFWorkbook;
9 import org.apache.poi.xssf.usermodel.XSSFCell;
10 import org.apache.poi.xssf.usermodel.XSSFRow;
11 import org.apache.poi.xssf.usermodel.XSSFSheet;
12 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
13 import org.springframework.web.multipart.MultipartFile;
14
15 import javax.imageio.ImageIO;
16 import java.awt.image.BufferedImage;
17 import java.io.*;
18 import java.text.DateFormat;
19 import java.text.SimpleDateFormat;
20 import java.util.ArrayList;
21 import java.util.Date;
22 import java.util.List;
23 import java.util.Map;
24
25
26 /**
27  *
28  * @author hjr
29  */
30 public final class ExcelUtil {
31
32     /**
33      * @param excelName
34      *         文件名称
35      * @param outPath
36      *             保存路径
37      * @param headList
38      *        Excel文件Head标题集合
39      * @param fieldList
40      *        Excel文件Field标题集合 根据field来寻找位置填充表格
41      * @param dataList
42      *        Excel文件数据内容部分
43      * @throws Exception
44      */
45     public static String createExcel(String outPath, String excelName,
46                                      String[] headList, String[] fieldList,
47                                      List<Map<String, Object>> dataList) throws Exception {
48
49         String filePath = null;
50         // 创建新的Excel 工作簿
51         HSSFWorkbook workbook = new HSSFWorkbook();
52
53         // 在Excel工作簿中建一工作表,其名为缺省值
54         // 如要新建一名为"效益指标"的工作表,其语句为:
55         // HSSFSheet sheet = workbook.createSheet("效益指标");
56         HSSFSheet sheet = workbook.createSheet();
57         // 在索引0的位置创建行(最顶端的行)
58         HSSFRow row = sheet.createRow(0);
59         // ===============================================================
60
61         HSSFCell cell;
62         for (int i = 0; i < headList.length; i++) {
63             // 在索引0的位置创建单元格(左上端)
64             cell = row.createCell(i);
65             // 定义单元格为字符串类型
66             //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
67             // 在单元格中输入一些内容
68             cell.setCellValue(headList[i]);
69         }
70         // ===============================================================
71         if (dataList != null) {
72             HSSFRow row_value;
73             Map<String, Object> dataMap;
74             for (int n = 0; n < dataList.size(); n++) {
75                 // 在索引1的位置创建行
76                 row_value = sheet.createRow(n + 1);
77                 dataMap = dataList.get(n);
78                 // ===============================================================
79                 for (int i = 0; i < fieldList.length; i++) {
80                     // 在索引0的位置创建单元格(左上端)
81                     cell = row_value.createCell(i);
82                     // 定义单元格为字符串类型
83                     //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
84                     // 在单元格中输入一些内容
85                     cell.setCellValue(objToString(dataMap.get(fieldList[i])));
86                 }
87                 // ===============================================================
88             }
89         }
90
91         // 新建一输出文件流
92         File file = SimpleTool.createFile(outPath, excelName);
93         FileOutputStream fOut = new FileOutputStream(file);
94         // 把相应的Excel 工作簿存盘
95         workbook.write(fOut);
96         fOut.flush();
97         // 操作结束,关闭文件
98         fOut.close();
99
100         if(outPath.endsWith("/")){
101             filePath = outPath + excelName;
102         }else{
103             filePath = outPath +"/"+ excelName;
104         }
105         return filePath;
106     }
107
108     /**生成临时文件
109      * @param headList
110      *        Excel文件Head标题集合
111      * @param fieldList
112      *        Excel文件Field标题集合 根据field来寻找位置填充表格
113      * @param dataList
114      *        Excel文件数据内容部分
115      * @throws Exception
116      */
117     public static File createExcel(String[] headList, String[] fieldList,
118                                    List<Map<String, Object>> dataList) throws Exception {
119         File file = File.createTempFile("temp", ".xlsx");
120         try{
121             // 创建新的Excel 工作簿
122             HSSFWorkbook workbook = new HSSFWorkbook();
123
124             // 在Excel工作簿中建一工作表,其名为缺省值
125             // 如要新建一名为"效益指标"的工作表,其语句为:
126             // HSSFSheet sheet = workbook.createSheet("效益指标");
127             HSSFSheet sheet = workbook.createSheet();
128             // 在索引0的位置创建行(最顶端的行)
129             HSSFRow row = sheet.createRow(0);
130             // ===============================================================
131             HSSFCell cell;
132             for (int i = 0; i < headList.length; i++) {
133                 // 在索引0的位置创建单元格(左上端)
134                 cell = row.createCell(i);
135                 // 定义单元格为字符串类型
136                 //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
137                 // 在单元格中输入一些内容
138                 cell.setCellValue(headList[i]);
139             }
140             // ===============================================================
141             if (dataList != null) {
142                 HSSFRow row_value;
143                 Map<String, Object> dataMap;
144                 for (int n = 0; n < dataList.size(); n++) {
145                     // 在索引1的位置创建行
146                     row_value = sheet.createRow(n + 1);
147                     dataMap = dataList.get(n);
148                     // ===============================================================
149                     for (int i = 0; i < fieldList.length; i++) {
150                         // 在索引0的位置创建单元格(左上端)
151                         cell = row_value.createCell(i);
152                         // 定义单元格为字符串类型
153                         //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
154                         // 在单元格中输入一些内容
155                         cell.setCellValue(objToString(dataMap.get(fieldList[i])));
156                     }
157                     // ===============================================================
158                 }
159             }
160
161             // 新建一输出文件流
162             FileOutputStream fOut = new FileOutputStream(file);
163             // 把相应的Excel 工作簿存盘
164             workbook.write(fOut);
165             fOut.flush();
166             // 操作结束,关闭文件
167             fOut.close();
168         }catch (Exception e){
169
170         }finally {
171             file.deleteOnExit();
172         }
173         return file;
174     }
175
176     /**生成临时文件
177      * @param headList
178      *        Excel文件Head标题集合
179      * @param fieldList
180      *        Excel文件Field标题集合 根据field来寻找位置填充表格
181      * @param dataList
182      *        Excel文件数据内容部分
183      * @throws Exception
184      */
185     public static File createExcel(String[] headList, String[] fieldList, List<Map<String, Object>> dataList
186             ,Integer height,Integer width) throws Exception {
187         File file = File.createTempFile("temp", ".xls");
188         try{
189
190             if(height == null){
191                 height = 450;
192             }
193             if(width == null){
194                 width = 5000;
195             }
196             // 创建新的Excel 工作簿
197             HSSFWorkbook workbook = new HSSFWorkbook();
198
199             //合并的单元格样式
200             HSSFCellStyle boderStyle = workbook.createCellStyle();
201             //垂直居中
202             boderStyle.setVerticalAlignment(VerticalAlignment.CENTER);
203             boderStyle.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
204
205             // 在Excel工作簿中建一工作表,其名为缺省值
206             // 如要新建一名为"效益指标"的工作表,其语句为:
207             // HSSFSheet sheet = workbook.createSheet("效益指标");
208             HSSFSheet sheet = workbook.createSheet();
209             // 在索引0的位置创建行(最顶端的行)
210             HSSFRow row = sheet.createRow(0);
211             // ===============================================================
212             HSSFCell cell;
213             for (int i = 0; i < headList.length; i++) {
214                 //高度
215                 row.setHeight(height.shortValue());
216                 sheet.setColumnWidth(i,width);
217                 // 在索引0的位置创建单元格(左上端)
218                 cell = row.createCell(i);
219                 // 定义单元格为字符串类型
220                 //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
221                 // 在单元格中输入一些内容
222                 cell.setCellValue(headList[i]);
223                 cell.setCellStyle(boderStyle);
224             }
225             // ===============================================================
226             if (dataList != null) {
227                 HSSFRow row_value;
228                 Map<String, Object> dataMap;
229                 for (int n = 0; n < dataList.size(); n++) {
230                     // 在索引1的位置创建行
231                     row_value = sheet.createRow(n + 1);
232                     row_value.setHeight(height.shortValue());
233                     dataMap = dataList.get(n);
234                     // ===============================================================
235                     for (int i = 0; i < fieldList.length; i++) {
236                         // 在索引0的位置创建单元格(左上端)
237                         sheet.setColumnWidth(i,width);
238                         cell = row_value.createCell(i);
239                         // 定义单元格为字符串类型
240                         //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
241                         // 在单元格中输入一些内容
242                         cell.setCellValue(objToString(dataMap.get(fieldList[i])));
243                         cell.setCellStyle(boderStyle);
244                     }
245                     // ===============================================================
246                 }
247             }
248
249             // 新建一输出文件流
250             FileOutputStream fOut = new FileOutputStream(file);
251             // 把相应的Excel 工作簿存盘
252             workbook.write(fOut);
253             fOut.flush();
254             // 操作结束,关闭文件
255             fOut.close();
256         }catch (Exception e){
257
258         }finally {
259             file.deleteOnExit();
260         }
261         return file;
262     }
263
264     /**无限制行数生成ecxel,生成临时文件
265      * @param headList
266      *        Excel文件Head标题集合
267      * @param fieldList
268      *        Excel文件Field标题集合 根据field来寻找位置填充表格
269      * @param dataList
270      *        Excel文件数据内容部分
271      * @param height  单元格高度,默认450
272      * @param width  单元格宽度,默认5000
273      * @throws Exception
274      */
275     public static File createXSSExcel(String[] headList, String[] fieldList, List<Map<String, Object>> dataList
276             ,Integer height,Integer width) throws Exception {
277         File file = File.createTempFile("temp", ".xls");
278         try{
279
280             if(height == null){
281                 height = 450;
282             }
283             if(width == null){
284                 width = 5000;
285             }
286             // 创建新的Excel 工作簿
287             //XSSFWorkbook workbook = new XSSFWorkbook();
288             SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
289
290             //合并的单元格样式
291             CellStyle boderStyle = workbook.createCellStyle();
292             //垂直居中
293             boderStyle.setVerticalAlignment(VerticalAlignment.CENTER);
294             boderStyle.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
295
296             // 在Excel工作簿中建一工作表,其名为缺省值
297             // 如要新建一名为"效益指标"的工作表,其语句为:
298             // HSSFSheet sheet = workbook.createSheet("效益指标");
299             Sheet sheet = workbook.createSheet();
300             // 在索引0的位置创建行(最顶端的行)
301             Row row = sheet.createRow(0);
302             // ===============================================================
303             Cell cell;
304             for (int i = 0; i < headList.length; i++) {
305                 //高度
306                 row.setHeight(height.shortValue());
307                 sheet.setColumnWidth(i,width);
308                 // 在索引0的位置创建单元格(左上端)
309                 cell = row.createCell(i);
310                 // 定义单元格为字符串类型
311                 //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
312                 // 在单元格中输入一些内容
313                 cell.setCellValue(headList[i]);
314                 cell.setCellStyle(boderStyle);
315             }
316             // ===============================================================
317             if (dataList != null) {
318                 Row row_value;
319                 Map<String, Object> dataMap;
320                 for (int n = 0; n < dataList.size(); n++) {
321                     // 在索引1的位置创建行
322                     row_value = sheet.createRow(n + 1);
323                     row_value.setHeight(height.shortValue());
324                     dataMap = dataList.get(n);
325                     // ===============================================================
326                     for (int i = 0; i < fieldList.length; i++) {
327                         // 在索引0的位置创建单元格(左上端)
328                         sheet.setColumnWidth(i,width);
329                         cell = row_value.createCell(i);
330                         // 定义单元格为字符串类型
331                         //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
332                         // 在单元格中输入一些内容
333                         cell.setCellValue(objToString(dataMap.get(fieldList[i])));
334                         cell.setCellStyle(boderStyle);
335                     }
336                     // ===============================================================
337                 }
338             }
339
340             // 新建一输出文件流
341             FileOutputStream fOut = new FileOutputStream(file);
342             // 把相应的Excel 工作簿存盘
343             workbook.write(fOut);
344             fOut.flush();
345             // 操作结束,关闭文件
346             fOut.close();
347         }catch (Exception e){
348
349         }finally {
350             file.deleteOnExit();
351         }
352         return file;
353     }
354
355
356     private static String objToString(Object obj) {
357         if (obj == null) {
358             return "";
359         } else {
360             if (obj instanceof String) {
361                 return (String) obj;
362             } else if (obj instanceof Date) {
363                 return null;// DateUtil.dateToString((Date)
364                 // obj,DateUtil.DATESTYLE_SHORT_EX);
365             } else {
366                 return obj.toString();
367             }
368         }
369     }
370
371     /**
372      * 读取Excel数据
373      * @param file
374      * @param header
375      * @return
376      * @throws Exception
377      */
378     public static List<List<String>> readExcelData(MultipartFile file, boolean header) throws Exception {
379
380         String fileName = file.getOriginalFilename();
381         if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
382             throw new TipsException("上传文件格式不正确");
383         }
384
385         //判断不同格式处理方法不同
386         if(fileName.matches("^.+\\.(?i)(xls)$")){
387             //xls格式使用HSSF
388             return readExcelByeFileData(file, header);
389         }else{
390             //xlsx格式使用XSSF
391             return readExcelByeFileDataToXSSF(file, header);
392         }
393     }
394
395     /**
396      * 读取 Excel文件内容
397      *
398      * @param file
399      * @param header 是否包括表头
400      * @return
401      * @throws Exception
402      */
403     public static List<List<String>> readExcelByeFileData(MultipartFile file, boolean header) throws Exception {
404
405         String fileName = file.getOriginalFilename();
406         if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
407             throw new TipsException("上传文件格式不正确");
408         }
409
410         // 结果集
411         List<List<String>> list = new ArrayList<>();
412
413         HSSFWorkbook hssfworkbook = new HSSFWorkbook(file.getInputStream());
414
415         // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
416         for(int s=0;s<hssfworkbook.getNumberOfSheets();s++) {
417             HSSFSheet hssfsheet = hssfworkbook.getSheetAt(s);
418             int col = 0;
419             // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
420             for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
421                 HSSFRow hssfrow = hssfsheet.getRow(j);
422                 if(hssfrow!=null){
423                     if(j == 0) {
424                         col = hssfrow.getPhysicalNumberOfCells();
425                         if(!header) {
426                             //不包括表头
427                             continue;
428                         }
429                     }
430                     // 单行数据
431                     List<String> arrayString = new ArrayList<>();
432                     for (int i = 0; i < col; i++) {
433                         HSSFCell cell = hssfrow.getCell(i);
434                         if (cell == null) {
435                             arrayString.add("");
436                         } else if (cell.getCellType() == CellType.NUMERIC) {
437                             // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
438                             if (CellType.NUMERIC == cell.getCellType()) {
439                                 short format = cell.getCellStyle().getDataFormat();
440                                 if(format == 14 || format == 31 || format == 57 || format == 58){
441                                     //日期(中文时间格式的)
442                                     Date d = cell.getDateCellValue();
443                                     DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
444                                     // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
445                                     arrayString.add(formater.format(d));
446                                     //arrayString[i] = formater.format(d);
447                                 }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
448                                     Date d = cell.getDateCellValue();
449                                     //DateFormat formater = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
450                                     DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
451                                     arrayString.add(formater.format(d));
452                                     //arrayString[i] = formater.format(d);
453                                 } else {
454                                     if(CellType.STRING == cell.getCellType()){
455                                         arrayString.add(cell.getStringCellValue());
456                                         //arrayString[i] =cell.getStringCellValue();
457                                     }else if(CellType.FORMULA==cell.getCellType()){
458                                         arrayString.add(cell.getCellFormula());
459                                         //arrayString[i] =cell.getCellFormula();
460                                     }else if(CellType.NUMERIC== cell.getCellType()){
461                                         HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
462                                         arrayString.add(dataFormatter.formatCellValue(cell));
463                                         //arrayString[i] =dataFormatter.formatCellValue(cell);
464                                     }
465                                 }
466                             }
467                         } else if(cell.getCellType() == CellType.BLANK){
468                             arrayString.add("");
469                             //arrayString[i] = "";
470                         } else { // 如果EXCEL表格中的数据类型为字符串型
471                             if(cell.getCellType() != CellType.BOOLEAN){
472                                 arrayString.add(cell.getStringCellValue().trim());
473                             }else{
474                                 arrayString.add(cell.getBooleanCellValue() ? "TRUE" : "FALSE");
475                             }
476                             //arrayString[i] = cell.getStringCellValue().trim();
477                         }
478                     }
479                     list.add(arrayString);
480                 }
481             }
482         }
483         return list;
484     }
485
486     /**
487      * 读取 Excel文件内容
488      *
489      * @param file
490      * @param header 是否包括表头
491      * @return
492      * @throws Exception
493      */
494     public static List<List<String>> readExcelByeFileDataToXSSF(MultipartFile file, boolean header) throws Exception {
495
496         String fileName = file.getOriginalFilename();
497         if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
498             throw new TipsException("上传文件格式不正确");
499         }
500
501         // 结果集
502         List<List<String>> list = new ArrayList<>();
503
504         XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file.getInputStream());
505
506         // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
507         for(int s=0;s<xssfWorkbook.getNumberOfSheets();s++) {
508             XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(s);
509             int col = 0;
510             // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
511             for (int j = 0; j < xssfSheet.getPhysicalNumberOfRows(); j++) {
512                 XSSFRow xssfrow = xssfSheet.getRow(j);
513                 if(xssfrow!=null){
514                     if(j == 0) {
515                         col = xssfrow.getPhysicalNumberOfCells();
516                         if(!header) {
517                             //不包括表头
518                             continue;
519                         }
520                     }
521                     // 单行数据
522                     List<String> arrayString = new ArrayList<>();
523                     for (int i = 0; i < col; i++) {
524                         XSSFCell cell = xssfrow.getCell(i);
525                         if (cell == null) {
526                             arrayString.add("");
527                         } else if (cell.getCellType() == CellType.NUMERIC) {
528                             // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
529                             if (CellType.NUMERIC == cell.getCellType()) {
530                                 short format = cell.getCellStyle().getDataFormat();
531                                 if(format == 14 || format == 31 || format == 57 || format == 58){
532                                     //日期(中文时间格式的)
533                                     Date d = cell.getDateCellValue();
534                                     DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
535                                     // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
536                                     arrayString.add(formater.format(d));
537                                     //arrayString[i] = formater.format(d);
538                                 }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
539                                     Date d = cell.getDateCellValue();
540                                     //DateFormat formater = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
541                                     DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
542                                     arrayString.add(formater.format(d));
543                                     //arrayString[i] = formater.format(d);
544                                 } else {
545                                     if(CellType.STRING == cell.getCellType()){
546                                         arrayString.add(cell.getStringCellValue());
547                                         //arrayString[i] =cell.getStringCellValue();
548                                     }else if(CellType.FORMULA==cell.getCellType()){
549                                         arrayString.add(cell.getCellFormula());
550                                         //arrayString[i] =cell.getCellFormula();
551                                     }else if(CellType.NUMERIC== cell.getCellType()){
552                                         HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
553                                         arrayString.add(dataFormatter.formatCellValue(cell));
554                                         //arrayString[i] =dataFormatter.formatCellValue(cell);
555                                     }
556                                 }
557                             }
558                         } else if(cell.getCellType() == CellType.BLANK){
559                             arrayString.add("");
560                             //arrayString[i] = "";
561                         } else { // 如果EXCEL表格中的数据类型为字符串型
562                             if(cell.getCellType() != CellType.BOOLEAN){
563                                 arrayString.add(cell.getStringCellValue().trim());
564                             }else{
565                                 arrayString.add(cell.getBooleanCellValue() ? "TRUE" : "FALSE");
566                             }
567
568
569                             //arrayString[i] = cell.getStringCellValue().trim();
570                         }
571                     }
572                     list.add(arrayString);
573                 }
574             }
575         }
576         return list;
577     }
578
579
580     /**判断excel的版本*/
581     public static Workbook create(InputStream inp) throws IOException {
582         //这样写  excel 能兼容03和07
583         return WorkbookFactory.create(inp);
584     }
585
586     /**读取excel文件,兼容2003和2007
587      * 通过流读取Excel文件
588      * @return
589      * @throws Exception
590      */
591     public static List<List<String>> getExcelDataCompatible(File file,boolean header) throws Exception {
592         try {
593
594             String fileName = file.getName();
595             if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
596                 throw new TipsException("上传文件格式不正确");
597             }
598
599             // 结果集
600             List<List<String>> list = new ArrayList<>();
601             Workbook book = create(new BufferedInputStream(new FileInputStream(file)));
602
603             // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
604             Sheet hssfsheet;
605             Row hssfrow;
606             List<String> arrayString;
607             Cell cell;
608             short format;
609             Date d;
610             DateFormat formater;
611             HSSFDataFormatter dataFormatter;
612             for(int s=0;s<book.getNumberOfSheets();s++) {
613                 hssfsheet = book.getSheetAt(s);
614                 int col = 0;
615                 // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
616                 for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
617                     hssfrow = hssfsheet.getRow(j);
618                     if(hssfrow!=null){
619                         if(j == 0) {
620                             col = hssfrow.getPhysicalNumberOfCells();
621                             if(!header) {
622                                 //不包括表头
623                                 continue;
624                             }
625                         }
626                         // 单行数据
627                         arrayString = new ArrayList<>();
628                         for (int i = 0; i < col; i++) {
629                             cell = hssfrow.getCell(i);
630                             if (cell == null) {
631                                 arrayString.add("");
632                             } else if (cell.getCellType() == CellType.NUMERIC) {
633                                 // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
634                                 if (CellType.NUMERIC == cell.getCellType()) {
635                                     format = cell.getCellStyle().getDataFormat();
636                                     if(format == 14 || format == 31 || format == 57 || format == 58){
637                                         //日期(中文时间格式的)
638                                          d = cell.getDateCellValue();
639                                          formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
640                                         // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
641                                         arrayString.add(formater.format(d));
642                                         //arrayString[i] = formater.format(d);
643                                     }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
644                                         d = cell.getDateCellValue();
645                                         //DateFormat formater = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
646                                         formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
647                                         arrayString.add(formater.format(d));
648                                         //arrayString[i] = formater.format(d);
649                                     } else {
650                                         if(CellType.STRING == cell.getCellType()){
651                                             arrayString.add(cell.getStringCellValue());
652                                             //arrayString[i] =cell.getStringCellValue();
653                                         }else if(CellType.FORMULA==cell.getCellType()){
654                                             arrayString.add(cell.getCellFormula());
655                                             //arrayString[i] =cell.getCellFormula();
656                                         }else if(CellType.NUMERIC== cell.getCellType()){
657                                             dataFormatter = new HSSFDataFormatter();
658                                             arrayString.add(dataFormatter.formatCellValue(cell));
659                                             //arrayString[i] =dataFormatter.formatCellValue(cell);
660                                         }
661                                     }
662                                 }
663                             } else if(cell.getCellType() == CellType.BLANK){
664                                 arrayString.add("");
665                                 //arrayString[i] = "";
666                             } else { // 如果EXCEL表格中的数据类型为字符串型
667                                 arrayString.add(cell.getStringCellValue().trim());
668                                 //arrayString[i] = cell.getStringCellValue().trim();
669                             }
670                         }
671                         list.add(arrayString);
672                     }
673                 }
674             }
675             return list;
676         } catch (Exception e) {
677             e.printStackTrace();
678         }
679         return null;
680     }
681
682     /**读取excel文件,兼容2003和2007
683      * 通过流读取Excel文件
684      * @return
685      * @throws Exception
686      */
687     public static List<List<String>> getExcelDataCompatible(MultipartFile file,boolean header) throws Exception {
688         try {
689
690             String fileName = file.getOriginalFilename();
691             if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
692                 throw new TipsException("上传文件格式不正确");
693             }
694
695             // 结果集
696             List<List<String>> list = new ArrayList<>();
697             Workbook book = create(new BufferedInputStream(file.getInputStream()));
698
699             Sheet hssfsheet;
700             Row hssfrow;
701             List<String> arrayString;
702             Cell cell;
703             short format;
704             Date d;
705             DateFormat formater;
706             HSSFDataFormatter dataFormatter;
707             // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
708             for(int s=0;s<book.getNumberOfSheets();s++) {
709                 hssfsheet = book.getSheetAt(s);
710                 int col = 0;
711                 // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
712                 for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
713                     hssfrow = hssfsheet.getRow(j);
714                     if(hssfrow!=null){
715                         if(j == 0) {
716                             col = hssfrow.getPhysicalNumberOfCells();
717                             if(!header) {
718                                 //不包括表头
719                                 continue;
720                             }
721                         }
722                         // 单行数据
723                         arrayString = new ArrayList<>();
724                         for (int i = 0; i < col; i++) {
725                             cell = hssfrow.getCell(i);
726                             if (cell == null) {
727                                 arrayString.add("");
728                             } else if (cell.getCellType() == CellType.NUMERIC) {
729                                 // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
730                                 if (CellType.NUMERIC == cell.getCellType()) {
731                                     format = cell.getCellStyle().getDataFormat();
732                                     if(format == 14 || format == 31 || format == 57 || format == 58){
733                                         //日期(中文时间格式的)
734                                         d = cell.getDateCellValue();
735                                         formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
736                                         // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
737                                         arrayString.add(formater.format(d));
738                                         //arrayString[i] = formater.format(d);
739                                     }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
740                                         d = cell.getDateCellValue();
741                                         //DateFormat formater = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
742                                         formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
743                                         arrayString.add(formater.format(d));
744                                         //arrayString[i] = formater.format(d);
745                                     } else {
746                                         if(CellType.STRING == cell.getCellType()){
747                                             arrayString.add(cell.getStringCellValue());
748                                             //arrayString[i] =cell.getStringCellValue();
749                                         }else if(CellType.FORMULA==cell.getCellType()){
750                                             arrayString.add(cell.getCellFormula());
751                                             //arrayString[i] =cell.getCellFormula();
752                                         }else if(CellType.NUMERIC== cell.getCellType()){
753                                             dataFormatter = new HSSFDataFormatter();
754                                             arrayString.add(dataFormatter.formatCellValue(cell));
755                                             //arrayString[i] =dataFormatter.formatCellValue(cell);
756                                         }
757                                     }
758                                 }
759                             } else if(cell.getCellType() == CellType.BLANK){
760                                 arrayString.add("");
761                                 //arrayString[i] = "";
762                             } else { // 如果EXCEL表格中的数据类型为字符串型
763                                 arrayString.add(cell.getStringCellValue().trim());
764                                 //arrayString[i] = cell.getStringCellValue().trim();
765                             }
766                         }
767                         list.add(arrayString);
768                     }
769                 }
770             }
771             return list;
772         } catch (Exception e) {
773             e.printStackTrace();
774         }
775         return null;
776     }
777
778     /**读取excel文件,兼容2003和2007
779      * 通过流读取Excel文件
780      * @return
781      * @throws Exception
782      */
783     public static List<List<String>> getExcelDataCompatible(InputStream inputStream,boolean header) throws Exception {
784         try {
785             // 结果集
786             List<List<String>> list = new ArrayList<>();
787             Workbook book = create(new BufferedInputStream(inputStream));
788
789             Sheet hssfsheet;
790             Row hssfrow;
791             List<String> arrayString;
792             Cell cell;
793             short format;
794             Date d;
795             DateFormat formater;
796             HSSFDataFormatter dataFormatter;
797             // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
798             for(int s=0;s<book.getNumberOfSheets();s++) {
799                 hssfsheet = book.getSheetAt(s);
800                 int col = 0;
801                 // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
802                 for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
803                     hssfrow = hssfsheet.getRow(j);
804                     if(hssfrow!=null){
805                         if(j == 0) {
806                             col = hssfrow.getPhysicalNumberOfCells();
807                             if(!header) {
808                                 //不包括表头
809                                 continue;
810                             }
811                         }
812                         // 单行数据
813                         arrayString = new ArrayList<>();
814                         for (int i = 0; i < col; i++) {
815                             cell = hssfrow.getCell(i);
816                             if (cell == null) {
817                                 arrayString.add("");
818                             } else if (cell.getCellType() == CellType.NUMERIC) {
819                                 // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
820                                 if (CellType.NUMERIC == cell.getCellType()) {
821                                     format = cell.getCellStyle().getDataFormat();
822                                     if(format == 14 || format == 31 || format == 57 || format == 58){
823                                         //日期(中文时间格式的)
824                                         d = cell.getDateCellValue();
825                                         formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
826                                         // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
827                                         arrayString.add(formater.format(d));
828                                         //arrayString[i] = formater.format(d);
829                                     }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
830                                         d = cell.getDateCellValue();
831                                         //DateFormat formater = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
832                                         formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
833                                         arrayString.add(formater.format(d));
834                                         //arrayString[i] = formater.format(d);
835                                     } else {
836                                         if(CellType.STRING == cell.getCellType()){
837                                             arrayString.add(cell.getStringCellValue());
838                                             //arrayString[i] =cell.getStringCellValue();
839                                         }else if(CellType.FORMULA==cell.getCellType()){
840                                             arrayString.add(cell.getCellFormula());
841                                             //arrayString[i] =cell.getCellFormula();
842                                         }else if(CellType.NUMERIC== cell.getCellType()){
843                                             dataFormatter = new HSSFDataFormatter();
844                                             arrayString.add(dataFormatter.formatCellValue(cell));
845                                             //arrayString[i] =dataFormatter.formatCellValue(cell);
846                                         }
847                                     }
848                                 }
849                             } else if(cell.getCellType() == CellType.BLANK){
850                                 arrayString.add("");
851                                 //arrayString[i] = "";
852                             } else { // 如果EXCEL表格中的数据类型为字符串型
853                                 arrayString.add(cell.getStringCellValue().trim());
854                                 //arrayString[i] = cell.getStringCellValue().trim();
855                             }
856                         }
857                         list.add(arrayString);
858                     }
859                 }
860             }
861             return list;
862         } catch (Exception e) {
863             e.printStackTrace();
864         }
865         return null;
866     }
867
868     /**
869      * 新版读取Excel,只支持2007以上版本,也就是xslx格式
870      * 支持大数据量
871      * @param file 文件
872      * @return 数据
873      */
874     public static List<List<String>> readExcelData(File file){
875         if(!isExcel(file)){
876             throw new TipsException("请上传excel的文件格式!");
877         }
878         List<List<String>> listData = new ArrayList<>();
879         try{
880             //rowCacheSize 缓存到内存中的行数(默认是10)
881             //bufferSize 读取资源时,缓存到内存的字节大小(默认是1024)
882             //open InputStream或者XLSX格式的File(必须)
883             Workbook book = StreamingReader.builder()
884                     .rowCacheSize(100)
885                     .bufferSize(10240)
886                     .open(new FileInputStream(file));
887             listData =readhandle(book);
888         }catch (OLE2NotOfficeXmlFileException ex){
889             ex.printStackTrace();
890             throw new RuntimeException("excel版本不为2007及以上");
891         } catch (Exception e){
892             e.printStackTrace();
893             throw new RuntimeException(e.getMessage());
894         }
895         return listData;
896     }
897
898     /**
899      * 新版读取Excel,只支持2007以上版本,也就是xslx格式
900      * 支持大数据量
901      * @param file 文件
902      * @return 数据
903      */
904     public static List<List<String>> readExcelData(MultipartFile file){
905         if(!isExcel(file)){
906             throw new TipsException("请上传excel的文件格式!");
907         }
908         List<List<String>> listData = new ArrayList<>();
909         try{
910             //rowCacheSize 缓存到内存中的行数(默认是10)
911             //bufferSize 读取资源时,缓存到内存的字节大小(默认是1024)
912             //open InputStream或者XLSX格式的File(必须)
913             Workbook book = StreamingReader.builder()
914                     .rowCacheSize(100)
915                     .bufferSize(10240)
916                     .open(new BufferedInputStream(file.getInputStream()));
917
918             listData =readhandle(book);
919         }catch (OLE2NotOfficeXmlFileException ex){
920             ex.printStackTrace();
921             throw new RuntimeException("excel版本不为2007及以上");
922         } catch (Exception e){
923             e.printStackTrace();
924             throw new RuntimeException(e.getMessage());
925         }
926         return listData;
927     }
928
929     /**
930      * 新版读取Excel,只支持2007以上版本,也就是xslx格式
931      * 支持大数据量
932      * @param file 文件
933      * @return 数据
934      */
935     public static List<List<String>> readExcelData(InputStream file){
936         List<List<String>> listData = new ArrayList<>();
937         try{
938             //rowCacheSize 缓存到内存中的行数(默认是10)
939             //bufferSize 读取资源时,缓存到内存的字节大小(默认是1024)
940             //open InputStream或者XLSX格式的File(必须)
941             Workbook book = StreamingReader.builder()
942                     .rowCacheSize(100)
943                     .bufferSize(10240)
944                     .open(file);
945
946             listData =readhandle(book);
947         }catch (OLE2NotOfficeXmlFileException ex){
948             ex.printStackTrace();
949             throw new RuntimeException("excel版本不为2007及以上");
950         }catch (Exception e){
951             e.printStackTrace();
952             throw new RuntimeException(e.getMessage());
953         }
954         return listData;
955     }
956
957     /**处理数据*/
958     public static List<List<String>> readhandle(Workbook book){
959         List<List<String>> listData = new ArrayList<>();
960
961         //是否存在数据
962         boolean isData;
963         List<String> arrayString;
964         short format;
965         Date d;
966         DateFormat formater;
967         Sheet sheet;
968         Cell cell;
969         //遍历所有的sheet
970         for(int i=0;i<book.getNumberOfSheets();i++) {
971             sheet = book.getSheetAt(i);
972             //列数
973             Integer arrange = null;
974             //遍历所有的行
975             for (Row row : sheet) {
976                 if(row == null){
977                     continue;
978                 }
979                 isData = false;
980                 arrayString = new ArrayList<>();
981                 if(arrange == null){
982                     arrange = row.getPhysicalNumberOfCells();
983                 }
984                 //遍历所有的列
985                 for (int j = 0;j<arrange;j++) {
986                     cell = row.getCell(j);
987                     if (cell == null) {
988                         arrayString.add("");
989                     }else{
990                         if (cell.getCellType() == CellType.NUMERIC) {
991                             isData = true;
992                             format = cell.getCellStyle().getDataFormat();
993                             if (format == 14 || format == 31 || format == 57 || format == 58) {
994                                 //日期(中文时间格式的)
995                                 d = cell.getDateCellValue();
996                                 formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
997                                 arrayString.add(formater.format(d));
998                             } else if (HSSFDateUtil.isCellDateFormatted(cell)) {
999                                 d = cell.getDateCellValue();
1000                                 formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
1001                                 arrayString.add(formater.format(d));
1002                             } else {
1003                                 if (CellType.STRING == cell.getCellType()) {
1004                                     arrayString.add(cell.getStringCellValue());
1005                                 } else if (CellType.FORMULA == cell.getCellType()) {
1006                                     arrayString.add(cell.getCellFormula());
1007                                 } else {
1008                                     arrayString.add(cell.getStringCellValue().trim());
1009                                 }
1010                             }
1011                         } else if (cell.getCellType() == CellType.BLANK) {
1012                             arrayString.add("");
1013                         } else { // 如果EXCEL表格中的数据类型为字符串型
1014                             isData = true;
1015                             arrayString.add(cell.getStringCellValue().trim());
1016                         }
1017                     }
1018                 }
1019                 if (isData) {
1020                     listData.add(arrayString);
1021                 }
1022             }
1023         }
1024         return listData;
1025     }
1026
1027
1028     /**
1029      * p判断是否excel文件
1030      * @param file
1031      * @return
1032      */
1033     public static boolean isExcel(MultipartFile file){
1034         return isExcel(file.getOriginalFilename());
1035     }
1036
1037
1038     /**
1039      * p判断是否excel文件
1040      * @param file
1041      * @return
1042      */
1043     public static boolean isExcel(File file){
1044         return isExcel(file.getName());
1045     }
1046
1047
1048     /**判断文件格式是不是excel*/
1049     public static boolean isExcel(String fileName){
1050         if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
1051             return false;
1052         }
1053         return true;
1054     }
1055
1056     public static File createExcelByImg(String[] headList, String[] fieldList, List<Map<String, Object>> dataList, Integer height, Integer width) throws Exception {
1057         File file = File.createTempFile("temp", ".xls");
1058         FileOutputStream fileOut = null;
1059         BufferedImage bufferImg = null;
1060
1061         try {
1062             ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
1063             if (height == null) {
1064                 height = 450;
1065             }
1066
1067             if (width == null) {
1068                 width = 1000;
1069             }
1070
1071             HSSFWorkbook workbook = new HSSFWorkbook();
1072             HSSFCellStyle boderStyle = workbook.createCellStyle();
1073             boderStyle.setVerticalAlignment(VerticalAlignment.CENTER);
1074             boderStyle.setAlignment(HorizontalAlignment.CENTER);
1075             HSSFSheet sheet = workbook.createSheet();
1076             HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
1077             HSSFRow row = sheet.createRow(0);
1078
1079             HSSFCell anchor;
1080             for(int i = 0; i < headList.length; ++i) {
1081                 row.setHeight(height.shortValue());
1082                 sheet.setColumnWidth(i, width);
1083                 anchor = row.createCell(i);
1084                 anchor.setCellValue(headList[i]);
1085                 anchor.setCellStyle(boderStyle);
1086             }
1087
1088             HSSFRow row_value = null;
1089             anchor = null;
1090             HSSFCell cell = null;
1091             if (dataList != null) {
1092                 for(int n = 0; n < dataList.size(); ++n) {
1093                     row_value = sheet.createRow(n + 1);
1094                     row_value.setHeight(height.shortValue());
1095                     Map<String, Object> dataMap = (Map)dataList.get(n);
1096
1097                     for(int i = 0; i < fieldList.length; ++i) {
1098                         sheet.setColumnWidth(i, width);
1099                         cell = row_value.createCell(i);
1100                         Object value = dataMap.get(fieldList[i]);
1101                         if (value != null && "class java.io.File".equals(value.getClass().toString())) {
1102                             File file2 = (File)value;
1103                             if (file2 == null) {
1104                                 cell.setCellValue("");
1105                             } else {
1106                                 bufferImg = ImageIO.read(file2);
1107                                 ImageIO.write(bufferImg, "jpg", byteArrayOut);
1108                                 HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 1023, 255, (short)i, n + 1, (short)i, n + 1);
1109                                 anchor1.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
1110                                 patriarch.createPicture(anchor1, workbook.addPicture(byteArrayOut.toByteArray(), 5));
1111                             }
1112                         } else {
1113                             cell.setCellValue(objToString(dataMap.get(fieldList[i])));
1114                             cell.setCellStyle(boderStyle);
1115                         }
1116                     }
1117                 }
1118             }
1119
1120             FileOutputStream fOut = new FileOutputStream(file);
1121             workbook.write(fOut);
1122             fOut.flush();
1123             fOut.close();
1124         } catch (Exception var25) {
1125             var25.printStackTrace();
1126         } finally {
1127             file.deleteOnExit();
1128         }
1129
1130         return file;
1131     }
1132
1133 }