chenjiahe
2023-09-04 5b623ba0cf530207953c4ec708d6d3706634c139
提交 | 用户 | age
5c5945 1 package com.hx.util;
E 2
5b623b 3 import com.alibaba.fastjson.JSON;
5c5945 4 import com.hx.exception.TipsException;
2e06d1 5 import com.monitorjbl.xlsx.StreamingReader;
5c5945 6 import org.apache.poi.hssf.usermodel.*;
d9e60e 7 import org.apache.poi.ss.usermodel.*;
C 8 import org.apache.poi.xssf.streaming.SXSSFWorkbook;
5b623b 9 import org.apache.poi.xssf.usermodel.XSSFCell;
C 10 import org.apache.poi.xssf.usermodel.XSSFRow;
11 import org.apache.poi.xssf.usermodel.XSSFSheet;
12 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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
7f9b53 61         HSSFCell cell;
C 62         for (int i = 0; i < headList.length; i++) {
5c5945 63             // 在索引0的位置创建单元格(左上端)
7f9b53 64             cell = row.createCell(i);
5c5945 65             // 定义单元格为字符串类型
2e06d1 66             //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
5c5945 67             // 在单元格中输入一些内容
E 68             cell.setCellValue(headList[i]);
69         }
70         // ===============================================================
71         if (dataList != null) {
7f9b53 72             HSSFRow row_value;
C 73             Map<String, Object> dataMap;
5c5945 74             for (int n = 0; n < dataList.size(); n++) {
E 75                 // 在索引1的位置创建行
7f9b53 76                 row_value = sheet.createRow(n + 1);
C 77                 dataMap = dataList.get(n);
5c5945 78                 // ===============================================================
E 79                 for (int i = 0; i < fieldList.length; i++) {
80                     // 在索引0的位置创建单元格(左上端)
7f9b53 81                     cell = row_value.createCell(i);
5c5945 82                     // 定义单元格为字符串类型
2e06d1 83                     //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
5c5945 84                     // 在单元格中输入一些内容
E 85                     cell.setCellValue(objToString(dataMap.get(fieldList[i])));
86                 }
87                 // ===============================================================
88             }
89         }
90
91         // 新建一输出文件流
c6eec8 92         File file = SimpleTool.createFile(outPath, excelName);
5c5945 93         FileOutputStream fOut = new FileOutputStream(file);
E 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
db7fc9 108     /**生成临时文件
C 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,
cac339 118                                    List<Map<String, Object>> dataList) throws Exception {
b4fb02 119         File file = File.createTempFile("temp", ".xlsx");
db7fc9 120         try{
C 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             // ===============================================================
7f9b53 131             HSSFCell cell;
db7fc9 132             for (int i = 0; i < headList.length; i++) {
C 133                 // 在索引0的位置创建单元格(左上端)
7f9b53 134                 cell = row.createCell(i);
db7fc9 135                 // 定义单元格为字符串类型
2e06d1 136                 //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
db7fc9 137                 // 在单元格中输入一些内容
C 138                 cell.setCellValue(headList[i]);
139             }
140             // ===============================================================
141             if (dataList != null) {
7f9b53 142                 HSSFRow row_value;
C 143                 Map<String, Object> dataMap;
db7fc9 144                 for (int n = 0; n < dataList.size(); n++) {
C 145                     // 在索引1的位置创建行
7f9b53 146                     row_value = sheet.createRow(n + 1);
C 147                     dataMap = dataList.get(n);
db7fc9 148                     // ===============================================================
C 149                     for (int i = 0; i < fieldList.length; i++) {
150                         // 在索引0的位置创建单元格(左上端)
7f9b53 151                         cell = row_value.createCell(i);
db7fc9 152                         // 定义单元格为字符串类型
2e06d1 153                         //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
db7fc9 154                         // 在单元格中输入一些内容
C 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
49f28b 176     /**生成临时文件
C 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             //垂直居中
2e06d1 202             boderStyle.setVerticalAlignment(VerticalAlignment.CENTER);
C 203             boderStyle.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
49f28b 204
C 205             // 在Excel工作簿中建一工作表,其名为缺省值
206             // 如要新建一名为"效益指标"的工作表,其语句为:
207             // HSSFSheet sheet = workbook.createSheet("效益指标");
208             HSSFSheet sheet = workbook.createSheet();
209             // 在索引0的位置创建行(最顶端的行)
210             HSSFRow row = sheet.createRow(0);
211             // ===============================================================
7f9b53 212             HSSFCell cell;
49f28b 213             for (int i = 0; i < headList.length; i++) {
C 214                 //高度
215                 row.setHeight(height.shortValue());
216                 sheet.setColumnWidth(i,width);
217                 // 在索引0的位置创建单元格(左上端)
7f9b53 218                 cell = row.createCell(i);
49f28b 219                 // 定义单元格为字符串类型
2e06d1 220                 //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
49f28b 221                 // 在单元格中输入一些内容
C 222                 cell.setCellValue(headList[i]);
223                 cell.setCellStyle(boderStyle);
224             }
225             // ===============================================================
226             if (dataList != null) {
7f9b53 227                 HSSFRow row_value;
C 228                 Map<String, Object> dataMap;
49f28b 229                 for (int n = 0; n < dataList.size(); n++) {
C 230                     // 在索引1的位置创建行
7f9b53 231                     row_value = sheet.createRow(n + 1);
49f28b 232                     row_value.setHeight(height.shortValue());
7f9b53 233                     dataMap = dataList.get(n);
49f28b 234                     // ===============================================================
C 235                     for (int i = 0; i < fieldList.length; i++) {
236                         // 在索引0的位置创建单元格(左上端)
237                         sheet.setColumnWidth(i,width);
7f9b53 238                         cell = row_value.createCell(i);
49f28b 239                         // 定义单元格为字符串类型
2e06d1 240                         //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
49f28b 241                         // 在单元格中输入一些内容
C 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
1b1815 264     /**无限制行数生成ecxel,生成临时文件
C 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 工作簿
d9e60e 287             //XSSFWorkbook workbook = new XSSFWorkbook();
C 288             SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
1b1815 289
C 290             //合并的单元格样式
d9e60e 291             CellStyle boderStyle = workbook.createCellStyle();
1b1815 292             //垂直居中
2e06d1 293             boderStyle.setVerticalAlignment(VerticalAlignment.CENTER);
C 294             boderStyle.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
1b1815 295
C 296             // 在Excel工作簿中建一工作表,其名为缺省值
297             // 如要新建一名为"效益指标"的工作表,其语句为:
298             // HSSFSheet sheet = workbook.createSheet("效益指标");
d9e60e 299             Sheet sheet = workbook.createSheet();
1b1815 300             // 在索引0的位置创建行(最顶端的行)
d9e60e 301             Row row = sheet.createRow(0);
1b1815 302             // ===============================================================
d9e60e 303             Cell cell;
1b1815 304             for (int i = 0; i < headList.length; i++) {
C 305                 //高度
306                 row.setHeight(height.shortValue());
307                 sheet.setColumnWidth(i,width);
308                 // 在索引0的位置创建单元格(左上端)
7f9b53 309                 cell = row.createCell(i);
1b1815 310                 // 定义单元格为字符串类型
2e06d1 311                 //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
1b1815 312                 // 在单元格中输入一些内容
C 313                 cell.setCellValue(headList[i]);
314                 cell.setCellStyle(boderStyle);
315             }
316             // ===============================================================
317             if (dataList != null) {
d9e60e 318                 Row row_value;
7f9b53 319                 Map<String, Object> dataMap;
1b1815 320                 for (int n = 0; n < dataList.size(); n++) {
C 321                     // 在索引1的位置创建行
7f9b53 322                     row_value = sheet.createRow(n + 1);
1b1815 323                     row_value.setHeight(height.shortValue());
7f9b53 324                     dataMap = dataList.get(n);
1b1815 325                     // ===============================================================
C 326                     for (int i = 0; i < fieldList.length; i++) {
327                         // 在索引0的位置创建单元格(左上端)
328                         sheet.setColumnWidth(i,width);
7f9b53 329                         cell = row_value.createCell(i);
1b1815 330                         // 定义单元格为字符串类型
2e06d1 331                         //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
1b1815 332                         // 在单元格中输入一些内容
C 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
db7fc9 355
5c5945 356     private static String objToString(Object obj) {
E 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)
cac339 364                 // obj,DateUtil.DATESTYLE_SHORT_EX);
5c5945 365             } else {
E 366                 return obj.toString();
367             }
368         }
369     }
370
371     /**
c6eec8 372      * 读取Excel数据
F 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     /**
5c5945 396      * 读取 Excel文件内容
E 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("");
2e06d1 436                         } else if (cell.getCellType() == CellType.NUMERIC) {
5c5945 437                             // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
2e06d1 438                             if (CellType.NUMERIC == cell.getCellType()) {
5c5945 439                                 short format = cell.getCellStyle().getDataFormat();
E 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 {
2e06d1 454                                     if(CellType.STRING == cell.getCellType()){
5c5945 455                                         arrayString.add(cell.getStringCellValue());
E 456                                         //arrayString[i] =cell.getStringCellValue();
2e06d1 457                                     }else if(CellType.FORMULA==cell.getCellType()){
5c5945 458                                         arrayString.add(cell.getCellFormula());
E 459                                         //arrayString[i] =cell.getCellFormula();
2e06d1 460                                     }else if(CellType.NUMERIC== cell.getCellType()){
5c5945 461                                         HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
E 462                                         arrayString.add(dataFormatter.formatCellValue(cell));
463                                         //arrayString[i] =dataFormatter.formatCellValue(cell);
464                                     }
465                                 }
466                             }
2e06d1 467                         } else if(cell.getCellType() == CellType.BLANK){
5c5945 468                             arrayString.add("");
E 469                             //arrayString[i] = "";
470                         } else { // 如果EXCEL表格中的数据类型为字符串型
2e06d1 471                             if(cell.getCellType() != CellType.BOOLEAN){
b77bfb 472                                 arrayString.add(cell.getStringCellValue().trim());
F 473                             }else{
474                                 arrayString.add(cell.getBooleanCellValue() ? "TRUE" : "FALSE");
475                             }
5c5945 476                             //arrayString[i] = cell.getStringCellValue().trim();
E 477                         }
478                     }
479                     list.add(arrayString);
480                 }
481             }
482         }
483         return list;
484     }
485
c6eec8 486     /**
F 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("");
2e06d1 527                         } else if (cell.getCellType() == CellType.NUMERIC) {
c6eec8 528                             // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
2e06d1 529                             if (CellType.NUMERIC == cell.getCellType()) {
c6eec8 530                                 short format = cell.getCellStyle().getDataFormat();
F 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 {
2e06d1 545                                     if(CellType.STRING == cell.getCellType()){
c6eec8 546                                         arrayString.add(cell.getStringCellValue());
F 547                                         //arrayString[i] =cell.getStringCellValue();
2e06d1 548                                     }else if(CellType.FORMULA==cell.getCellType()){
c6eec8 549                                         arrayString.add(cell.getCellFormula());
F 550                                         //arrayString[i] =cell.getCellFormula();
2e06d1 551                                     }else if(CellType.NUMERIC== cell.getCellType()){
c6eec8 552                                         HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
F 553                                         arrayString.add(dataFormatter.formatCellValue(cell));
554                                         //arrayString[i] =dataFormatter.formatCellValue(cell);
555                                     }
556                                 }
557                             }
2e06d1 558                         } else if(cell.getCellType() == CellType.BLANK){
c6eec8 559                             arrayString.add("");
F 560                             //arrayString[i] = "";
561                         } else { // 如果EXCEL表格中的数据类型为字符串型
2e06d1 562                             if(cell.getCellType() != CellType.BOOLEAN){
b77bfb 563                                 arrayString.add(cell.getStringCellValue().trim());
F 564                             }else{
565                                 arrayString.add(cell.getBooleanCellValue() ? "TRUE" : "FALSE");
566                             }
567
568
c6eec8 569                             //arrayString[i] = cell.getStringCellValue().trim();
F 570                         }
571                     }
572                     list.add(arrayString);
573                 }
574             }
575         }
576         return list;
577     }
578
cac339 579
C 580     /**判断excel的版本*/
2e06d1 581     public static Workbook create(InputStream inp) throws IOException {
C 582         //这样写  excel 能兼容03和07
583         return WorkbookFactory.create(inp);
cac339 584     }
C 585
586     /**读取excel文件,兼容2003和2007
587      * 通过流读取Excel文件
588      * @return
589      * @throws Exception
590      */
3f4072 591     public static List<List<String>> getExcelDataCompatible(File file,boolean header) throws Exception {
C 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表示工作表的总数
2e06d1 604             Sheet hssfsheet;
C 605             Row hssfrow;
606             List<String> arrayString;
607             Cell cell;
608             short format;
609             Date d;
610             DateFormat formater;
611             HSSFDataFormatter dataFormatter;
3f4072 612             for(int s=0;s<book.getNumberOfSheets();s++) {
2e06d1 613                 hssfsheet = book.getSheetAt(s);
3f4072 614                 int col = 0;
C 615                 // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
616                 for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
2e06d1 617                     hssfrow = hssfsheet.getRow(j);
3f4072 618                     if(hssfrow!=null){
C 619                         if(j == 0) {
620                             col = hssfrow.getPhysicalNumberOfCells();
621                             if(!header) {
622                                 //不包括表头
623                                 continue;
624                             }
625                         }
626                         // 单行数据
2e06d1 627                         arrayString = new ArrayList<>();
3f4072 628                         for (int i = 0; i < col; i++) {
2e06d1 629                             cell = hssfrow.getCell(i);
3f4072 630                             if (cell == null) {
C 631                                 arrayString.add("");
2e06d1 632                             } else if (cell.getCellType() == CellType.NUMERIC) {
3f4072 633                                 // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
2e06d1 634                                 if (CellType.NUMERIC == cell.getCellType()) {
C 635                                     format = cell.getCellStyle().getDataFormat();
3f4072 636                                     if(format == 14 || format == 31 || format == 57 || format == 58){
C 637                                         //日期(中文时间格式的)
2e06d1 638                                          d = cell.getDateCellValue();
C 639                                          formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
3f4072 640                                         // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
C 641                                         arrayString.add(formater.format(d));
642                                         //arrayString[i] = formater.format(d);
643                                     }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
2e06d1 644                                         d = cell.getDateCellValue();
3f4072 645                                         //DateFormat formater = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
2e06d1 646                                         formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
3f4072 647                                         arrayString.add(formater.format(d));
C 648                                         //arrayString[i] = formater.format(d);
649                                     } else {
2e06d1 650                                         if(CellType.STRING == cell.getCellType()){
3f4072 651                                             arrayString.add(cell.getStringCellValue());
C 652                                             //arrayString[i] =cell.getStringCellValue();
2e06d1 653                                         }else if(CellType.FORMULA==cell.getCellType()){
3f4072 654                                             arrayString.add(cell.getCellFormula());
C 655                                             //arrayString[i] =cell.getCellFormula();
2e06d1 656                                         }else if(CellType.NUMERIC== cell.getCellType()){
C 657                                             dataFormatter = new HSSFDataFormatter();
3f4072 658                                             arrayString.add(dataFormatter.formatCellValue(cell));
C 659                                             //arrayString[i] =dataFormatter.formatCellValue(cell);
660                                         }
661                                     }
662                                 }
2e06d1 663                             } else if(cell.getCellType() == CellType.BLANK){
3f4072 664                                 arrayString.add("");
C 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     }
2e06d1 681
3f4072 682
C 683
684
685     /**读取excel文件,兼容2003和2007
686      * 通过流读取Excel文件
687      * @return
688      * @throws Exception
689      */
cac339 690     public static List<List<String>> getExcelDataCompatible(MultipartFile file,boolean header) throws Exception {
C 691         try {
692
693             String fileName = file.getOriginalFilename();
694             if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
695                 throw new TipsException("上传文件格式不正确");
696             }
697
698             // 结果集
699             List<List<String>> list = new ArrayList<>();
700             Workbook book = create(new BufferedInputStream(file.getInputStream()));
701
2e06d1 702             Sheet hssfsheet;
C 703             Row hssfrow;
704             List<String> arrayString;
705             Cell cell;
706             short format;
707             Date d;
708             DateFormat formater;
709             HSSFDataFormatter dataFormatter;
cac339 710             // 遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
2e06d1 711             for(int s=0;s<book.getNumberOfSheets();s++) {
C 712                 hssfsheet = book.getSheetAt(s);
713                 int col = 0;
714                 // 遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数 去除标题
715                 for (int j = 0; j < hssfsheet.getPhysicalNumberOfRows(); j++) {
716                     hssfrow = hssfsheet.getRow(j);
717                     if(hssfrow!=null){
718                         if(j == 0) {
719                             col = hssfrow.getPhysicalNumberOfCells();
720                             if(!header) {
721                                 //不包括表头
722                                 continue;
723                             }
724                         }
725                         // 单行数据
726                         arrayString = new ArrayList<>();
727                         for (int i = 0; i < col; i++) {
728                             cell = hssfrow.getCell(i);
729                             if (cell == null) {
730                                 arrayString.add("");
731                             } else if (cell.getCellType() == CellType.NUMERIC) {
732                                 // arrayString[i] = new Double(cell.getNumericCellValue()).toString();
733                                 if (CellType.NUMERIC == cell.getCellType()) {
734                                     format = cell.getCellStyle().getDataFormat();
735                                     if(format == 14 || format == 31 || format == 57 || format == 58){
736                                         //日期(中文时间格式的)
737                                         d = cell.getDateCellValue();
738                                         formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
739                                         // DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
740                                         arrayString.add(formater.format(d));
741                                         //arrayString[i] = formater.format(d);
742                                     }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
743                                         d = cell.getDateCellValue();
744                                         //DateFormat formater = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
745                                         formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
746                                         arrayString.add(formater.format(d));
747                                         //arrayString[i] = formater.format(d);
748                                     } else {
749                                         if(CellType.STRING == cell.getCellType()){
750                                             arrayString.add(cell.getStringCellValue());
751                                             //arrayString[i] =cell.getStringCellValue();
752                                         }else if(CellType.FORMULA==cell.getCellType()){
753                                             arrayString.add(cell.getCellFormula());
754                                             //arrayString[i] =cell.getCellFormula();
755                                         }else if(CellType.NUMERIC== cell.getCellType()){
756                                             dataFormatter = new HSSFDataFormatter();
757                                             arrayString.add(dataFormatter.formatCellValue(cell));
758                                             //arrayString[i] =dataFormatter.formatCellValue(cell);
759                                         }
760                                     }
761                                 }
762                             } else if(cell.getCellType() == CellType.BLANK){
763                                 arrayString.add("");
764                                 //arrayString[i] = "";
765                             } else { // 如果EXCEL表格中的数据类型为字符串型
766                                 arrayString.add(cell.getStringCellValue().trim());
767                                 //arrayString[i] = cell.getStringCellValue().trim();
768                             }
769                         }
770                         list.add(arrayString);
771                     }
772                 }
773             }
774             return list;
775         } catch (Exception e) {
776             e.printStackTrace();
777         }
778         return null;
779     }
780
5b623b 781
C 782     /**
783      * 新版读取Excel,只支持2007以上版本,也就是xslx格式
784      * @param file 文件
785      * @return 数据
2e06d1 786      */
5b623b 787     public static List<List<String>> readExcelData(File file){
C 788         if(!isExcel(file)){
789             throw new TipsException("请上传excel的文件格式!");
790         }
791         List<List<String>> listData = new ArrayList<>();
792         try{
793             //rowCacheSize 缓存到内存中的行数(默认是10)
794             //bufferSize 读取资源时,缓存到内存的字节大小(默认是1024)
795             //open InputStream或者XLSX格式的File(必须)
796             Workbook book = StreamingReader.builder()
797                     .rowCacheSize(100)
798                     .bufferSize(4096)
799                     .open(new FileInputStream(file));
2e06d1 800
5b623b 801             //是否存在数据
C 802             boolean isData;
803             List<String> arrayString;
804             short format;
805             Date d;
806             DateFormat formater;
807             Sheet sheet;
808             //遍历所有的sheet
809             for(int i=0;i<book.getNumberOfSheets();i++){
810                 sheet = book.getSheetAt(i);
811                 //遍历所有的行
812                 for (Row row : sheet) {
813                     isData = false;
814                     arrayString = new ArrayList<>();
815                     //遍历所有的列
816                     for (Cell cell : row) {
817                         if (cell == null) {
818                             arrayString.add("");
819                         } else if (cell.getCellType() == CellType.NUMERIC) {
820                             isData = true;
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                                 arrayString.add(formater.format(d));
827                             }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
828                                 d = cell.getDateCellValue();
829                                 formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
830                                 arrayString.add(formater.format(d));
831                             } else {
832                                 if(CellType.STRING == cell.getCellType()){
833                                     arrayString.add(cell.getStringCellValue());
834                                 }else if(CellType.FORMULA==cell.getCellType()){
835                                     arrayString.add(cell.getCellFormula());
836                                 }else{
837                                     arrayString.add(cell.getStringCellValue().trim());
cac339 838                                 }
C 839                             }
5b623b 840                         } else if(cell.getCellType() == CellType.BLANK){
C 841                             arrayString.add("");
842                         } else { // 如果EXCEL表格中的数据类型为字符串型
843                             isData = true;
844                             arrayString.add(cell.getStringCellValue().trim());
cac339 845                         }
5b623b 846                     }
C 847                     if(isData){
848                         listData.add(arrayString);
d57fc1 849                     }
F 850                 }
851             }
5b623b 852         }catch (Exception e){
d57fc1 853             e.printStackTrace();
5b623b 854             throw new RuntimeException(e.getMessage());
d57fc1 855         }
5b623b 856         return listData;
d57fc1 857     }
F 858
5b623b 859     /**
C 860      * 新版读取Excel,只支持2007以上版本,也就是xslx格式
861      * @param file 文件
862      * @return 数据
2e06d1 863      */
5b623b 864     public static List<List<String>> readExcelData(MultipartFile file){
C 865         if(!isExcel(file)){
866             throw new TipsException("请上传excel的文件格式!");
867         }
868         List<List<String>> listData = new ArrayList<>();
869         try{
870             //rowCacheSize 缓存到内存中的行数(默认是10)
871             //bufferSize 读取资源时,缓存到内存的字节大小(默认是1024)
872             //open InputStream或者XLSX格式的File(必须)
873             Workbook book = StreamingReader.builder()
874                     .rowCacheSize(100)
875                     .bufferSize(4096)
876                     .open(new BufferedInputStream(file.getInputStream()));
2e06d1 877
5b623b 878             //是否存在数据
C 879             boolean isData;
880             List<String> arrayString;
881             short format;
882             Date d;
883             DateFormat formater;
884             Sheet sheet;
885             //遍历所有的sheet
886             for(int i=0;i<book.getNumberOfSheets();i++){
887                 sheet = book.getSheetAt(i);
888                 //遍历所有的行
889                 for (Row row : sheet) {
890                     isData = false;
891                     arrayString = new ArrayList<>();
892                     //遍历所有的列
893                     for (Cell cell : row) {
894                         if (cell == null) {
895                             arrayString.add("");
896                         } else if (cell.getCellType() == CellType.NUMERIC) {
897                             isData = true;
898                             format = cell.getCellStyle().getDataFormat();
899                             if(format == 14 || format == 31 || format == 57 || format == 58){
900                                 //日期(中文时间格式的)
901                                 d = cell.getDateCellValue();
902                                 formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
903                                 arrayString.add(formater.format(d));
904                             }else if (HSSFDateUtil.isCellDateFormatted(cell)) {
905                                 d = cell.getDateCellValue();
906                                 formater = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
907                                 arrayString.add(formater.format(d));
908                             } else {
909                                 if(CellType.STRING == cell.getCellType()){
910                                     arrayString.add(cell.getStringCellValue());
911                                 }else if(CellType.FORMULA==cell.getCellType()){
912                                     arrayString.add(cell.getCellFormula());
913                                 }else{
914                                     arrayString.add(cell.getStringCellValue().trim());
2e06d1 915                                 }
C 916                             }
5b623b 917                         } else if(cell.getCellType() == CellType.BLANK){
C 918                             arrayString.add("");
919                         } else { // 如果EXCEL表格中的数据类型为字符串型
920                             isData = true;
921                             arrayString.add(cell.getStringCellValue().trim());
2e06d1 922                         }
5b623b 923                     }
C 924                     if(isData){
925                         listData.add(arrayString);
2e06d1 926                     }
C 927                 }
928             }
5b623b 929         }catch (Exception e){
2e06d1 930             e.printStackTrace();
5b623b 931             throw new RuntimeException(e.getMessage());
2e06d1 932         }
5b623b 933         return listData;
2e06d1 934     }
C 935
cac339 936
e7c3ff 937     /**
C 938      * p判断是否excel文件
939      * @param file
940      * @return
941      */
942     public static boolean isExcel(MultipartFile file){
5b623b 943         return isExcel(file.getOriginalFilename());
C 944     }
945
946
947     /**
948      * p判断是否excel文件
949      * @param file
950      * @return
951      */
952     public static boolean isExcel(File file){
953         return isExcel(file.getName());
954     }
955
956
957     /**判断文件格式是不是excel*/
958     public static boolean isExcel(String fileName){
e7c3ff 959         if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
C 960             return false;
961         }
962         return true;
963     }
6b6bf5 964
W 965     public static File createExcelByImg(String[] headList, String[] fieldList, List<Map<String, Object>> dataList, Integer height, Integer width) throws Exception {
966         File file = File.createTempFile("temp", ".xls");
967         FileOutputStream fileOut = null;
968         BufferedImage bufferImg = null;
969
970         try {
971             ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
972             if (height == null) {
973                 height = 450;
974             }
975
976             if (width == null) {
977                 width = 1000;
978             }
979
980             HSSFWorkbook workbook = new HSSFWorkbook();
981             HSSFCellStyle boderStyle = workbook.createCellStyle();
2e06d1 982             boderStyle.setVerticalAlignment(VerticalAlignment.CENTER);
C 983             boderStyle.setAlignment(HorizontalAlignment.CENTER);
6b6bf5 984             HSSFSheet sheet = workbook.createSheet();
W 985             HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
986             HSSFRow row = sheet.createRow(0);
987
988             HSSFCell anchor;
989             for(int i = 0; i < headList.length; ++i) {
990                 row.setHeight(height.shortValue());
991                 sheet.setColumnWidth(i, width);
992                 anchor = row.createCell(i);
993                 anchor.setCellValue(headList[i]);
994                 anchor.setCellStyle(boderStyle);
995             }
996
997             HSSFRow row_value = null;
998             anchor = null;
999             HSSFCell cell = null;
1000             if (dataList != null) {
1001                 for(int n = 0; n < dataList.size(); ++n) {
1002                     row_value = sheet.createRow(n + 1);
1003                     row_value.setHeight(height.shortValue());
1004                     Map<String, Object> dataMap = (Map)dataList.get(n);
1005
1006                     for(int i = 0; i < fieldList.length; ++i) {
1007                         sheet.setColumnWidth(i, width);
1008                         cell = row_value.createCell(i);
1009                         Object value = dataMap.get(fieldList[i]);
1010                         if (value != null && "class java.io.File".equals(value.getClass().toString())) {
1011                             File file2 = (File)value;
1012                             if (file2 == null) {
1013                                 cell.setCellValue("");
1014                             } else {
1015                                 bufferImg = ImageIO.read(file2);
1016                                 ImageIO.write(bufferImg, "jpg", byteArrayOut);
1017                                 HSSFClientAnchor anchor1 = new HSSFClientAnchor(0, 0, 1023, 255, (short)i, n + 1, (short)i, n + 1);
2e06d1 1018                                 anchor1.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
6b6bf5 1019                                 patriarch.createPicture(anchor1, workbook.addPicture(byteArrayOut.toByteArray(), 5));
W 1020                             }
1021                         } else {
1022                             cell.setCellValue(objToString(dataMap.get(fieldList[i])));
1023                             cell.setCellStyle(boderStyle);
1024                         }
1025                     }
1026                 }
1027             }
1028
1029             FileOutputStream fOut = new FileOutputStream(file);
1030             workbook.write(fOut);
1031             fOut.flush();
1032             fOut.close();
1033         } catch (Exception var25) {
1034             var25.printStackTrace();
1035         } finally {
1036             file.deleteOnExit();
1037         }
1038
1039         return file;
2e06d1 1040     }
C 1041
cac339 1042 }