wangrenhuang
2023-04-03 d15b472a5979b2562e95784adff3e81f738c958f
提交 | 用户 | age
5c5945 1 package com.hx.util;
E 2
3 import com.hx.exception.TipsException;
cac339 4 import org.apache.poi.POIXMLDocument;
5c5945 5 import org.apache.poi.hssf.usermodel.*;
cac339 6 import org.apache.poi.openxml4j.opc.OPCPackage;
C 7 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
5c5945 8 import org.apache.poi.ss.usermodel.Cell;
cac339 9 import org.apache.poi.ss.usermodel.Row;
C 10 import org.apache.poi.ss.usermodel.Sheet;
11 import org.apache.poi.ss.usermodel.Workbook;
1b1815 12 import org.apache.poi.xssf.usermodel.*;
5c5945 13 import org.springframework.web.multipart.MultipartFile;
c6eec8 14
6b6bf5 15 import javax.imageio.ImageIO;
W 16 import java.awt.image.BufferedImage;
c6eec8 17 import java.io.*;
F 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;
5c5945 24
E 25
26 /**
cac339 27  *
5c5945 28  * @author hjr
E 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,
cac339 46                                      String[] headList, String[] fieldList,
C 47                                      List<Map<String, Object>> dataList) throws Exception {
5c5945 48
E 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         for (int i = 0; i < headList.length; i++) {
61
62             // 在索引0的位置创建单元格(左上端)
63             HSSFCell cell = row.createCell(i);
64             // 定义单元格为字符串类型
65             cell.setCellType(HSSFCell.CELL_TYPE_STRING);
66             // 在单元格中输入一些内容
67             cell.setCellValue(headList[i]);
68         }
69         // ===============================================================
70         if (dataList != null) {
71             for (int n = 0; n < dataList.size(); n++) {
72                 // 在索引1的位置创建行
73                 HSSFRow row_value = sheet.createRow(n + 1);
74                 Map<String, Object> dataMap = dataList.get(n);
75                 // ===============================================================
76                 for (int i = 0; i < fieldList.length; i++) {
77                     // 在索引0的位置创建单元格(左上端)
78                     HSSFCell cell = row_value.createCell(i);
79                     // 定义单元格为字符串类型
80                     cell.setCellType(HSSFCell.CELL_TYPE_STRING);
81                     // 在单元格中输入一些内容
82                     cell.setCellValue(objToString(dataMap.get(fieldList[i])));
83                 }
84                 // ===============================================================
85             }
86         }
87
88         // 新建一输出文件流
c6eec8 89         File file = SimpleTool.createFile(outPath, excelName);
5c5945 90         FileOutputStream fOut = new FileOutputStream(file);
E 91         // 把相应的Excel 工作簿存盘
92         workbook.write(fOut);
93         fOut.flush();
94         // 操作结束,关闭文件
95         fOut.close();
96
97         if(outPath.endsWith("/")){
98             filePath = outPath + excelName;
99         }else{
100             filePath = outPath +"/"+ excelName;
101         }
102         return filePath;
103     }
104
db7fc9 105     /**生成临时文件
C 106      * @param headList
107      *        Excel文件Head标题集合
108      * @param fieldList
109      *        Excel文件Field标题集合 根据field来寻找位置填充表格
110      * @param dataList
111      *        Excel文件数据内容部分
112      * @throws Exception
113      */
114     public static File createExcel(String[] headList, String[] fieldList,
cac339 115                                    List<Map<String, Object>> dataList) throws Exception {
b4fb02 116         File file = File.createTempFile("temp", ".xlsx");
db7fc9 117         try{
C 118             // 创建新的Excel 工作簿
119             HSSFWorkbook workbook = new HSSFWorkbook();
120
121             // 在Excel工作簿中建一工作表,其名为缺省值
122             // 如要新建一名为"效益指标"的工作表,其语句为:
123             // HSSFSheet sheet = workbook.createSheet("效益指标");
124             HSSFSheet sheet = workbook.createSheet();
125             // 在索引0的位置创建行(最顶端的行)
126             HSSFRow row = sheet.createRow(0);
127             // ===============================================================
128             for (int i = 0; i < headList.length; i++) {
129
130                 // 在索引0的位置创建单元格(左上端)
131                 HSSFCell cell = row.createCell(i);
132                 // 定义单元格为字符串类型
133                 cell.setCellType(HSSFCell.CELL_TYPE_STRING);
134                 // 在单元格中输入一些内容
135                 cell.setCellValue(headList[i]);
136             }
137             // ===============================================================
138             if (dataList != null) {
139                 for (int n = 0; n < dataList.size(); n++) {
140                     // 在索引1的位置创建行
141                     HSSFRow row_value = sheet.createRow(n + 1);
142                     Map<String, Object> dataMap = dataList.get(n);
143                     // ===============================================================
144                     for (int i = 0; i < fieldList.length; i++) {
145                         // 在索引0的位置创建单元格(左上端)
146                         HSSFCell cell = row_value.createCell(i);
147                         // 定义单元格为字符串类型
148                         cell.setCellType(HSSFCell.CELL_TYPE_STRING);
149                         // 在单元格中输入一些内容
150                         cell.setCellValue(objToString(dataMap.get(fieldList[i])));
151                     }
152                     // ===============================================================
153                 }
154             }
155
156             // 新建一输出文件流
157             FileOutputStream fOut = new FileOutputStream(file);
158             // 把相应的Excel 工作簿存盘
159             workbook.write(fOut);
160             fOut.flush();
161             // 操作结束,关闭文件
162             fOut.close();
163         }catch (Exception e){
164
165         }finally {
166             file.deleteOnExit();
167         }
168         return file;
169     }
170
49f28b 171     /**生成临时文件
C 172      * @param headList
173      *        Excel文件Head标题集合
174      * @param fieldList
175      *        Excel文件Field标题集合 根据field来寻找位置填充表格
176      * @param dataList
177      *        Excel文件数据内容部分
178      * @throws Exception
179      */
180     public static File createExcel(String[] headList, String[] fieldList, List<Map<String, Object>> dataList
181             ,Integer height,Integer width) throws Exception {
182         File file = File.createTempFile("temp", ".xls");
183         try{
184
185             if(height == null){
186                 height = 450;
187             }
188             if(width == null){
189                 width = 5000;
190             }
191             // 创建新的Excel 工作簿
192             HSSFWorkbook workbook = new HSSFWorkbook();
193
194             //合并的单元格样式
195             HSSFCellStyle boderStyle = workbook.createCellStyle();
196             //垂直居中
197             boderStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
198             boderStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
199
200             // 在Excel工作簿中建一工作表,其名为缺省值
201             // 如要新建一名为"效益指标"的工作表,其语句为:
202             // HSSFSheet sheet = workbook.createSheet("效益指标");
203             HSSFSheet sheet = workbook.createSheet();
204             // 在索引0的位置创建行(最顶端的行)
205             HSSFRow row = sheet.createRow(0);
206             // ===============================================================
207             for (int i = 0; i < headList.length; i++) {
208                 //高度
209                 row.setHeight(height.shortValue());
210                 sheet.setColumnWidth(i,width);
211                 // 在索引0的位置创建单元格(左上端)
212                 HSSFCell cell = row.createCell(i);
213                 // 定义单元格为字符串类型
214                 cell.setCellType(HSSFCell.CELL_TYPE_STRING);
215                 // 在单元格中输入一些内容
216                 cell.setCellValue(headList[i]);
217                 cell.setCellStyle(boderStyle);
218             }
219             // ===============================================================
220             if (dataList != null) {
221                 for (int n = 0; n < dataList.size(); n++) {
222                     // 在索引1的位置创建行
223                     HSSFRow row_value = sheet.createRow(n + 1);
224                     row_value.setHeight(height.shortValue());
225                     Map<String, Object> dataMap = dataList.get(n);
226                     // ===============================================================
227                     for (int i = 0; i < fieldList.length; i++) {
228                         // 在索引0的位置创建单元格(左上端)
229                         sheet.setColumnWidth(i,width);
230                         HSSFCell cell = row_value.createCell(i);
231                         // 定义单元格为字符串类型
232                         cell.setCellType(HSSFCell.CELL_TYPE_STRING);
233                         // 在单元格中输入一些内容
234                         cell.setCellValue(objToString(dataMap.get(fieldList[i])));
235                         cell.setCellStyle(boderStyle);
236                     }
237                     // ===============================================================
238                 }
239             }
240
241             // 新建一输出文件流
242             FileOutputStream fOut = new FileOutputStream(file);
243             // 把相应的Excel 工作簿存盘
244             workbook.write(fOut);
245             fOut.flush();
246             // 操作结束,关闭文件
247             fOut.close();
248         }catch (Exception e){
249
250         }finally {
251             file.deleteOnExit();
252         }
253         return file;
254     }
255
1b1815 256     /**无限制行数生成ecxel,生成临时文件
C 257      * @param headList
258      *        Excel文件Head标题集合
259      * @param fieldList
260      *        Excel文件Field标题集合 根据field来寻找位置填充表格
261      * @param dataList
262      *        Excel文件数据内容部分
263      * @param height  单元格高度,默认450
264      * @param width  单元格宽度,默认5000
265      * @throws Exception
266      */
267     public static File createXSSExcel(String[] headList, String[] fieldList, List<Map<String, Object>> dataList
268             ,Integer height,Integer width) throws Exception {
269         File file = File.createTempFile("temp", ".xls");
270         try{
271
272             if(height == null){
273                 height = 450;
274             }
275             if(width == null){
276                 width = 5000;
277             }
278             // 创建新的Excel 工作簿
279             XSSFWorkbook workbook = new XSSFWorkbook();
280
281
282             //合并的单元格样式
283             XSSFCellStyle boderStyle = workbook.createCellStyle();
284             //垂直居中
285             boderStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
286             boderStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
287
288             // 在Excel工作簿中建一工作表,其名为缺省值
289             // 如要新建一名为"效益指标"的工作表,其语句为:
290             // HSSFSheet sheet = workbook.createSheet("效益指标");
291             XSSFSheet sheet = workbook.createSheet();
292             // 在索引0的位置创建行(最顶端的行)
293             XSSFRow row = sheet.createRow(0);
294             // ===============================================================
295             for (int i = 0; i < headList.length; i++) {
296                 //高度
297                 row.setHeight(height.shortValue());
298                 sheet.setColumnWidth(i,width);
299                 // 在索引0的位置创建单元格(左上端)
300                 XSSFCell cell = row.createCell(i);
301                 // 定义单元格为字符串类型
302                 cell.setCellType(HSSFCell.CELL_TYPE_STRING);
303                 // 在单元格中输入一些内容
304                 cell.setCellValue(headList[i]);
305                 cell.setCellStyle(boderStyle);
306             }
307             // ===============================================================
308             if (dataList != null) {
309                 for (int n = 0; n < dataList.size(); n++) {
310                     // 在索引1的位置创建行
311                     XSSFRow row_value = sheet.createRow(n + 1);
312                     row_value.setHeight(height.shortValue());
313                     Map<String, Object> dataMap = dataList.get(n);
314                     // ===============================================================
315                     for (int i = 0; i < fieldList.length; i++) {
316                         // 在索引0的位置创建单元格(左上端)
317                         sheet.setColumnWidth(i,width);
318                         XSSFCell cell = row_value.createCell(i);
319                         // 定义单元格为字符串类型
320                         cell.setCellType(HSSFCell.CELL_TYPE_STRING);
321                         // 在单元格中输入一些内容
322                         cell.setCellValue(objToString(dataMap.get(fieldList[i])));
323                         cell.setCellStyle(boderStyle);
324                     }
325                     // ===============================================================
326                 }
327             }
328
329             // 新建一输出文件流
330             FileOutputStream fOut = new FileOutputStream(file);
331             // 把相应的Excel 工作簿存盘
332             workbook.write(fOut);
333             fOut.flush();
334             // 操作结束,关闭文件
335             fOut.close();
336         }catch (Exception e){
337
338         }finally {
339             file.deleteOnExit();
340         }
341         return file;
342     }
343
db7fc9 344
5c5945 345     private static String objToString(Object obj) {
E 346         if (obj == null) {
347             return "";
348         } else {
349             if (obj instanceof String) {
350                 return (String) obj;
351             } else if (obj instanceof Date) {
352                 return null;// DateUtil.dateToString((Date)
cac339 353                 // obj,DateUtil.DATESTYLE_SHORT_EX);
5c5945 354             } else {
E 355                 return obj.toString();
356             }
357         }
358     }
359
360     /**
c6eec8 361      * 读取Excel数据
F 362      * @param file
363      * @param header
364      * @return
365      * @throws Exception
366      */
367     public static List<List<String>> readExcelData(MultipartFile file, boolean header) throws Exception {
368
369         String fileName = file.getOriginalFilename();
370         if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
371             throw new TipsException("上传文件格式不正确");
372         }
373
374         //判断不同格式处理方法不同
375         if(fileName.matches("^.+\\.(?i)(xls)$")){
376             //xls格式使用HSSF
377             return readExcelByeFileData(file, header);
378         }else{
379             //xlsx格式使用XSSF
380             return readExcelByeFileDataToXSSF(file, header);
381         }
382     }
383
384     /**
5c5945 385      * 读取 Excel文件内容
E 386      *
387      * @param file
388      * @param header 是否包括表头
389      * @return
390      * @throws Exception
391      */
392     public static List<List<String>> readExcelByeFileData(MultipartFile file, boolean header) throws Exception {
393
394         String fileName = file.getOriginalFilename();
395         if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
396             throw new TipsException("上传文件格式不正确");
397         }
398
399         // 结果集
400         List<List<String>> list = new ArrayList<>();
401
402         HSSFWorkbook hssfworkbook = new HSSFWorkbook(file.getInputStream());
403
404         // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
405         for(int s=0;s<hssfworkbook.getNumberOfSheets();s++) {
406             HSSFSheet hssfsheet = hssfworkbook.getSheetAt(s);
407             int col = 0;
408             // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
409             for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
410                 HSSFRow hssfrow = hssfsheet.getRow(j);
411                 if(hssfrow!=null){
412                     if(j == 0) {
413                         col = hssfrow.getPhysicalNumberOfCells();
414                         if(!header) {
415                             //不包括表头
416                             continue;
417                         }
418                     }
419                     // 单行数据
420                     List<String> arrayString = new ArrayList<>();
421                     for (int i = 0; i < col; i++) {
422                         HSSFCell cell = hssfrow.getCell(i);
423                         if (cell == null) {
424                             arrayString.add("");
425                         } else if (cell.getCellType() == 0) {
426                             // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
427                             if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
428                                 short format = cell.getCellStyle().getDataFormat();
429                                 if(format == 14 || format == 31 || format == 57 || format == 58){
430                                     //日期(中文时间格式的)
431                                     Date d = cell.getDateCellValue();
432                                     DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
433                                     // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
434                                     arrayString.add(formater.format(d));
435                                     //arrayString[i] = formater.format(d);
436                                 }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
437                                     Date d = cell.getDateCellValue();
438                                     //DateFormat formater = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
439                                     DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
440                                     arrayString.add(formater.format(d));
441                                     //arrayString[i] = formater.format(d);
442                                 } else {
443                                     if(HSSFCell.CELL_TYPE_STRING == cell.getCellType()){
444                                         arrayString.add(cell.getStringCellValue());
445                                         //arrayString[i] =cell.getStringCellValue();
446                                     }else if(HSSFCell.CELL_TYPE_FORMULA==cell.getCellType()){
447                                         arrayString.add(cell.getCellFormula());
448                                         //arrayString[i] =cell.getCellFormula();
449                                     }else if(HSSFCell.CELL_TYPE_NUMERIC== cell.getCellType()){
450                                         HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
451                                         arrayString.add(dataFormatter.formatCellValue(cell));
452                                         //arrayString[i] =dataFormatter.formatCellValue(cell);
453                                     }
454                                 }
455                             }
456                         } else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
457                             arrayString.add("");
458                             //arrayString[i] = "";
459                         } else { // 如果EXCEL表格中的数据类型为字符串型
b77bfb 460                             if(cell.getCellType() != Cell.CELL_TYPE_BOOLEAN){
F 461                                 arrayString.add(cell.getStringCellValue().trim());
462                             }else{
463                                 arrayString.add(cell.getBooleanCellValue() ? "TRUE" : "FALSE");
464                             }
5c5945 465                             //arrayString[i] = cell.getStringCellValue().trim();
E 466                         }
467                     }
468                     list.add(arrayString);
469                 }
470             }
471         }
472         return list;
473     }
474
c6eec8 475     /**
F 476      * 读取 Excel文件内容
477      *
478      * @param file
479      * @param header 是否包括表头
480      * @return
481      * @throws Exception
482      */
483     public static List<List<String>> readExcelByeFileDataToXSSF(MultipartFile file, boolean header) throws Exception {
484
485         String fileName = file.getOriginalFilename();
486         if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
487             throw new TipsException("上传文件格式不正确");
488         }
489
490         // 结果集
491         List<List<String>> list = new ArrayList<>();
492
493         XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file.getInputStream());
494
495         // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
496         for(int s=0;s<xssfWorkbook.getNumberOfSheets();s++) {
497             XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(s);
498             int col = 0;
499             // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
500             for (int j = 0; j < xssfSheet.getPhysicalNumberOfRows(); j++) {
501                 XSSFRow xssfrow = xssfSheet.getRow(j);
502                 if(xssfrow!=null){
503                     if(j == 0) {
504                         col = xssfrow.getPhysicalNumberOfCells();
505                         if(!header) {
506                             //不包括表头
507                             continue;
508                         }
509                     }
510                     // 单行数据
511                     List<String> arrayString = new ArrayList<>();
512                     for (int i = 0; i < col; i++) {
513                         XSSFCell cell = xssfrow.getCell(i);
514                         if (cell == null) {
515                             arrayString.add("");
516                         } else if (cell.getCellType() == 0) {
517                             // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
b77bfb 518                             if (XSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
c6eec8 519                                 short format = cell.getCellStyle().getDataFormat();
F 520                                 if(format == 14 || format == 31 || format == 57 || format == 58){
521                                     //日期(中文时间格式的)
522                                     Date d = cell.getDateCellValue();
523                                     DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
524                                     // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
525                                     arrayString.add(formater.format(d));
526                                     //arrayString[i] = formater.format(d);
527                                 }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
528                                     Date d = cell.getDateCellValue();
529                                     //DateFormat formater = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
530                                     DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
531                                     arrayString.add(formater.format(d));
532                                     //arrayString[i] = formater.format(d);
533                                 } else {
b77bfb 534                                     if(XSSFCell.CELL_TYPE_STRING == cell.getCellType()){
c6eec8 535                                         arrayString.add(cell.getStringCellValue());
F 536                                         //arrayString[i] =cell.getStringCellValue();
b77bfb 537                                     }else if(XSSFCell.CELL_TYPE_FORMULA==cell.getCellType()){
c6eec8 538                                         arrayString.add(cell.getCellFormula());
F 539                                         //arrayString[i] =cell.getCellFormula();
b77bfb 540                                     }else if(XSSFCell.CELL_TYPE_NUMERIC== cell.getCellType()){
c6eec8 541                                         HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
F 542                                         arrayString.add(dataFormatter.formatCellValue(cell));
543                                         //arrayString[i] =dataFormatter.formatCellValue(cell);
544                                     }
545                                 }
546                             }
547                         } else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
548                             arrayString.add("");
549                             //arrayString[i] = "";
550                         } else { // 如果EXCEL表格中的数据类型为字符串型
b77bfb 551                             if(cell.getCellType() != Cell.CELL_TYPE_BOOLEAN){
F 552                                 arrayString.add(cell.getStringCellValue().trim());
553                             }else{
554                                 arrayString.add(cell.getBooleanCellValue() ? "TRUE" : "FALSE");
555                             }
556
557
c6eec8 558                             //arrayString[i] = cell.getStringCellValue().trim();
F 559                         }
560                     }
561                     list.add(arrayString);
562                 }
563             }
564         }
565         return list;
566     }
567
cac339 568
C 569     /**判断excel的版本*/
570     public static Workbook create(InputStream inp) throws Exception {
571         if (!inp.markSupported()) {
572             inp = new PushbackInputStream(inp, 8);
573         }
574         if (POIFSFileSystem.hasPOIFSHeader(inp)) {
575             return new HSSFWorkbook(inp);
576         }
577         if (POIXMLDocument.hasOOXMLHeader(inp)) {
578             return new XSSFWorkbook(OPCPackage.open(inp));
579         }
580         throw new IllegalArgumentException("你的excel版本目前poi解析不了");
581     }
582
583     /**读取excel文件,兼容2003和2007
584      * 通过流读取Excel文件
585      * @return
586      * @throws Exception
587      */
3f4072 588     public static List<List<String>> getExcelDataCompatible(File file,boolean header) throws Exception {
C 589         try {
590
591             String fileName = file.getName();
592             if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
593                 throw new TipsException("上传文件格式不正确");
594             }
595
596             // 结果集
597             List<List<String>> list = new ArrayList<>();
598             Workbook book = create(new BufferedInputStream(new FileInputStream(file)));
599
600             // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
601             for(int s=0;s<book.getNumberOfSheets();s++) {
602                 Sheet hssfsheet = book.getSheetAt(s);
603                 int col = 0;
604                 // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
605                 for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
606                     Row hssfrow = hssfsheet.getRow(j);
607                     if(hssfrow!=null){
608                         if(j == 0) {
609                             col = hssfrow.getPhysicalNumberOfCells();
610                             if(!header) {
611                                 //不包括表头
612                                 continue;
613                             }
614                         }
615                         // 单行数据
616                         List<String> arrayString = new ArrayList<>();
617                         for (int i = 0; i < col; i++) {
618                             Cell cell = hssfrow.getCell(i);
619                             if (cell == null) {
620                                 arrayString.add("");
621                             } else if (cell.getCellType() == 0) {
622                                 // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
623                                 if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
624                                     short format = cell.getCellStyle().getDataFormat();
625                                     if(format == 14 || format == 31 || format == 57 || format == 58){
626                                         //日期(中文时间格式的)
627                                         Date d = cell.getDateCellValue();
628                                         DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
629                                         // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
630                                         arrayString.add(formater.format(d));
631                                         //arrayString[i] = formater.format(d);
632                                     }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
633                                         Date d = cell.getDateCellValue();
634                                         //DateFormat formater = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
635                                         DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
636                                         arrayString.add(formater.format(d));
637                                         //arrayString[i] = formater.format(d);
638                                     } else {
639                                         if(HSSFCell.CELL_TYPE_STRING == cell.getCellType()){
640                                             arrayString.add(cell.getStringCellValue());
641                                             //arrayString[i] =cell.getStringCellValue();
642                                         }else if(HSSFCell.CELL_TYPE_FORMULA==cell.getCellType()){
643                                             arrayString.add(cell.getCellFormula());
644                                             //arrayString[i] =cell.getCellFormula();
645                                         }else if(HSSFCell.CELL_TYPE_NUMERIC== cell.getCellType()){
646                                             HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
647                                             arrayString.add(dataFormatter.formatCellValue(cell));
648                                             //arrayString[i] =dataFormatter.formatCellValue(cell);
649                                         }
650                                     }
651                                 }
652                             } else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
653                                 arrayString.add("");
654                                 //arrayString[i] = "";
655                             } else { // 如果EXCEL表格中的数据类型为字符串型
656                                 arrayString.add(cell.getStringCellValue().trim());
657                                 //arrayString[i] = cell.getStringCellValue().trim();
658                             }
659                         }
660                         list.add(arrayString);
661                     }
662                 }
663             }
664             return list;
665         } catch (Exception e) {
666             e.printStackTrace();
667         }
668         return null;
669     }
670
671
672
673
674     /**读取excel文件,兼容2003和2007
675      * 通过流读取Excel文件
676      * @return
677      * @throws Exception
678      */
cac339 679     public static List<List<String>> getExcelDataCompatible(MultipartFile file,boolean header) throws Exception {
C 680         try {
681
682             String fileName = file.getOriginalFilename();
683             if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
684                 throw new TipsException("上传文件格式不正确");
685             }
686
687             // 结果集
688             List<List<String>> list = new ArrayList<>();
689             Workbook book = create(new BufferedInputStream(file.getInputStream()));
690
691             // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
692             for(int s=0;s<book.getNumberOfSheets();s++) {
693                 Sheet hssfsheet = book.getSheetAt(s);
694                 int col = 0;
695                 // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
696                 for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
697                     Row hssfrow = hssfsheet.getRow(j);
698                     if(hssfrow!=null){
699                         if(j == 0) {
700                             col = hssfrow.getPhysicalNumberOfCells();
701                             if(!header) {
702                                 //不包括表头
703                                 continue;
704                             }
705                         }
706                         // 单行数据
707                         List<String> arrayString = new ArrayList<>();
708                         for (int i = 0; i < col; i++) {
709                             Cell cell = hssfrow.getCell(i);
710                             if (cell == null) {
711                                 arrayString.add("");
712                             } else if (cell.getCellType() == 0) {
713                                 // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
714                                 if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
715                                     short format = cell.getCellStyle().getDataFormat();
716                                     if(format == 14 || format == 31 || format == 57 || format == 58){
717                                         //日期(中文时间格式的)
718                                         Date d = cell.getDateCellValue();
719                                         DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
720                                         // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
721                                         arrayString.add(formater.format(d));
722                                         //arrayString[i] = formater.format(d);
723                                     }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
724                                         Date d = cell.getDateCellValue();
725                                         //DateFormat formater = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
726                                         DateFormat formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
727                                         arrayString.add(formater.format(d));
728                                         //arrayString[i] = formater.format(d);
729                                     } else {
730                                         if(HSSFCell.CELL_TYPE_STRING == cell.getCellType()){
731                                             arrayString.add(cell.getStringCellValue());
732                                             //arrayString[i] =cell.getStringCellValue();
733                                         }else if(HSSFCell.CELL_TYPE_FORMULA==cell.getCellType()){
734                                             arrayString.add(cell.getCellFormula());
735                                             //arrayString[i] =cell.getCellFormula();
736                                         }else if(HSSFCell.CELL_TYPE_NUMERIC== cell.getCellType()){
737                                             HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
738                                             arrayString.add(dataFormatter.formatCellValue(cell));
739                                             //arrayString[i] =dataFormatter.formatCellValue(cell);
740                                         }
741                                     }
742                                 }
743                             } else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
744                                 arrayString.add("");
745                                 //arrayString[i] = "";
746                             } else { // 如果EXCEL表格中的数据类型为字符串型
747                                 arrayString.add(cell.getStringCellValue().trim());
748                                 //arrayString[i] = cell.getStringCellValue().trim();
749                             }
750                         }
751                         list.add(arrayString);
752                     }
753                 }
754             }
755             return list;
756         } catch (Exception e) {
757             e.printStackTrace();
758         }
759         return null;
760     }
761
762     private static String getCellVal(Cell cell) {
763         if (null == cell) {
764             return "";
765         }
766         switch (cell.getCellType()) {
767             // 数字
768             case HSSFCell.CELL_TYPE_NUMERIC:
769                 // 日期格式的处理
770                 if (HSSFDateUtil.isCellDateFormatted(cell)) {
771                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
772                     return sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
773                 }
774                 return String.valueOf(cell.getNumericCellValue());
775             // 字符串
776             case HSSFCell.CELL_TYPE_STRING:
777                 return cell.getStringCellValue();
778             // 公式
779             case HSSFCell.CELL_TYPE_FORMULA:
780                 return cell.getCellFormula();
781             // 空白
782             case HSSFCell.CELL_TYPE_BLANK:
783                 return "";
784             case HSSFCell.CELL_TYPE_BOOLEAN:
785                 return cell.getBooleanCellValue() + "";
786             // 错误类型
787             case HSSFCell.CELL_TYPE_ERROR:
788                 return cell.getErrorCellValue() + "";
789             default:
790                 break;
791         }
792         return "";
793     }
794
e7c3ff 795     /**
C 796      * p判断是否excel文件
797      * @param file
798      * @return
799      */
800     public static boolean isExcel(MultipartFile file){
801         String fileName = file.getOriginalFilename();
802         if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
803             return false;
804         }
805         return true;
806     }
807
808
6b6bf5 809
W 810
811
812     public static File createExcelByImg(String[] headList, String[] fieldList, List<Map<String, Object>> dataList, Integer height, Integer width) throws Exception {
813         File file = File.createTempFile("temp", ".xls");
814         FileOutputStream fileOut = null;
815         BufferedImage bufferImg = null;
816
817         try {
818             ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
819             if (height == null) {
820                 height = 450;
821             }
822
823             if (width == null) {
824                 width = 1000;
825             }
826
827             HSSFWorkbook workbook = new HSSFWorkbook();
828             HSSFCellStyle boderStyle = workbook.createCellStyle();
829             boderStyle.setVerticalAlignment((short)1);
830             boderStyle.setAlignment((short)2);
831             HSSFSheet sheet = workbook.createSheet();
832             HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
833             HSSFRow row = sheet.createRow(0);
834
835             HSSFCell anchor;
836             for(int i = 0; i < headList.length; ++i) {
837                 row.setHeight(height.shortValue());
838                 sheet.setColumnWidth(i, width);
839                 anchor = row.createCell(i);
840                 anchor.setCellType(1);
841                 anchor.setCellValue(headList[i]);
842                 anchor.setCellStyle(boderStyle);
843             }
844
845             HSSFRow row_value = null;
846             anchor = null;
847             HSSFCell cell = null;
848             if (dataList != null) {
849                 for(int n = 0; n < dataList.size(); ++n) {
850                     row_value = sheet.createRow(n + 1);
851                     row_value.setHeight(height.shortValue());
852                     Map<String, Object> dataMap = (Map)dataList.get(n);
853
854                     for(int i = 0; i < fieldList.length; ++i) {
855                         sheet.setColumnWidth(i, width);
856                         cell = row_value.createCell(i);
857                         cell.setCellType(1);
858                         Object value = dataMap.get(fieldList[i]);
859                         if (value != null && "class java.io.File".equals(value.getClass().toString())) {
860                             File file2 = (File)value;
861                             if (file2 == null) {
862                                 cell.setCellValue("");
863                             } else {
864                                 bufferImg = ImageIO.read(file2);
865                                 ImageIO.write(bufferImg, "jpg", byteArrayOut);
866                                 HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 1023, 255, (short)i, n + 1, (short)i, n + 1);
867                                 anchor1.setAnchorType(0);
868                                 patriarch.createPicture(anchor1, workbook.addPicture(byteArrayOut.toByteArray(), 5));
869                             }
870                         } else {
871                             cell.setCellValue(objToString(dataMap.get(fieldList[i])));
872                             cell.setCellStyle(boderStyle);
873                         }
874                     }
875                 }
876             }
877
878             FileOutputStream fOut = new FileOutputStream(file);
879             workbook.write(fOut);
880             fOut.flush();
881             fOut.close();
882         } catch (Exception var25) {
883             var25.printStackTrace();
884         } finally {
885             file.deleteOnExit();
886         }
887
888         return file;
889     }
cac339 890 }