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 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 | package zj.excel.util; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import zj.check.util.CheckUtil; import zj.excel.bean.DatasKeySheets; import zj.excel.bean.Excel; import zj.excel.bean.ExcelI; import zj.excel.bean.ExcelTemplate; import zj.excel.bean.ReadExcelI; import zj.excel.bean.SheetDatas; import zj.java.util.JavaUtil; import zj.type.TypeUtil; /** * 概况 :Excel/xls/xlsx<br> * * @version 1.00 (2011.12.02) * @author SHNKCS 张军 {@link <a target=_blank href="http://www.shanghaijiadun.com">上海加盾信息科技有限公司</a> <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a> <a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>} <br> * * <br> * --------------------------读取excel数据------------------------------<br> * * <pre> * try { * Excel readExcel = new Excel(); * readExcel.setFilePath("E:/document/zj-utils/excel/写入excel" + "1" + ".xls"); * // readExcel.setSheetValue(new String[] { "Sheet1" }); * DatasKeySheets datasKeySheets = null; * // RE re = new RE(); * // datasKeySheets = ExcelUtil.readExcel(readExcel,re); * datasKeySheets = ExcelUtil.readExcel(readExcel); * List<SheetDatas> sheetDatas = datasKeySheets.getSheetDatas(); * for (SheetDatas datas : sheetDatas) { * // ======================= * System.out.println("sheet:" + datas.getSheetIndex() + "\t\t" + datas.getSheetName() + "\t\t" + datas.getSheet()); * // 循环sheet * // 获取某个sheet的行列数据 * List<List<SheetData>> datasLst = datas.getRowsDataLst(); * if (datasLst != null) { * // 循环某个sheet的行数据 * for (List<SheetData> dataLst : datasLst) { * // 循环某个sheet的列数据 * for (SheetData data : dataLst) { * if (data != null) { * System.out.print(data.getValue() + "\t\t"); * } * } * System.out.println(); * } * } * } * } catch (Exception e) { * e.printStackTrace(); * } * </pre> * * <pre> * <br>------------------------------导出excel数据------------------------------<br> * try { * // 设置数据 * for (int ii = 0; ii < 10; ii++) { * List<SheetDatas> sheetDatas = new ArrayList<SheetDatas>(); * for (int k = 0; k < 10; k++) { * // 所有行列数据对象 * SheetDatas sheetData = new SheetDatas(); * sheetData.setSheetName("sheet名." + k); * sheetDatas.add(sheetData); * // 所有行数据 * List<List<SheetData>> rowsDataLst = new ArrayList<List<SheetData>>(); * // 设置所有行数据 * sheetData.setRowsDataLst(rowsDataLst); * // 所有列数据 * List<SheetData> columnsDataLst = null; * // 所有单元格数据 * SheetData data = null; * // 实例化所有行列数据 * for (int i = 0; i < 10000; i++) { * // 设置第i行数据 * columnsDataLst = new ArrayList<SheetData>(); * rowsDataLst.add(columnsDataLst); * // 添加第j行数据 * for (int j = 0; j < 10; j++) { * data = new SheetData(); * if (j == 5) { * data.setValue(i * j); * } else { * data.setValue("行" + i + "列" + j); * } * columnsDataLst.add(data); * } * } * } * // 导出excel设置 * Excel excel = new Excel(); * excel.setFilePath("E:/document/zj-utils/excel/写入excel" + ii + ".xls"); * ExcelUtil.writeExcel(sheetDatas, excel); * } * } catch (Exception e) { * e.printStackTrace(); * } * </pre> */ public final class ExcelReadUtil implements Serializable { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(ExcelReadUtil. class .getName()); private ExcelReadUtil() { } /** * 读取excel * * @param excel * excel对象 * @return 所有行列数据对象 * @throws Exception */ public static final List<String> readExcelSheetNames( final Excel excel) throws Exception { List<String> sheetNames = new ArrayList<String>(); excel.initWorkbook(); Workbook wb = excel.getWb(); int sheetCount = wb.getNumberOfSheets(); // 循环所有sheet for ( int sheetIndex = 0 ; sheetIndex < sheetCount; sheetIndex++) { // 获得sheet工作簿Sheet Sheet sheet = wb.getSheetAt(sheetIndex); sheetNames.add(sheet.getSheetName()); } return sheetNames; } /** * 根据标题获取excel数据 * * @param excel * 数据对象 * @param rowsValues * 数据 * @return */ public static final void readTitleRowValues(Excel excel, SheetDatas datas) { Object objTitles = excel.getObjTitles(); String titleSplit = excel.getTitleSplit(); int titleRowIndex = excel.getTitleRow(); List<List<Object>> rowsValues = datas.getRowValues(); datas.setTitleRowValues(readTitleRowValues(objTitles, titleSplit, titleRowIndex, rowsValues)); } /** * 根据标题获取excel数据 * * @param objTitles * 标题对象 * @param titleSplit * 标题分割符 * @param titleRowIndex * 标题行索引 * @param rowsValues * 值 * @return */ @SuppressWarnings ( "unchecked" ) public static final List<Map<String, Object>> readTitleRowValues(Object objTitles, String titleSplit, int titleRowIndex, List<List<Object>> rowsValues) { // 行值->{标题:值} List<Map<String, Object>> titleRowValues = new ArrayList<Map<String, Object>>(); if (rowsValues != null ) { // 标题对应的数据索引 Map<String, Integer> titlesIndex = new HashMap<String, Integer>(); if (objTitles instanceof String[]) { String[] titleKeys = (String[]) objTitles; for (String title : titleKeys) { titlesIndex.put(title, - 1 ); } } else if (objTitles instanceof Collection) { Collection<String> titleKeys = (Collection<String>) objTitles; for (String title : titleKeys) { titlesIndex.put(title, - 1 ); } } else { return titleRowValues; } // System.out.println("总行数:" + datasLst.size()); if (rowsValues.size() > 0 ) { // 设置标题项 List<Object> titleDatas = rowsValues.get(titleRowIndex); for ( int i = 0 ; i < titleDatas.size(); i++) { String value = JavaUtil.objToStr(titleDatas.get(i)); for (String title : titlesIndex.keySet()) { String[] titles = JavaUtil.split(title, titleSplit); String thisTitle = titles[ 0 ]; if (thisTitle.equals(value)) { // 如果标题相同,设置列索引 titlesIndex.put(title, i); break ; } } // System.out.print(value + "\t\t"); } // System.out.println(); // System.out.println(titlesIndex); for ( int i = 0 ; i < rowsValues.size(); i++) { if (i == titleRowIndex) { // 去除标题行 continue ; } List<Object> rowDatas = rowsValues.get(i); Map<String, Object> rowValue = new HashMap<String, Object>(); // 添加数据 titleRowValues.add(rowValue); for (String title : titlesIndex.keySet()) { // 获取列索引 Integer colIndex = titlesIndex.get(title); // 根据列索引获取数据 Object value = null ; if (colIndex != - 1 ) { if (rowDatas.size()>colIndex){ value = rowDatas.get(colIndex); } } String[] titles = JavaUtil.split(title, titleSplit); String thisTitle = titles[ 0 ]; if (titles.length > 1 ) { // 别名 thisTitle = titles[ 1 ]; } // 设置行数据{title,value} rowValue.put(thisTitle, value); } } // System.out.println(rowValues); } } return titleRowValues; } /** * 读取excel * * @param excel * excel对象 * @return 所有行列数据对象 * @throws Exception */ public static final DatasKeySheets readExcel( final Excel excel) throws Exception { return readExcel(excel, null ); } /** * 读取excel * * @param excel * excel对象 * @param excelI * excelI接口 * @return 所有行列数据对象 * @throws Exception */ @SuppressWarnings ( "rawtypes" ) public static final DatasKeySheets readExcel( final Excel excel, final ExcelI excelI) throws Exception { excel.initWorkbook(); Workbook wb = excel.getWb(); // key:index/sheet/sheetName DatasKeySheets datasKeySheets = new DatasKeySheets(); List<SheetDatas> sheetDatas = new ArrayList<SheetDatas>(); Sheet sheet = null ; int sheetCount = wb.getNumberOfSheets(); // 获得sheet工作簿Sheet Object sheetValue = excel.getSheetValue(); boolean isUseTitleData = excel.getObjTitles() != null ; if (sheetValue == null ) { // 循环所有sheet for ( int sheetIndex = 0 ; sheetIndex < sheetCount; sheetIndex++) { // 获得sheet工作簿Sheet sheet = wb.getSheetAt(sheetIndex); SheetDatas datas = new SheetDatas(); datas.setSheetIndex(sheetIndex); datas.setSheetName(sheet.getSheetName()); datas.setSheet(sheet); sheetDatas.add(datas); readRowValue(excel, sheet, datas, excelI); if (isUseTitleData) { readTitleRowValues(excel, datas); } } } else { if (sheetValue instanceof String) { String sheetName = String.valueOf(sheetValue); sheet = wb.getSheet(sheetName); if (sheet != null ) { SheetDatas datas = new SheetDatas(); datas.setSheetIndex(wb.getSheetIndex(sheet)); datas.setSheetName(sheet.getSheetName()); datas.setSheet(sheet); sheetDatas.add(datas); readRowValue(excel, sheet, datas, excelI); if (isUseTitleData) { readTitleRowValues(excel, datas); } } } else if (sheetValue instanceof Integer) { Integer sheetIndex = Integer.parseInt(String.valueOf(sheetValue)); sheet = wb.getSheetAt(sheetIndex); if (sheet != null ) { SheetDatas datas = new SheetDatas(); datas.setSheetIndex(sheetIndex); datas.setSheetName(sheet.getSheetName()); datas.setSheet(sheet); sheetDatas.add(datas); readRowValue(excel, sheet, datas, excelI); if (isUseTitleData) { readTitleRowValues(excel, datas); } } } else if (sheetValue instanceof String[]) { String[] sheetNames = (String[]) sheetValue; for (String sheetName : sheetNames) { sheet = wb.getSheet(sheetName); if (sheet != null ) { SheetDatas datas = new SheetDatas(); datas.setSheetIndex(wb.getSheetIndex(sheet)); datas.setSheetName(sheet.getSheetName()); datas.setSheet(sheet); sheetDatas.add(datas); readRowValue(excel, sheet, datas, excelI); if (isUseTitleData) { readTitleRowValues(excel, datas); } } } } else if (sheetValue instanceof int []) { int [] sheetIndexs = ( int []) sheetValue; for ( int a = 0 ; a < sheetIndexs.length; a++) { sheet = wb.getSheetAt(a); if (sheet != null ) { SheetDatas datas = new SheetDatas(); datas.setSheetIndex(a); datas.setSheetName(sheet.getSheetName()); datas.setSheet(sheet); sheetDatas.add(datas); readRowValue(excel, sheet, datas, excelI); if (isUseTitleData) { readTitleRowValues(excel, datas); } } } } else if (sheetValue instanceof Integer[]) { Integer[] sheetIndexs = (Integer[]) sheetValue; for ( int a = 0 ; a < sheetIndexs.length; a++) { sheet = wb.getSheetAt(a); if (sheet != null ) { SheetDatas datas = new SheetDatas(); datas.setSheetIndex(a); datas.setSheetName(sheet.getSheetName()); datas.setSheet(sheet); sheetDatas.add(datas); readRowValue(excel, sheet, datas, excelI); if (isUseTitleData) { readTitleRowValues(excel, datas); } } } } else if (sheetValue instanceof Collection) { Collection sheetCollection = (Collection) sheetValue; Iterator it = sheetCollection.iterator(); while (it.hasNext()) { Object ito = it.next(); if (ito instanceof Integer) { int sheetIndex = Integer.parseInt(String.valueOf(ito)); sheet = wb.getSheetAt(sheetIndex); if (sheet != null ) { SheetDatas datas = new SheetDatas(); datas.setSheetIndex(sheetIndex); datas.setSheetName(sheet.getSheetName()); datas.setSheet(sheet); sheetDatas.add(datas); readRowValue(excel, sheet, datas, excelI); if (isUseTitleData) { readTitleRowValues(excel, datas); } } } else if (ito instanceof String) { String sheetName = String.valueOf(ito); sheet = wb.getSheet(sheetName); if (sheet != null ) { SheetDatas datas = new SheetDatas(); datas.setSheetIndex(wb.getSheetIndex(sheet)); datas.setSheetName(sheet.getSheetName()); datas.setSheet(sheet); sheetDatas.add(datas); readRowValue(excel, sheet, datas, excelI); if (isUseTitleData) { readTitleRowValues(excel, datas); } } } } } else { throw new Exception( "不支持类型:" + sheetValue); } } datasKeySheets.setSheetDatas(sheetDatas); datasKeySheets.setSheetCount(sheetCount); return datasKeySheets; } /** * 读取sheet行列集合(正常) * * @param sheet * @param datas * @param excelI * @throws Exception */ public static final void readRowValue( final Excel excel, final Sheet sheet, final SheetDatas datas, final ExcelI excelI) throws Exception { ReadExcelI rexcelI = null ; if (excelI != null ) { rexcelI = (ReadExcelI) excelI; } // 行列数据 List<List<Object>> rowValues = new ArrayList<List<Object>>(); int endRowIndex = rexcelI == null ? ExcelI.END_ROW_INDEX : rexcelI.getEndRowIndex(); int endColumnIndex = rexcelI == null ? ExcelI.END_COLUMN_INDEX : rexcelI.getEndColumnIndex(); // 循环sheet中的所有行数据 for ( int rowIndex = rexcelI == null ? ExcelI.START_ROW_INDEX : rexcelI.getStartRowIndex(); rowIndex <= sheet.getLastRowNum(); rowIndex++) { // 是否结束 if (endRowIndex != - 1 && rowIndex > endRowIndex) break ; if (rexcelI != null && rexcelI.filterRow(sheet, rowIndex)) { // ("sheetName:" + sheet.getSheetName() + ",第" + rowIndex + "行数据已被过虑"); continue ; } // 获得行对象 Row row = sheet.getRow(rowIndex); // 判断是否一行全部为""或null boolean notNull = excel.isAddRowNull(); if ( null != row) { // 行数据 List<Object> rowValue = new ArrayList<Object>(); // // 添加标题索引值 // if (excel.getTitleKeys() != null && rowIndex == ExcelI.START_ROW_INDEX) { // for (int ci = 0; ci < rowTitle.getLastCellNum(); ci++) { // String titleKey = null; // if (excel.getTitleKeys().size() > ci) { // titleKey = excel.getTitleKeys().get(ci); // } else { // // 默认当前单元格式值 // Cell cell = row.getCell(ci); // Object value = readCellString(cell); // value = rexcelI == null ? value : rexcelI.readValue(sheet, rowIndex, ci, value); // titleKey = JavaUtil.objToStr(value); // } // rowsDataMap.put(titleKey, new ArrayList<Map<String,SheetData>>()); // } // } // 获得本行中单元格的个数 // 遍历列cell for ( int columnIndex = rexcelI == null ? 0 : rexcelI.getStartColumnIndex(); columnIndex < row.getLastCellNum(); columnIndex++) { // 是否结束 if (endColumnIndex != - 1 && columnIndex > endColumnIndex) break ; Cell cell = row.getCell(columnIndex); // 获得指定单元格中的数据 Object value = readCellString(cell); value = rexcelI == null ? value : rexcelI.readValue(sheet, rowIndex, columnIndex, value); if (!notNull && CheckUtil.isNotNull(JavaUtil.objToStr(value))) { notNull = true ; } rowValue.add(value); } if (notNull) { rowValues.add(rowValue); } } else { List<Object> rowValue = new ArrayList<Object>(); if (notNull) { rowValues.add(rowValue); } } } // 删除判断最后行是否一行全部为""或null List<List<Object>> addRowsNull = new ArrayList<List<Object>>(); boolean notNull = false ; for ( int b = rowValues.size() - 1 ; b >= 0 ; b--) { List<Object> datasNull = rowValues.get(b); for (Object value : datasNull) { if (!notNull && CheckUtil.isNotNull(JavaUtil.objToStr(value))) { notNull = true ; break ; } } if (notNull) { break ; } addRowsNull.add(datasNull); } for (List<Object> datasNull : addRowsNull) { rowValues.remove(datasNull); } datas.setRowValues(rowValues); } /** * 获取导出的excel的sheet,复制新模板sheet * * @param excel * @return * @throws Exception */ public static Set<Sheet> readSheets( final ExcelTemplate excel) throws Exception { Set<Sheet> sheets = new HashSet<Sheet>(); excel.initWorkbook(); Workbook wb = excel.getWb(); // key:index/sheet/sheetName Sheet sheet = null ; int sheetCount = wb.getNumberOfSheets(); // 获得sheet工作簿Sheet Object sheetValue = excel.getSheetValue(); // if (sheetValue == null) { // // 循环所有sheet // for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++) { // // 获得sheet工作簿Sheet // sheet = wb.getSheetAt(sheetIndex); // sheets.add(sheet); // } // } else { // if (sheetValue instanceof String) { // String sheetName = String.valueOf(sheetValue); // // 取得 // sheet = wb.getSheet(sheetName); // sheets.add(sheet); // } else if (sheetValue instanceof Integer) { // Integer sheetIndex = Integer.parseInt(String.valueOf(sheetValue)); // sheet = wb.getSheetAt(sheetIndex); // sheets.add(sheet); // } else if (sheetValue instanceof String[]) { // String[] sheetNames = (String[]) sheetValue; // for (String sheetName : sheetNames) { // sheet = wb.getSheet(sheetName); // //wb.setSheetName(wb.getSheetIndex(sheet), sheetName + "--zhangjun"); // sheets.add(sheet); // } // } else if (sheetValue instanceof int[]) { // int[] sheetIndexs = (int[]) sheetValue; // for (int a = 0; a < sheetIndexs.length; a++) { // sheet = wb.getSheetAt(a); // sheets.add(sheet); // } // } else if (sheetValue instanceof Integer[]) { // Integer[] sheetIndexs = (Integer[]) sheetValue; // for (int a = 0; a < sheetIndexs.length; a++) { // sheet = wb.getSheetAt(a); // sheets.add(sheet); // } // } else if (sheetValue instanceof Collection) { // Collection sheetCollection = (Collection) sheetValue; // Iterator it = sheetCollection.iterator(); // while (it.hasNext()) { // Object ito = it.next(); // if (ito instanceof Integer) { // int sheetIndex = Integer.parseInt(String.valueOf(ito)); // sheet = wb.getSheetAt(sheetIndex); // sheets.add(sheet); // } else if (ito instanceof String) { // String sheetName = String.valueOf(ito); // sheet = wb.getSheet(sheetName); // sheets.add(sheet); // } // } // } else { // throw new Exception("不支持类型:" + sheetValue); // } // } if (sheetValue == null ) { // 循环所有sheet for ( int sheetIndex = 0 ; sheetIndex < sheetCount; sheetIndex++) { // 获得sheet工作簿Sheet sheet = wb.getSheetAt(sheetIndex); addWriteSheetVariable(excel, sheets, sheet); } } else { if (sheetValue instanceof String) { String sheetNames = String.valueOf(sheetValue); sheet = readCloneSheet(wb, excel, sheetNames); addWriteSheetVariable(excel, sheets, sheet); } else if (sheetValue instanceof Integer) { Integer sheetIndex = Integer.parseInt(String.valueOf(sheetValue)); sheet = wb.getSheetAt(sheetIndex); addWriteSheetVariable(excel, sheets, sheet); } else if (sheetValue instanceof String[]) { String[] sheetNameAry = (String[]) sheetValue; for (String sheetNames : sheetNameAry) { sheet = readCloneSheet(wb, excel, sheetNames); addWriteSheetVariable(excel, sheets, sheet); } } else if (sheetValue instanceof int []) { int [] sheetIndexs = ( int []) sheetValue; for ( int a = 0 ; a < sheetIndexs.length; a++) { sheet = wb.getSheetAt(a); addWriteSheetVariable(excel, sheets, sheet); } } else if (sheetValue instanceof Integer[]) { Integer[] sheetIndexs = (Integer[]) sheetValue; for ( int a = 0 ; a < sheetIndexs.length; a++) { sheet = wb.getSheetAt(a); addWriteSheetVariable(excel, sheets, sheet); } } else if (sheetValue instanceof Collection) { Collection<?> sheetCollection = (Collection<?>) sheetValue; Iterator<?> it = sheetCollection.iterator(); while (it.hasNext()) { Object ito = it.next(); if (ito instanceof Integer) { int sheetIndex = Integer.parseInt(String.valueOf(ito)); sheet = wb.getSheetAt(sheetIndex); addWriteSheetVariable(excel, sheets, sheet); } else if (ito instanceof String) { String sheetNames = String.valueOf(ito); sheet = readCloneSheet(wb, excel, sheetNames); addWriteSheetVariable(excel, sheets, sheet); } } } else { throw new Exception( "不支持类型:" + sheetValue); } } return sheets; } private static void addWriteSheetVariable( final ExcelTemplate excel, Set<Sheet> sheets, Sheet sheet) { if (sheet != null ) { sheets.add(sheet); excel.addedSheets.add(sheet.getSheetName()); } } /** * 获取sheet对象 * * @param wb * @param sheetNames * @return */ private static Sheet readCloneSheet( final Workbook wb, final ExcelTemplate excel, final String sheetNames) { String sheetNamesAry[] = JavaUtil.split(sheetNames, "*" ); String sheetName = "" ; String newSheetName = "" ; if (sheetNamesAry.length > 0 ) { sheetName = sheetNamesAry[ 0 ]; } if (sheetNamesAry.length > 1 ) { newSheetName = sheetNamesAry[ 1 ]; } Sheet sheet = wb.getSheet(sheetName); if (sheet != null ) { // 重点:针对输出多个模板sheet时,模板sheet名称取值一定要唯一,由于使用过sheet之后会重新重命名原来的模板名,否则添加多个sheet无法进行判断 if (CheckUtil.isNull(newSheetName)) { // 没有重命名,克隆后,此时无法进行一个sheet模板输出多个sheet,因为在输出时已经把模板sheet重写了 } else { if (sheetName.equals(newSheetName)) { } else { // 重命名 int index = wb.getSheetIndex(sheet); // 被克隆对象 Sheet cloneSheet = wb.cloneSheet(index); // 重命名(克隆后,还原以前的模板名) wb.setSheetName(index, newSheetName); // 重命名复制模板sheet的名字 int cloneIndex = wb.getSheetIndex(cloneSheet); wb.setSheetName(cloneIndex, sheetName); excel.templateSheets.add(cloneSheet.getSheetName()); } } } return sheet; } /** * 读取excel某个单元格值的索引号 * * @param excel * excel对象 * @param params * 参数 * @return 单元格值 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @throws Exception */ public static final Map<ConstantForEnum.CellValueKey, Integer> readCellValueIndex( final Excel excel, Map<ConstantForEnum.CellValueKey, Object> params) throws Exception { Map<ConstantForEnum.CellValueKey, Integer> returnMap = new HashMap<ConstantForEnum.CellValueKey, Integer>(); returnMap.put(ConstantForEnum.CellValueKey.ROW_INDEX, - 1 ); returnMap.put(ConstantForEnum.CellValueKey.COLUMN_INDEX, - 1 ); String value = JavaUtil.trim(JavaUtil.objToStr(params.get(ConstantForEnum.CellValueKey.VALUE))); Object valueCountObj = params.get(ConstantForEnum.CellValueKey.VALUE_COUNT); boolean valueCountMatch = TypeUtil.Primitive.booleanValue(params.get(ConstantForEnum.CellValueKey.VALUE_COUNT_MATCH)); Object valueRowObj = params.get(ConstantForEnum.CellValueKey.VALUE_ROW); Object valueColumnObj = params.get(ConstantForEnum.CellValueKey.VALUE_COLUMN); int valueRow = - 1 ; int valueColumn = - 1 ; if (valueRowObj != null ) { valueRow = TypeUtil.Primitive.intValue(valueRowObj); } if (valueColumnObj != null ) { valueColumn = TypeUtil.Primitive.intValue(valueColumnObj); } int valueCount = 1 ; if (valueCountObj != null ) { valueCount = TypeUtil.Primitive.intValue(valueCountObj); } if (CheckUtil.isNull(value)) { // logger.debug("查询值不能为空"); return returnMap; } int valueCountDefault = 0 ; int tempRowCount = - 1 ; int tempColumnCount = - 1 ; Sheet sheet = readSheet(excel); // 如果未指定查询行,则查询所有行,否则只查询一行,从valueRow开始到valueRow+1结束 int startRows = - 1 ; int rows = - 1 ; if (valueRow == - 1 ) { startRows = 0 ; rows = sheet.getLastRowNum(); } else { startRows = valueRow; rows = valueRow + 1 ; } for ( int i = startRows; i < rows; i++) { Row row = sheet.getRow(i); if (row == null ) { // logger.debug("第[" + i + "]行对象为null,继续下个行对象查询"); continue ; } int startColumns = - 1 ; int columns = - 1 ; if (valueColumn == - 1 ) { startColumns = 0 ; columns = row.getLastCellNum(); } else { startColumns = valueColumn; columns = valueColumn + 1 ; } breakFor: for ( int j = startColumns; j < columns; j++) { Cell cell = row.getCell(j); if (cell == null ) { // logger.debug("第[" + i + "]行第[" + j + "]列单元格对象为null,继续下个单元格查询"); continue ; } Object obj = readCellString(cell); String cellValue = JavaUtil.trim(JavaUtil.objToStr(obj)); if (valueCountDefault != valueCount) { // 如果未找到指定的匹配索引,则继续查找 if (value.equals(cellValue)) { tempRowCount = i; tempColumnCount = j; valueCountDefault++; } } if (tempRowCount != - 1 && tempColumnCount != - 1 ) { // 获取行列索引,判断行列第几个 if (valueCountDefault == valueCount) { // logger.debug("找到位置了行[" + tempRowCount + "]列[" + tempColumnCount + "]第[" + valueCount + "]个值"); break breakFor; } } } } if (tempRowCount == - 1 || tempColumnCount == - 1 ) { // logger.debug("没有找到位置了行[" + tempRowCount + "]列[" + tempColumnCount + "]第[" + valueCount + "]个值"); return returnMap; } else { if (valueCountMatch && valueCountDefault != valueCount) { // logger.debug("行必须匹配,没有找到位置了行[" + tempRowCount + "]列[" + tempColumnCount + "][最多第(" + valueCountDefault + ")个与配置第(" + valueCount + ")个值不同]"); return returnMap; } returnMap.put(ConstantForEnum.CellValueKey.ROW_INDEX, tempRowCount); returnMap.put(ConstantForEnum.CellValueKey.COLUMN_INDEX, tempColumnCount); } return returnMap; } /** * 读取excel某个单元格值 * * @param excel * excel对象 * @param params * 参数 * @return 单元格值 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @throws Exception */ public static final Object readCellValue( final Excel excel, Map<ConstantForEnum.CellValueKey, Object> params) throws Exception { Object rowIndexObj = params.get(ConstantForEnum.CellValueKey.ROW_INDEX); Object columnIndexObj = params.get(ConstantForEnum.CellValueKey.COLUMN_INDEX); if (rowIndexObj == null || columnIndexObj == null ) { Sheet sheet = readSheet(excel); Map<ConstantForEnum.CellValueKey, Object> paramsRow = new HashMap<ConstantForEnum.CellValueKey, Object>(); paramsRow.put(ConstantForEnum.CellValueKey.VALUE, params.get(ConstantForEnum.CellValueKey.ROW_VALUE)); paramsRow.put(ConstantForEnum.CellValueKey.VALUE_COUNT, params.get(ConstantForEnum.CellValueKey.ROW_COUNT)); paramsRow.put(ConstantForEnum.CellValueKey.VALUE_COUNT_MATCH, params.get(ConstantForEnum.CellValueKey.ROW_COUNT_MATCH)); Map<ConstantForEnum.CellValueKey, Integer> returnRowIndex = ExcelReadUtil.readCellValueIndex(excel, paramsRow); int tempRowCount = returnRowIndex.get(ConstantForEnum.CellValueKey.ROW_INDEX); if (tempRowCount == - 1 ) { return null ; } Map<ConstantForEnum.CellValueKey, Object> paramsColumn = new HashMap<ConstantForEnum.CellValueKey, Object>(); paramsColumn.put(ConstantForEnum.CellValueKey.VALUE, params.get(ConstantForEnum.CellValueKey.COLUMN_VALUE)); paramsColumn.put(ConstantForEnum.CellValueKey.VALUE_COUNT, params.get(ConstantForEnum.CellValueKey.COLUMN_COUNT)); paramsColumn.put(ConstantForEnum.CellValueKey.VALUE_COUNT_MATCH, params.get(ConstantForEnum.CellValueKey.COLUMN_COUNT_MATCH)); Map<ConstantForEnum.CellValueKey, Integer> returnColumnIndex = ExcelReadUtil.readCellValueIndex(excel, paramsColumn); int tempColumnCount = returnColumnIndex.get(ConstantForEnum.CellValueKey.COLUMN_INDEX); if (tempColumnCount == - 1 ) { return null ; } return readCellString(sheet.getRow(tempRowCount).getCell(tempColumnCount)); // String rowValue = JavaUtil.trim(JavaUtil.objToStr(params.get(ConstantForEnum.CellValueKey.ROW_VALUE))); // String columnValue = JavaUtil.trim(JavaUtil.objToStr(params.get(ConstantForEnum.CellValueKey.COLUMN_VALUE))); // Object rowCountObj = params.get(ConstantForEnum.CellValueKey.ROW_COUNT); // Object columnCountObj = params.get(ConstantForEnum.CellValueKey.COLUMN_COUNT); // boolean rowCountMatch = TypeUtil.Primitive.booleanValue(params.get(ConstantForEnum.CellValueKey.ROW_COUNT_MATCH)); // boolean columnCountMatch = TypeUtil.Primitive.booleanValue(params.get(ConstantForEnum.CellValueKey.COLUMN_COUNT_MATCH)); // int rowCount = 1; // int columnCount = 1; // if (rowCountObj != null) { // rowCount = TypeUtil.Primitive.intValue(rowCountObj); // } // if (columnCountObj != null) { // columnCount = TypeUtil.Primitive.intValue(columnCountObj); // } // if (CheckUtil.isNull(rowValue) || CheckUtil.isNull(columnValue)) { // logger.debug("行[" + rowValue + "]或列[" + columnValue + "]值不能为空"); // return null; // } // int rowCountDefault = 0; // int columnCountDefault = 0; // int tempRowCount = -1; // int tempColumnCount = -1; // Sheet sheet = getSheet(excel); // for (int i = 0; i < sheet.getLastRowNum(); i++) { // Row row = sheet.getRow(i); // if (row == null) { // logger.debug("第[" + i + "]行对象为null,继续下个行对象查询"); // continue; // } // breakFor: for (int j = 0; j < row.getLastCellNum(); j++) { // Cell cell = row.getCell(j); // if (cell == null) { // logger.debug("第[" + i + "]行第[" + j + "]列单元格对象为null,继续下个单元格查询"); // continue; // } // Object obj = readCellString(cell); // String value = JavaUtil.trim(JavaUtil.objToStr(obj)); // if (rowCountDefault != rowCount) { // // 如果未找到指定的匹配行索引,则继续查找 // if (rowValue.equals(value)) { // tempRowCount = i; // rowCountDefault++; // } // } // if (columnCountDefault != columnCount) { // // 如果未找到指定的匹配列索引,则继续查找 // if (columnValue.equals(value)) { // tempColumnCount = j; // columnCountDefault++; // } // } // if (tempRowCount != -1 && tempColumnCount != -1) { // // 获取行列索引,判断行列第几个 // if (rowCountDefault == rowCount && columnCountDefault == columnCount) { // logger.debug("找到位置了行[" + tempRowCount + "]第[" + rowCount + "]个值,列[" + tempColumnCount + "]第[" + columnCount + "]个值"); // break breakFor; // } // } // } // } // if (tempRowCount == -1 || tempColumnCount == -1) { // logger.debug("没有找到位置了行[" + tempRowCount + "]第[" + rowCount + "]个值,列[" + tempColumnCount + "]第[" + columnCount + "]个值"); // return null; // } else { // if (rowCountMatch && rowCountDefault != rowCount) { // logger.debug("行必须匹配,没有找到位置了行[" + tempRowCount + "][最多第(" + rowCountDefault + ")个与配置第(" + rowCount + ")个值不同],列[" + tempColumnCount + "]第[" + columnCount + "]个值"); // return null; // } // if (columnCountMatch && columnCountDefault != columnCount) { // logger.debug("列必须匹配,没有找到位置了行[" + tempRowCount + "]第[" + rowCount + "]个值,列[" + tempColumnCount + "][最多第(" + columnCountDefault + ")个与配置第(" + columnCount + ")个值不同]"); // return null; // } // return readCellString(sheet.getRow(tempRowCount).getCell(tempColumnCount)); // } } else { int rowIndex = TypeUtil.Primitive.intValue(rowIndexObj); int columnIndex = TypeUtil.Primitive.intValue(columnIndexObj); if (rowIndex == - 1 || columnIndex == - 1 ) { // logger.debug("行[" + rowIndex + "]或列[" + columnIndex + "]索引值不能小于0"); return null ; } Sheet sheet = readSheet(excel); Row row = sheet.getRow(TypeUtil.Primitive.intValue(rowIndexObj)); if (row == null ) { // logger.debug("第[" + rowIndex + "]行对象为null"); return null ; } Cell cell = row.getCell(columnIndex); if (cell == null ) { // logger.debug("第[" + rowIndex + "]行第[" + columnIndex + "]列单元格对象为null"); return null ; } return readCellString(cell); } } /** * 获取sheet对象 * * @return sheet对象 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 * @throws Exception */ public static Sheet readSheet( final Excel excel) throws Exception { excel.initWorkbook(); Workbook wb = excel.getWb(); // key:index/sheet/sheetName Sheet sheet = null ; // 获得sheet工作簿Sheet Object sheetValue = excel.getSheetValue(); if (sheetValue == null ) { sheet = wb.getSheetAt( 0 ); } else { if (sheetValue instanceof String) { String sheetName = String.valueOf(sheetValue); sheet = wb.getSheet(sheetName); } else if (sheetValue instanceof Integer) { Integer sheetCount = Integer.parseInt(String.valueOf(sheetValue)); sheet = wb.getSheetAt(sheetCount); } } return sheet; } /** * 判断指定的单元格是否是合并单元格 * * @param sheet * @param row * 行下标 * @param column * 列下标 * @return null:没有合并,非null,有合并 */ public static final CellRangeAddress readMergedRegion( final Sheet sheet, final int row, final int column) { int sheetMergeCount = sheet.getNumMergedRegions(); for ( int i = 0 ; i < sheetMergeCount; i++) { CellRangeAddress range = sheet.getMergedRegion(i); int firstColumn = range.getFirstColumn(); int lastColumn = range.getLastColumn(); int firstRow = range.getFirstRow(); int lastRow = range.getLastRow(); if (row >= firstRow && row <= lastRow) { if (column >= firstColumn && column <= lastColumn) { return range; } } } return null ; } /** * 获取一个cell的数据类型 * * @param cell * @return */ public static final Object readCell( final Cell cell) { Object result = null ; try { result = cell.getRichStringCellValue(); } catch (Exception e) { try { result = cell.getNumericCellValue(); } catch (Exception e2) { try { result = cell.getDateCellValue(); } catch (Exception e3) { try { result = cell.getBooleanCellValue(); } catch (Exception e4) { logger.error( "获取excel公式结果出错:[" + cell.getRowIndex() + "][" + cell.getColumnIndex() + "]" , e4); // 返回公式 result = "=" + cell.getCellFormula(); } } } } return result; } /** * 获取一个cell的数据类型 * * @param cell * @return */ public static final Object readCellString( final Cell cell) { Object result = null ; if (cell != null ) { // 单元格类型:Numeric:0,String:1,Formula:2,Blank:3,Boolean:4,Error:5 int cellType = cell.getCellType(); try { switch (cellType) { case Cell.CELL_TYPE_STRING: result = cell.getRichStringCellValue().getString(); break ; case Cell.CELL_TYPE_NUMERIC: if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) { result = cell.getDateCellValue(); } else { result = cell.getNumericCellValue(); } break ; case Cell.CELL_TYPE_FORMULA: result = readCell(cell); break ; case Cell.CELL_TYPE_BOOLEAN: result = cell.getBooleanCellValue(); break ; case Cell.CELL_TYPE_BLANK: result = null ; break ; case Cell.CELL_TYPE_ERROR: result = null ; break ; default : break ; } } catch (Exception e) { // 读取文本 logger.error( "读取格式行列[" + cell.getRowIndex() + "," + cell.getColumnIndex() + "]出错,改成读取文本:" + e.getMessage()); try { result = cell.getRichStringCellValue().getString(); } catch (Exception e1) { logger.error( "改成读取文本出错,返回null:" + e1.getMessage()); return null ; } } } return JavaUtil.getIsNumValue(result); } } |
本文为张军原创文章,转载无需和我联系,但请注明来自张军的军军小站,个人博客http://www.zhangjunbk.com