1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
| import cn.afterturn.easypoi.entity.BaseTypeConstants; import cn.afterturn.easypoi.excel.annotation.ExcelTarget; import cn.afterturn.easypoi.excel.entity.ImportParams; import cn.afterturn.easypoi.excel.entity.params.ExcelCollectionParams; import cn.afterturn.easypoi.excel.entity.params.ExcelImportEntity; import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult; import cn.afterturn.easypoi.excel.entity.result.ExcelVerifyHandlerResult; import cn.afterturn.easypoi.excel.imports.ExcelImportService; import cn.afterturn.easypoi.excel.imports.recursive.ExcelImportForkJoinWork; import cn.afterturn.easypoi.exception.excel.ExcelImportException; import cn.afterturn.easypoi.exception.excel.enums.ExcelImportEnum; import cn.afterturn.easypoi.handler.inter.IExcelDataHandler; import cn.afterturn.easypoi.handler.inter.IExcelDataModel; import cn.afterturn.easypoi.handler.inter.IExcelDictHandler; import cn.afterturn.easypoi.handler.inter.IExcelModel; import cn.afterturn.easypoi.util.PoiPublicUtil; import cn.afterturn.easypoi.util.PoiReflectorUtil; import cn.afterturn.easypoi.util.PoiValidationUtil; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.time.DateUtils; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.formula.functions.T; import org.apache.poi.ss.usermodel.*; import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.math.BigDecimal; import java.sql.Time; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.ZoneId; import java.util.*; import java.util.concurrent.ForkJoinPool;
public class ExcelImportServiceImok extends ExcelImportService { private static final Logger LOGGER = LoggerFactory.getLogger(ExcelImportServiceImok.class); private List<String> handlerList = null;
private boolean verifyFail = false;
private CellStyle errorCellStyle;
private List<Row> successRow; private List<Row> failRow; private List failCollection;
public ExcelImportServiceImok() { successRow = new ArrayList<>(); failRow = new ArrayList<>(); failCollection = new ArrayList(); }
public void addListContinues(Object object, ExcelCollectionParams param, Row row, Map<Integer, String> titlemap, String targetId, Map<String, PictureData> pictures, ImportParams params, StringBuilder errorMsg) throws Exception { Collection collection = (Collection) PoiReflectorUtil.fromCache(object.getClass()) .getValue(object, param.getName()); Object entity = PoiPublicUtil.createObject(param.getType(), targetId); if (entity instanceof IExcelDataModel) { ((IExcelDataModel) entity).setRowNum(row.getRowNum()); } String picId; boolean isUsed = false; for (int i = row.getFirstCellNum(); i < titlemap.size(); i++) { Cell cell = row.getCell(i); String titleString = titlemap.get(i); if (param.getExcelParams().containsKey(titleString)) { if (param.getExcelParams().get(titleString).getType() == BaseTypeConstants.IMAGE_TYPE) { picId = row.getRowNum() + "_" + i; saveImage(entity, picId, param.getExcelParams(), titleString, pictures, params); } else { try { saveFieldValues(params, entity, cell, param.getExcelParams(), titleString, row); } catch (ExcelImportException e) { if (params.isNeedVerify() && ExcelImportEnum.GET_VALUE_ERROR.equals(e.getType())) { errorMsg.append(" ").append(titleString).append(ExcelImportEnum.GET_VALUE_ERROR.getMsg()); } } } isUsed = true; } } if (isUsed) { collection.add(entity); } }
private String getKeyValue(Cell cell) { Object obj = PoiCellUtils.getCellValue(cell); return obj == null ? null : obj.toString().trim(); }
private String getSaveUrl(ExcelImportEntity excelImportEntity, Object object) throws Exception { if (ExcelImportEntity.IMG_SAVE_PATH.equals(excelImportEntity.getSaveUrl())) { if (excelImportEntity.getMethods() != null && excelImportEntity.getMethods().size() > 0) { object = getFieldBySomeMethod(excelImportEntity.getMethods(), object); } String url = object.getClass().getName() .split("\\.")[object.getClass().getName().split("\\.").length - 1]; return excelImportEntity.getSaveUrl() + File.separator + url; } return excelImportEntity.getSaveUrl(); }
private <T> List<T> importExcel(Collection<T> result, Sheet sheet, Class<?> pojoClass, ImportParams params, Map<String, PictureData> pictures) throws Exception { List collection = new ArrayList(); Map<String, ExcelImportEntity> excelParams = new HashMap<>(); List<ExcelCollectionParams> excelCollection = new ArrayList<>(); String targetId = null; i18nHandler = params.getI18nHandler(); boolean isMap = Map.class.equals(pojoClass); if (!isMap) { Field[] fileds = PoiPublicUtil.getClassFields(pojoClass); ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class); if (etarget != null) { targetId = etarget.value(); } getAllExcelField(targetId, fileds, excelParams, excelCollection, pojoClass, null, null); } Iterator<Row> rows = sheet.rowIterator(); for (int j = 0; j < params.getTitleRows(); j++) { rows.next(); } Map<Integer, String> titlemap = getTitleMap(rows, params, excelCollection, excelParams); checkIsValidTemplate(titlemap, excelParams, params, excelCollection); Object object = null; String picId; int readRow = 1; for (int i = 0; i < params.getStartRows(); i++) { rows.next(); } if (excelCollection.size() > 0 && params.getKeyIndex() == null) { params.setKeyIndex(0); } int endRow = sheet.getLastRowNum() - params.getLastOfInvalidRow(); if (params.getReadRows() > 0) { endRow = Math.min(params.getReadRows(), endRow); } if (params.isConcurrentTask()) { ForkJoinPool forkJoinPool = new ForkJoinPool(); ExcelImportForkJoinWork task = new ExcelImportForkJoinWork(params.getStartRows() + params.getHeadRows() + params.getTitleRows(), endRow, sheet, params, pojoClass, this, targetId, titlemap, excelParams); ExcelImportResult forkJoinResult = forkJoinPool.invoke(task); collection = forkJoinResult.getList(); failCollection = forkJoinResult.getFailList(); } else { StringBuilder errorMsg; while (rows.hasNext()) { Row row = rows.next(); if (row.getRowNum() > endRow) { break; } if (row.getLastCellNum() < 0) { continue; } if (isMap && object != null) { ((Map) object).put("excelRowNum", row.getRowNum()); } errorMsg = new StringBuilder(); if (params.getKeyIndex() != null && (row.getCell(params.getKeyIndex()) == null || StringUtils.isEmpty(getKeyValue(row.getCell(params.getKeyIndex())))) && object != null) { for (ExcelCollectionParams param : excelCollection) { addListContinues(object, param, row, titlemap, targetId, pictures, params, errorMsg); } } else { object = PoiPublicUtil.createObject(pojoClass, targetId); try { Set<Integer> keys = titlemap.keySet(); for (Integer cn : keys) { Cell cell = row.getCell(cn); String titleString = titlemap.get(cn); if (excelParams.containsKey(titleString) || isMap) { if (excelParams.get(titleString) != null && excelParams.get(titleString).getType() == BaseTypeConstants.IMAGE_TYPE) { picId = row.getRowNum() + "_" + cn; saveImage(object, picId, excelParams, titleString, pictures, params); } else { try { saveFieldValues(params, object, cell, excelParams, titleString, row); } catch (ExcelImportException e) { if (params.isNeedVerify() && ExcelImportEnum.GET_VALUE_ERROR.equals(e.getType())) { errorMsg.append(" ").append(titleString).append(ExcelImportEnum.GET_VALUE_ERROR.getMsg()); } } } } }
if (object instanceof IExcelDataModel) { ((IExcelDataModel) object).setRowNum(row.getRowNum()); } for (ExcelCollectionParams param : excelCollection) { addListContinues(object, param, row, titlemap, targetId, pictures, params, errorMsg); } if (verifyingDataValiditys(object, row, params, isMap, errorMsg)) { collection.add(object); } else { failCollection.add(object); } } catch (ExcelImportException e) { LOGGER.error("excel import error , row num:{},obj:{}", readRow, ReflectionToStringBuilder.toString(object)); if (!e.getType().equals(ExcelImportEnum.VERIFY_ERROR)) { throw new ExcelImportException(e.getType(), e); } } catch (Exception e) { LOGGER.error("excel import error , row num:{},obj:{}", readRow, ReflectionToStringBuilder.toString(object)); throw new RuntimeException(e); } } readRow++; } } return collection; }
public boolean verifyingDataValiditys(Object object, Row row, ImportParams params, boolean isMap, StringBuilder fieldErrorMsg) { boolean isAdd = true; Cell cell = null; if (params.isNeedVerify()) { String errorMsg = PoiValidationUtil.validation(object, params.getVerifyGroup()); if (StringUtils.isNotEmpty(errorMsg)) { cell = row.createCell(row.getLastCellNum()); cell.setCellValue(errorMsg); if (object instanceof IExcelModel) { IExcelModel model = (IExcelModel) object; model.setErrorMsg(errorMsg); } isAdd = false; verifyFail = true; } } if (params.getVerifyHandler() != null) { ExcelVerifyHandlerResult result = params.getVerifyHandler().verifyHandler(object); if (!result.isSuccess()) { if (cell == null) { cell = row.createCell(row.getLastCellNum()); } cell.setCellValue((StringUtils.isNoneBlank(cell.getStringCellValue()) ? cell.getStringCellValue() + "," : "") + result.getMsg()); if (object instanceof IExcelModel) { IExcelModel model = (IExcelModel) object; model.setErrorMsg((StringUtils.isNoneBlank(model.getErrorMsg()) ? model.getErrorMsg() + "," : "") + result.getMsg()); } isAdd = false; verifyFail = true; } } if ((params.isNeedVerify() || params.getVerifyHandler() != null) && fieldErrorMsg.length() > 0) { if (object instanceof IExcelModel) { IExcelModel model = (IExcelModel) object; model.setErrorMsg((StringUtils.isNoneBlank(model.getErrorMsg()) ? model.getErrorMsg() + "," : "") + fieldErrorMsg.toString()); } if (cell == null) { cell = row.createCell(row.getLastCellNum()); } cell.setCellValue((StringUtils.isNoneBlank(cell.getStringCellValue()) ? cell.getStringCellValue() + "," : "") + fieldErrorMsg.toString()); isAdd = false; verifyFail = true; } if (cell != null) { cell.setCellStyle(errorCellStyle); failRow.add(row); if (isMap) { ((Map) object).put("excelErrorMsg", cell.getStringCellValue()); } } else { successRow.add(row); } return isAdd; }
private Map<Integer, String> getTitleMap(Iterator<Row> rows, ImportParams params, List<ExcelCollectionParams> excelCollection, Map<String, ExcelImportEntity> excelParams) { Map<Integer, String> titlemap = new LinkedHashMap<>(); Iterator<Cell> cellTitle; String collectionName = null; ExcelCollectionParams collectionParams = null; Row row = null; for (int j = 0; j < params.getHeadRows(); j++) { row = rows.next(); if (row == null) { continue; } cellTitle = row.cellIterator(); while (cellTitle.hasNext()) { Cell cell = cellTitle.next(); String value = getKeyValue(cell); value = value.replace("\n", ""); int i = cell.getColumnIndex(); if (StringUtils.isNotEmpty(value)) { if (titlemap.containsKey(i)) { collectionName = titlemap.get(i); collectionParams = getCollectionParams(excelCollection, collectionName); titlemap.put(i, collectionName + "_" + value); } else if (StringUtils.isNotEmpty(collectionName) && collectionParams != null && collectionParams.getExcelParams() .containsKey(collectionName + "_" + value)) { titlemap.put(i, collectionName + "_" + value); } else { collectionName = null; collectionParams = null; } if (StringUtils.isEmpty(collectionName)) { titlemap.put(i, value); } } } }
Set<String> keys = excelParams.keySet(); for (String key : keys) { if (key.startsWith("FIXED_")) { String[] arr = key.split("_"); titlemap.put(Integer.parseInt(arr[1]), key); } } return titlemap; }
private ExcelCollectionParams getCollectionParams(List<ExcelCollectionParams> excelCollection, String collectionName) { for (ExcelCollectionParams excelCollectionParams : excelCollection) { if (collectionName.equals(excelCollectionParams.getExcelName())) { return excelCollectionParams; } } return null; }
public ExcelImportResult importExcelByIss(InputStream inputstream, Class<?> pojoClass, ImportParams params, boolean needMore) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excel import start ,class is {}", pojoClass); } List<T> result = new ArrayList<>(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ExcelImportResult importResult; try { byte[] buffer = new byte[1024]; int len; while ((len = inputstream.read(buffer)) > -1) { baos.write(buffer, 0, len); } baos.flush();
InputStream userIs = new ByteArrayInputStream(baos.toByteArray()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excel clone success"); } Workbook book = WorkbookFactory.create(userIs);
boolean isXSSFWorkbook = !(book instanceof HSSFWorkbook); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Workbook create success"); } importResult = new ExcelImportResult(); createErrorCellStyle(book); Map<String, PictureData> pictures; for (int i = params.getStartSheetIndex(); i < params.getStartSheetIndex() + params.getSheetNum(); i++) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(" start to read excel by is ,startTime is {}", new Date()); } if (isXSSFWorkbook) { pictures = PoiPublicUtil.getSheetPictrues07((XSSFSheet) book.getSheetAt(i), (XSSFWorkbook) book); } else { pictures = PoiPublicUtil.getSheetPictrues03((HSSFSheet) book.getSheetAt(i), (HSSFWorkbook) book); } if (LOGGER.isDebugEnabled()) { LOGGER.debug(" end to read excel by is ,endTime is {}", new Date()); } result.addAll(importExcel(result, book.getSheetAt(i), pojoClass, params, pictures)); if (LOGGER.isDebugEnabled()) { LOGGER.debug(" end to read excel list by sheet ,endTime is {}", new Date()); } if (params.isReadSingleCell()) { readSingleCell(importResult, book.getSheetAt(i), params); if (LOGGER.isDebugEnabled()) { LOGGER.debug(" read Key-Value ,endTime is {}", System.currentTimeMillis()); } } } if (params.isNeedSave()) { saveThisExcel(params, pojoClass, isXSSFWorkbook, book); } importResult.setList(result); if (needMore) { InputStream successIs = new ByteArrayInputStream(baos.toByteArray()); try { Workbook successBook = WorkbookFactory.create(successIs); if (params.isVerifyFileSplit()) { importResult.setWorkbook(removeSuperfluousRows(successBook, failRow, params)); importResult.setFailWorkbook(removeSuperfluousRows(book, successRow, params)); } else { importResult.setWorkbook(book); } importResult.setFailList(failCollection); importResult.setVerifyFail(verifyFail); } finally { successIs.close(); } } } finally { IOUtils.closeQuietly(baos); }
return importResult; }
private Workbook removeSuperfluousRows(Workbook book, List<Row> rowList, ImportParams params) { for (int i = params.getStartSheetIndex(); i < params.getStartSheetIndex() + params.getSheetNum(); i++) { for (int j = rowList.size() - 1; j >= 0; j--) { if (rowList.get(j).getRowNum() < rowList.get(j).getSheet().getLastRowNum()) { book.getSheetAt(i).shiftRows(rowList.get(j).getRowNum() + 1, rowList.get(j).getSheet().getLastRowNum(), -1); } else if (rowList.get(j).getRowNum() == rowList.get(j).getSheet().getLastRowNum()) { book.getSheetAt(i).createRow(rowList.get(j).getRowNum() + 1); book.getSheetAt(i).shiftRows(rowList.get(j).getRowNum() + 1, rowList.get(j).getSheet().getLastRowNum() + 1, -1); } } } return book; }
private void readSingleCell(ExcelImportResult result, Sheet sheet, ImportParams params) { if (result.getMap() == null) { result.setMap(new HashMap<String, Object>()); } for (int i = 0; i < params.getTitleRows() + params.getHeadRows() + params.getStartRows(); i++) { getSingleCellValueForRow(result, sheet.getRow(i), params); }
for (int i = sheet.getLastRowNum() - params.getLastOfInvalidRow(); i < sheet.getLastRowNum(); i++) { getSingleCellValueForRow(result, sheet.getRow(i), params);
} }
private void getSingleCellValueForRow(ExcelImportResult result, Row row, ImportParams params) { for (int j = row.getFirstCellNum(), le = row.getLastCellNum(); j < le; j++) { String text = PoiCellUtils.getCellValue(row.getCell(j)); if (StringUtils.isNoneBlank(text) && text.endsWith(params.getKeyMark())) { if (result.getMap().containsKey(text)) { if (result.getMap().get(text) instanceof String) { List<String> list = new ArrayList<>(); list.add((String) result.getMap().get(text)); result.getMap().put(text, list); } ((List) result.getMap().get(text)).add(PoiCellUtils.getCellValue(row.getCell(++j))); } else { result.getMap().put(text, PoiCellUtils.getCellValue(row.getCell(++j))); }
}
} }
private void checkIsValidTemplate(Map<Integer, String> titlemap, Map<String, ExcelImportEntity> excelParams, ImportParams params, List<ExcelCollectionParams> excelCollection) {
if (params.getImportFields() != null) { if (params.isNeedCheckOrder()) {
if (params.getImportFields().length != titlemap.size()) { LOGGER.error("excel列顺序不一致"); throw new ExcelImportException(ExcelImportEnum.IS_NOT_A_VALID_TEMPLATE); } int i = 0; for (String title : titlemap.values()) { if (!StringUtils.equals(title, params.getImportFields()[i++])) { LOGGER.error("excel列顺序不一致"); throw new ExcelImportException(ExcelImportEnum.IS_NOT_A_VALID_TEMPLATE); } } } else { for (int i = 0, le = params.getImportFields().length; i < le; i++) { if (!titlemap.containsValue(params.getImportFields()[i])) { throw new ExcelImportException(ExcelImportEnum.IS_NOT_A_VALID_TEMPLATE); } } } } else { Collection<ExcelImportEntity> collection = excelParams.values(); for (ExcelImportEntity excelImportEntity : collection) { if (excelImportEntity.isImportField() && !titlemap.containsValue(excelImportEntity.getName())) { LOGGER.error(excelImportEntity.getName() + "必须有,但是没找到"); throw new ExcelImportException(ExcelImportEnum.IS_NOT_A_VALID_TEMPLATE); } }
for (int i = 0, le = excelCollection.size(); i < le; i++) { ExcelCollectionParams collectionparams = excelCollection.get(i); collection = collectionparams.getExcelParams().values(); for (ExcelImportEntity excelImportEntity : collection) { if (excelImportEntity.isImportField() && !titlemap.containsValue( collectionparams.getExcelName() + "_" + excelImportEntity.getName())) { throw new ExcelImportException(ExcelImportEnum.IS_NOT_A_VALID_TEMPLATE); } } } } }
public void saveFieldValues(ImportParams params, Object object, Cell cell, Map<String, ExcelImportEntity> excelParams, String titleString, Row row) throws Exception { Object value = getValues(params.getDataHandler(), object, cell, excelParams, titleString, params.getDictHandler()); if (object instanceof Map) { if (params.getDataHandler() != null) { params.getDataHandler().setMapValue((Map) object, titleString, value); } else { ((Map) object).put(titleString, value); } } else { setValues(excelParams.get(titleString), object, value); } }
public Object getValues(IExcelDataHandler<?> dataHandler, Object object, Object cell, Map<String, ExcelImportEntity> excelParams, String titleString, IExcelDictHandler dictHandler) throws Exception {
ExcelImportEntity entity = excelParams.get(titleString); String classFullName = "class java.lang.Object"; Class clazz = null; if (!(object instanceof Map)) { Method setMethod = entity.getMethods() != null && entity.getMethods().size() > 0 ? entity.getMethods().get(entity.getMethods().size() - 1) : entity.getMethod(); Type[] ts = setMethod.getGenericParameterTypes(); classFullName = ts[0].toString(); clazz = (Class) ts[0]; } Object result = null; if (cell instanceof Cell) { result = getCellValues(classFullName, (Cell) cell, entity); } else { result = cell; } if (entity != null) { result = handlerSuffix(entity.getSuffix(), result); result = replaceValue(entity.getReplace(), result); result = replaceValue(entity.getReplace(), result); if (dictHandler != null && StringUtils.isNoneBlank(entity.getDict())) { result = dictHandler.toValue(entity.getDict(), object, entity.getName(), result); } } result = handlerValue(dataHandler, object, result, titleString); return getValueByType(classFullName, result, entity, clazz); }
private Object getValueByType(String classFullName, Object result, ExcelImportEntity entity, Class clazz) { try { if (result == null || StringUtils.isBlank(result.toString())) { return null; } if ("class java.util.Date".equals(classFullName) && result instanceof String) { return DateUtils.parseDate(result.toString(), entity.getFormat()); } if ("class java.lang.Boolean".equals(classFullName) || "boolean".equals(classFullName)) { return Boolean.valueOf(String.valueOf(result)); } if ("class java.lang.Double".equals(classFullName) || "double".equals(classFullName)) { return Double.valueOf(String.valueOf(result)); } if ("class java.lang.Long".equals(classFullName) || "long".equals(classFullName)) { try { return Long.valueOf(String.valueOf(result)); } catch (Exception e) { return Double.valueOf(String.valueOf(result)).longValue(); } } if ("class java.lang.Float".equals(classFullName) || "float".equals(classFullName)) { return Float.valueOf(String.valueOf(result)); } if ("class java.lang.Integer".equals(classFullName) || "int".equals(classFullName)) { try { return Integer.valueOf(String.valueOf(result)); } catch (Exception e) { return Double.valueOf(String.valueOf(result)).intValue(); } } if ("class java.math.BigDecimal".equals(classFullName)) { return new BigDecimal(String.valueOf(result)); } if ("class java.lang.String".equals(classFullName)) { if (result instanceof String) { return result; } if (result instanceof Double) { return PoiPublicUtil.doubleToString((Double) result); } return String.valueOf(result); } if (clazz != null && clazz.isEnum()) { if (StringUtils.isNotEmpty(entity.getEnumImportMethod())) { return PoiReflectorUtil.fromCache(clazz).execEnumStaticMethod(entity.getEnumImportMethod(), result); } else { return Enum.valueOf(clazz, result.toString()); } } return result; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new ExcelImportException(ExcelImportEnum.GET_VALUE_ERROR); } }
private Object handlerValue(IExcelDataHandler dataHandler, Object object, Object result, String titleString) { if (dataHandler == null || dataHandler.getNeedHandlerFields() == null || dataHandler.getNeedHandlerFields().length == 0) { return result; } if (handlerList == null) { handlerList = Arrays.asList(dataHandler.getNeedHandlerFields()); } if (handlerList.contains(titleString)) { return dataHandler.importHandler(object, titleString, result); } return result; }
private Object handlerSuffix(String suffix, Object result) { if (StringUtils.isNotEmpty(suffix) && result != null && result.toString().endsWith(suffix)) { String temp = result.toString(); return temp.substring(0, temp.length() - suffix.length()); } return result; }
private Object replaceValue(String[] replace, Object result) { if (replace != null && replace.length > 0) { String temp = String.valueOf(result); String[] tempArr; for (int i = 0; i < replace.length; i++) { tempArr = replace[i].split("_"); if (temp.equals(tempArr[0])) { return tempArr[1]; } } } return result; }
private Object getCellValues(String classFullName, Cell cell, ExcelImportEntity entity) { if (cell == null) { return ""; } Object result = null; if ("class java.util.Date".equals(classFullName) || "class java.sql.Date".equals(classFullName) || ("class java.sql.Time").equals(classFullName) || ("class java.time.Instant").equals(classFullName) || ("class java.time.LocalDate").equals(classFullName) || ("class java.time.LocalDateTime").equals(classFullName) || ("class java.sql.Timestamp").equals(classFullName)) { if (CellType.NUMERIC == cell.getCellTypeEnum() && DateUtil.isCellDateFormatted(cell)) { result = DateUtil.getJavaDate(cell.getNumericCellValue()); } else { String val = ""; try { val = cell.getStringCellValue(); } catch (Exception e) { return null; }
result = getDateData(entity, val); if (result == null) { return null; } } if (("class java.time.Instant").equals(classFullName)) { result = ((Date) result).toInstant(); } else if (("class java.time.LocalDate").equals(classFullName)) { result = ((Date) result).toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); } else if (("class java.time.LocalDateTime").equals(classFullName)) { result = ((Date) result).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); } else if (("class java.time.OffsetDateTime").equals(classFullName)) { result = ((Date) result).toInstant().atZone(ZoneId.systemDefault()).toOffsetDateTime(); } else if (("class java.time.ZonedDateTime").equals(classFullName)) { result = ((Date) result).toInstant().atZone(ZoneId.systemDefault()); } else if (("class java.sql.Date").equals(classFullName)) { result = new java.sql.Date(((Date) result).getTime()); } else if (("class java.sql.Time").equals(classFullName)) { result = new Time(((Date) result).getTime()); } else if (("class java.sql.Timestamp").equals(classFullName)) { result = new Timestamp(((Date) result).getTime()); } } else { switch (cell.getCellTypeEnum()) { case STRING: result = cell.getRichStringCellValue() == null ? "" : cell.getRichStringCellValue().getString(); break; case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { if ("class java.lang.String".equals(classFullName)) { result = formateDate(entity, cell.getDateCellValue()); } } else { result = readNumericCell(cell); } break; case BOOLEAN: result = Boolean.toString(cell.getBooleanCellValue()); break; case BLANK: break; case ERROR: break; case FORMULA: try { result = readNumericCell(cell); } catch (Exception e1) { try { result = cell.getRichStringCellValue() == null ? "" : cell.getRichStringCellValue().getString(); } catch (Exception e2) { throw new RuntimeException("获取公式类型的单元格失败", e2); } } break; default: break; } } return result; }
private Object readNumericCell(Cell cell) { Object result = null; double value = cell.getNumericCellValue(); if (((int) value) == value) { result = (int) value; } else { result = value; } return result; }
private String formateDate(ExcelImportEntity entity, Date value) { if (StringUtils.isNotEmpty(entity.getFormat()) && value != null) { SimpleDateFormat format = new SimpleDateFormat(entity.getFormat()); return format.format(value); } return null; }
private Date getDateData(ExcelImportEntity entity, String value) { if (StringUtils.isNotEmpty(entity.getFormat()) && StringUtils.isNotEmpty(value)) { SimpleDateFormat format = new SimpleDateFormat(entity.getFormat()); try { return format.parse(value); } catch (ParseException e) { try { return DateUtil.getJavaDate(Double.parseDouble(value)); } catch (NumberFormatException ex) { LOGGER.error("时间格式化失败,格式化:{},值:{}", entity.getFormat(), value); throw new ExcelImportException(ExcelImportEnum.GET_VALUE_ERROR); } } } return null; }
private void saveImage(Object object, String picId, Map<String, ExcelImportEntity> excelParams, String titleString, Map<String, PictureData> pictures, ImportParams params) throws Exception { if (pictures == null) { return; } PictureData image = pictures.get(picId); if (image == null) { return; } byte[] data = image.getData(); String fileName = "pic" + Math.round(Math.random() * 100000000000L); fileName += "." + PoiPublicUtil.getFileExtendName(data); if (excelParams.get(titleString).getSaveType() == 1) { String path = getSaveUrl(excelParams.get(titleString), object); File savefile = new File(path); if (!savefile.exists()) { savefile.mkdirs(); } savefile = new File(path + File.separator + fileName); FileOutputStream fos = new FileOutputStream(savefile); try { fos.write(data); } finally { IOUtils.closeQuietly(fos); } setValues(excelParams.get(titleString), object, getSaveUrl(excelParams.get(titleString), object) + File.separator + fileName); } else { setValues(excelParams.get(titleString), object, data); } }
private void createErrorCellStyle(Workbook workbook) { errorCellStyle = workbook.createCellStyle(); Font font = workbook.createFont(); font.setColor(Font.COLOR_RED); errorCellStyle.setFont(font); }
}
|