From e2f9505cb35c152b8f12da00466626dfecbd57a7 Mon Sep 17 00:00:00 2001 From: jueyue Date: Sun, 9 Jun 2019 13:57:53 +0800 Subject: [PATCH] =?UTF-8?q?=E6=A0=B9=E6=8D=AE=E7=94=A8=E6=88=B7=E9=9C=80?= =?UTF-8?q?=E6=B1=82=E5=8A=A0=E5=85=A5=E4=BA=86=E5=AF=BC=E5=85=A5=E5=B9=B6?= =?UTF-8?q?=E8=A1=8C=E8=AE=A1=E7=AE=97,EXCEL=E8=BD=AC=E6=8D=A2html=20?= =?UTF-8?q?=E8=A1=8C=E5=92=8C=E8=A1=A8=E5=A4=B4=E7=AD=89=E4=B8=80=E4=BA=9B?= =?UTF-8?q?=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/entity/ExcelToHtmlParams.java | 19 ++ .../easypoi/excel/entity/ImportParams.java | 24 ++ .../template/ExcelExportOfTemplateUtil.java | 11 +- .../excel/html/ExcelToHtmlService.java | 64 +++-- .../excel/imports/CellValueService.java | 76 ++--- .../excel/imports/ExcelImportService.java | 260 +++++++++--------- .../recursive/ExcelImportForkJoinWork.java | 132 +++++++++ .../afterturn/easypoi/util/PoiPublicUtil.java | 163 ++++++----- 8 files changed, 469 insertions(+), 280 deletions(-) create mode 100644 easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/recursive/ExcelImportForkJoinWork.java diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/ExcelToHtmlParams.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/ExcelToHtmlParams.java index 4e16d81..e4a126e 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/ExcelToHtmlParams.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/ExcelToHtmlParams.java @@ -28,6 +28,9 @@ public class ExcelToHtmlParams { */ private String path = null; + private boolean showRowNum = false; + private boolean showColumnHead = false; + public ExcelToHtmlParams(Workbook wb) { this.wb = wb; } @@ -98,6 +101,22 @@ public class ExcelToHtmlParams { this.path = path; } + public boolean isShowRowNum() { + return showRowNum; + } + + public void setShowRowNum(boolean showRowNum) { + this.showRowNum = showRowNum; + } + + public boolean isShowColumnHead() { + return showColumnHead; + } + + public void setShowColumnHead(boolean showColumnHead) { + this.showColumnHead = showColumnHead; + } + @Override public boolean equals(Object obj) { if (obj instanceof ExcelToHtmlParams) { diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/ImportParams.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/ImportParams.java index 50b74f8..3752975 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/ImportParams.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/ImportParams.java @@ -102,6 +102,14 @@ public class ImportParams extends ExcelBaseParams { * 仅仅支持titleRows + headRows + startRows 以及 lastOfInvalidRow */ private boolean readSingleCell = false; + /** + * 是否并行计算 + */ + private boolean concurrentTask = false; + /** + * 最小截取大小 + */ + private Integer critical = 1000; public int getHeadRows() { return headRows; @@ -238,4 +246,20 @@ public class ImportParams extends ExcelBaseParams { public void setNeedCheckOrder(boolean needCheckOrder) { this.needCheckOrder = needCheckOrder; } + + public boolean isConcurrentTask() { + return concurrentTask; + } + + public void setConcurrentTask(boolean concurrentTask) { + this.concurrentTask = concurrentTask; + } + + public Integer getCritical() { + return critical; + } + + public void setCritical(Integer critical) { + this.critical = critical; + } } diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/export/template/ExcelExportOfTemplateUtil.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/export/template/ExcelExportOfTemplateUtil.java index 93a7e60..57f923d 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/export/template/ExcelExportOfTemplateUtil.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/export/template/ExcelExportOfTemplateUtil.java @@ -621,11 +621,15 @@ public final class ExcelExportOfTemplateUtil extends BaseExportService { private void setMergedRegionStyle(Row row, int ci, ExcelForEachParams params) { //第一行数据 for (int i = 1; i < params.getColspan(); i++) { - row.getCell(ci + i).setCellStyle(params.getCellStyle()); + if(params.getCellStyle() != null){ + row.getCell(ci + i).setCellStyle(params.getCellStyle()); + } } for (int i = 1; i < params.getRowspan(); i++) { for (int j = 0; j < params.getColspan(); j++) { - row.getCell(ci + j).setCellStyle(params.getCellStyle()); + if(params.getCellStyle() != null){ + row.getCell(ci + j).setCellStyle(params.getCellStyle()); + } } } } @@ -785,6 +789,9 @@ public final class ExcelExportOfTemplateUtil extends BaseExportService { try { this.teplateParams = params; wb = getCloneWorkBook(); + // 创建表格样式 + setExcelExportStyler((IExcelExportStyler) teplateParams.getStyle() + .getConstructor(Workbook.class).newInstance(wb)); // step 3. 解析模板 for (int i = 0, le = params.isScanAllsheet() ? wb.getNumberOfSheets() : params.getSheetNum().length; i < le; i++) { diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/html/ExcelToHtmlService.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/html/ExcelToHtmlService.java index 7028ed1..a34a288 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/html/ExcelToHtmlService.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/html/ExcelToHtmlService.java @@ -34,19 +34,21 @@ public class ExcelToHtmlService { private String today; private Workbook wb; - private int sheetNum; - private int cssRandom; + private int sheetNum; + private int cssRandom; /*是不是完成界面*/ - private boolean completeHTML; - private Formatter out; + private boolean completeHTML; + private Formatter out; /*已经完成范围处理*/ - private boolean gotBounds; - private int firstColumn; - private int endColumn; - private String imageCachePath; - private static final String COL_HEAD_CLASS = "colHeader"; - //private static final String ROW_HEAD_CLASS = "rowHeader"; + private boolean gotBounds; + private int firstColumn; + private int endColumn; + private String imageCachePath; + private boolean showRowNum; + private boolean showColumnHead; + private static final String COL_HEAD_CLASS = "colHeader"; + private static final String ROW_HEAD_CLASS = "rowHeader"; private static final String DEFAULTS_CLASS = "excelDefaults"; @@ -57,9 +59,11 @@ public class ExcelToHtmlService { this.wb = params.getWb(); this.completeHTML = params.isCompleteHTML(); this.sheetNum = params.getSheetNum(); - cssRandom = (int) Math.ceil(Math.random() * 1000); + this.cssRandom = (int) Math.ceil(Math.random() * 1000); this.imageCachePath = params.getPath(); - today = new SimpleDateFormat("yyyy_MM_dd").format(new Date()); + this.showRowNum = params.isShowRowNum(); + this.showColumnHead = params.isShowColumnHead(); + this.today = new SimpleDateFormat("yyyy_MM_dd").format(new Date()); } public String printPage() { @@ -125,17 +129,19 @@ public class ExcelToHtmlService { } private void printSheet(Sheet sheet) { - out.format("%n", DEFAULTS_CLASS, getTableWidth(sheet)); + out.format("
%n", DEFAULTS_CLASS, getTableWidth(sheet)); printCols(sheet); printSheetContent(sheet); out.format("
%n"); } private void printCols(Sheet sheet) { - //out.format("%n"); + if (showRowNum) { + out.format("%n", PoiPublicUtil.getNumDigits(sheet.getLastRowNum()) * 18); + } ensureColumnBounds(sheet); for (int i = firstColumn; i < endColumn; i++) { - out.format("%n", sheet.getColumnWidth(i) / 32); + out.format("%n", sheet.getColumnWidth(i) / 16); } } @@ -143,7 +149,7 @@ public class ExcelToHtmlService { ensureColumnBounds(sheet); int width = 0; for (int i = firstColumn; i < endColumn; i++) { - width = width + (sheet.getColumnWidth(i) / 32); + width = width + (sheet.getColumnWidth(i) / 16); } return width; } @@ -153,11 +159,11 @@ public class ExcelToHtmlService { return; } - Iterator iter = sheet.rowIterator(); - firstColumn = (iter.hasNext() ? Integer.MAX_VALUE : 0); + int lastRow = sheet.getLastRowNum(); + firstColumn = (lastRow > 1 ? Integer.MAX_VALUE : 0); endColumn = 0; - while (iter.hasNext()) { - Row row = iter.next(); + for (int i = 0; i < lastRow; i++) { + Row row = sheet.getRow(lastRow); short firstCell = row.getFirstCellNum(); if (firstCell >= 0) { firstColumn = Math.min(firstColumn, firstCell); @@ -188,20 +194,24 @@ public class ExcelToHtmlService { } private void printSheetContent(Sheet sheet) { - //printColumnHeads(sheet); + if (showColumnHead) { + printColumnHeads(sheet); + } MergedRegionHelper mergedRegionHelper = new MergedRegionHelper(sheet); - CellValueHelper cellValueHelper = new CellValueHelper(wb, cssRandom); + CellValueHelper cellValueHelper = new CellValueHelper(wb, cssRandom); out.format("%n"); - Iterator rows = sheet.rowIterator(); - int rowIndex = 1; + Iterator rows = sheet.rowIterator(); + int rowIndex = 1; while (rows.hasNext()) { Row row = rows.next(); out.format(" %n", row.getHeight() / 15); - //out.format(" %d%n", ROW_HEAD_CLASS, row.getRowNum() + 1); + if (showRowNum) { + out.format(" %d%n", row.getRowNum() + 1); + } for (int i = firstColumn; i < endColumn; i++) { if (mergedRegionHelper.isNeedCreate(rowIndex, i)) { - String content = " "; - CellStyle style = null; + String content = " "; + CellStyle style = null; if (i >= row.getFirstCellNum() && i < row.getLastCellNum()) { Cell cell = row.getCell(i); if (cell != null) { diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/CellValueService.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/CellValueService.java index fb283d3..582da68 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/CellValueService.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/CellValueService.java @@ -15,6 +15,22 @@ */ package cn.afterturn.easypoi.excel.imports; +import cn.afterturn.easypoi.excel.entity.params.ExcelImportEntity; +import cn.afterturn.easypoi.excel.entity.sax.SaxReadCellEntity; +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.IExcelDictHandler; +import cn.afterturn.easypoi.util.PoiPublicUtil; +import cn.afterturn.easypoi.util.PoiReflectorUtil; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.time.DateUtils; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.DateUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.lang.reflect.Method; import java.lang.reflect.Type; import java.math.BigDecimal; @@ -27,29 +43,12 @@ import java.util.Date; import java.util.List; import java.util.Map; -import cn.afterturn.easypoi.handler.inter.IExcelDictHandler; -import cn.afterturn.easypoi.util.PoiReflectorUtil; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.time.DateUtils; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DateUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import cn.afterturn.easypoi.excel.entity.params.ExcelImportEntity; -import cn.afterturn.easypoi.excel.entity.sax.SaxReadCellEntity; -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.util.PoiPublicUtil; - /** * Cell 取值服务 * 判断类型处理数据 1.判断Excel中的类型 2.根据replace替换值 3.handler处理数据 4.判断返回类型转化数据返回 * * @author JueYue - * 2014年6月26日 下午10:42:28 + * 2014年6月26日 下午10:42:28 */ public class CellValueService { @@ -93,14 +92,15 @@ public class CellValueService { } result = getDateData(entity, val); + if (result == null) { + return null; + } } if (("class java.sql.Date").equals(classFullName)) { result = new java.sql.Date(((Date) result).getTime()); - } - if (("class java.sql.Time").equals(classFullName)) { + } else if (("class java.sql.Time").equals(classFullName)) { result = new Time(((Date) result).getTime()); - } - if (("class java.sql.Timestamp").equals(classFullName)) { + } else if (("class java.sql.Timestamp").equals(classFullName)) { result = new Timestamp(((Date) result).getTime()); } } else if (CellType.NUMERIC == cell.getCellType() && DateUtil.isCellDateFormatted(cell)) { @@ -148,7 +148,7 @@ public class CellValueService { private Object readNumericCell(Cell cell) { Object result = null; - double value = cell.getNumericCellValue(); + double value = cell.getNumericCellValue(); if (((int) value) == value) { result = (int) value; } else { @@ -160,11 +160,11 @@ public class CellValueService { /** * 获取日期类型数据 * - * @author JueYue - * 2013年11月26日 * @param entity * @param value * @return + * @author JueYue + * 2013年11月26日 */ private Date getDateData(ExcelImportEntity entity, String value) { if (StringUtils.isNotEmpty(entity.getFormat()) && StringUtils.isNotEmpty(value)) { @@ -190,7 +190,8 @@ public class CellValueService { /** * 获取cell的值 - * @param object + * + * @param object * @param cell * @param excelParams * @param titleString @@ -199,9 +200,9 @@ public class CellValueService { public Object getValue(IExcelDataHandler dataHandler, Object object, String cell, Map excelParams, String titleString, IExcelDictHandler dictHandler) throws Exception { - ExcelImportEntity entity = excelParams.get(titleString); - String classFullName = "class java.lang.Object"; - Class clazz = null; + 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(); @@ -224,7 +225,8 @@ public class CellValueService { /** * 获取cell的值 - * @param object + * + * @param object * @param cell * @param excelParams * @param titleString @@ -233,9 +235,9 @@ public class CellValueService { public Object getValue(IExcelDataHandler dataHandler, Object object, Cell cell, Map excelParams, String titleString, IExcelDictHandler dictHandler) throws Exception { - ExcelImportEntity entity = excelParams.get(titleString); - String classFullName = "class java.lang.Object"; - Class clazz = null; + 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(); @@ -258,6 +260,7 @@ public class CellValueService { /** * 获取cell值 + * * @param dataHandler * @param object * @param cellEntity @@ -271,9 +274,9 @@ public class CellValueService { ExcelImportEntity entity = excelParams.get(titleString); Method setMethod = entity.getMethods() != null && entity.getMethods().size() > 0 ? entity.getMethods().get(entity.getMethods().size() - 1) : entity.getMethod(); - Type[] ts = setMethod.getGenericParameterTypes(); + Type[] ts = setMethod.getGenericParameterTypes(); String classFullName = ts[0].toString(); - Object result = cellEntity.getValue(); + Object result = cellEntity.getValue(); result = handlerSuffix(entity.getSuffix(), result); result = replaceValue(entity.getReplace(), result); result = handlerValue(dataHandler, object, result, titleString); @@ -282,6 +285,7 @@ public class CellValueService { /** * 把后缀删除掉 + * * @param result * @param suffix * @return @@ -405,7 +409,7 @@ public class CellValueService { */ private Object replaceValue(String[] replace, Object result) { if (replace != null && replace.length > 0) { - String temp = String.valueOf(result); + String temp = String.valueOf(result); String[] tempArr; for (int i = 0; i < replace.length; i++) { tempArr = replace[i].split("_"); diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/ExcelImportService.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/ExcelImportService.java index 7971a0b..6a3c1f2 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/ExcelImportService.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/ExcelImportService.java @@ -13,34 +13,6 @@ */ package cn.afterturn.easypoi.excel.imports; -import cn.afterturn.easypoi.handler.inter.IExcelDataModel; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.builder.ReflectionToStringBuilder; -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.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.PictureData; -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.usermodel.WorkbookFactory; -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.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.lang.reflect.Field; -import java.util.*; - import cn.afterturn.easypoi.excel.annotation.ExcelTarget; import cn.afterturn.easypoi.excel.entity.ImportParams; import cn.afterturn.easypoi.excel.entity.params.ExcelCollectionParams; @@ -48,13 +20,31 @@ 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.base.ImportBaseService; +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.IExcelDataModel; import cn.afterturn.easypoi.handler.inter.IExcelModel; import cn.afterturn.easypoi.util.PoiCellUtil; 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.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.util.*; +import java.util.concurrent.ForkJoinPool; /** * Excel 导入服务 @@ -68,7 +58,7 @@ public class ExcelImportService extends ImportBaseService { private CellValueService cellValueServer; - private boolean verifyFail = false; + private boolean verifyFail = false; /** * 异常数据styler */ @@ -76,7 +66,7 @@ public class ExcelImportService extends ImportBaseService { private List successRow; private List failRow; - private List failCollection = new ArrayList(); + private List failCollection = new ArrayList(); public ExcelImportService() { successRow = new ArrayList(); @@ -95,10 +85,10 @@ public class ExcelImportService extends ImportBaseService { * @param pictures * @param params */ - private void addListContinue(Object object, ExcelCollectionParams param, Row row, - Map titlemap, String targetId, - Map pictures, - ImportParams params, StringBuilder errorMsg) throws Exception { + public void addListContinue(Object object, ExcelCollectionParams param, Row row, + Map titlemap, String targetId, + Map 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); @@ -109,7 +99,7 @@ public class ExcelImportService extends ImportBaseService { // 是否需要加上这个对象 boolean isUsed = false; for (int i = row.getFirstCellNum(); i < titlemap.size(); i++) { - Cell cell = row.getCell(i); + Cell cell = row.getCell(i); String titleString = (String) titlemap.get(i); if (param.getExcelParams().containsKey(titleString)) { if (param.getExcelParams().get(titleString).getType() == 2) { @@ -120,7 +110,7 @@ public class ExcelImportService extends ImportBaseService { saveFieldValue(params, entity, cell, param.getExcelParams(), titleString, row); } catch (ExcelImportException e) { // 如果需要去校验就忽略,这个错误,继续执行 - if(params.isNeedVerify() && ExcelImportEnum.GET_VALUE_ERROR.equals(e.getType())){ + if (params.isNeedVerify() && ExcelImportEnum.GET_VALUE_ERROR.equals(e.getType())) { errorMsg.append(" ").append(titleString).append(ExcelImportEnum.GET_VALUE_ERROR.getMsg()); } } @@ -163,13 +153,13 @@ public class ExcelImportService extends ImportBaseService { private List importExcel(Collection result, Sheet sheet, Class pojoClass, ImportParams params, Map pictures) throws Exception { - List collection = new ArrayList(); - Map excelParams = new HashMap(); - List excelCollection = new ArrayList(); - String targetId = null; + List collection = new ArrayList(); + Map excelParams = new HashMap(); + List excelCollection = new ArrayList(); + String targetId = null; i18nHandler = params.getI18nHandler(); if (!Map.class.equals(pojoClass)) { - Field[] fileds = PoiPublicUtil.getClassFields(pojoClass); + Field[] fileds = PoiPublicUtil.getClassFields(pojoClass); ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class); if (etarget != null) { targetId = etarget.value(); @@ -182,10 +172,10 @@ public class ExcelImportService extends ImportBaseService { } Map titlemap = getTitleMap(rows, params, excelCollection, excelParams); checkIsValidTemplate(titlemap, excelParams, params, excelCollection); - Row row = null; - Object object = null; + Row row = null; + Object object = null; String picId; - int readRow = 0; + int readRow = 0; //跳过无效行 for (int i = 0; i < params.getStartRows(); i++) { rows.next(); @@ -194,78 +184,90 @@ public class ExcelImportService extends ImportBaseService { if (excelCollection.size() > 0 && params.getKeyIndex() == null) { params.setKeyIndex(0); } - StringBuilder errorMsg; - while (rows.hasNext() - && (row == null - || sheet.getLastRowNum() - row.getRowNum() > params.getLastOfInvalidRow())) { - if (params.getReadRows() > 0 && readRow > params.getReadRows()) { - break; + if (params.isConcurrentTask()) { + ForkJoinPool forkJoinPool = new ForkJoinPool(); + int endRow = sheet.getLastRowNum() - params.getLastOfInvalidRow(); + if (params.getReadRows() > 0) { + endRow = params.getReadRows(); } - row = rows.next(); - // Fix 如果row为无效行时候跳出 - if (sheet.getLastRowNum() - row.getRowNum() < params.getLastOfInvalidRow()) { - break; - } - errorMsg = new StringBuilder(); - // 判断是集合元素还是不是集合元素,如果是就继续加入这个集合,不是就创建新的对象 - // keyIndex 如果为空就不处理,仍然处理这一行 - if (params.getKeyIndex() != null - && (row.getCell(params.getKeyIndex()) == null - || StringUtils.isEmpty(getKeyValue(row.getCell(params.getKeyIndex())))) - && object != null) { - for (ExcelCollectionParams param : excelCollection) { - addListContinue(object, param, row, titlemap, targetId, pictures, params, errorMsg); + 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 == null + || sheet.getLastRowNum() - row.getRowNum() > params.getLastOfInvalidRow())) { + if (params.getReadRows() > 0 && readRow > params.getReadRows()) { + break; } - } else { - object = PoiPublicUtil.createObject(pojoClass, targetId); - try { - Set keys = titlemap.keySet(); - for (Integer cn : keys) { - Cell cell = row.getCell(cn); - String titleString = (String) titlemap.get(cn); - if (excelParams.containsKey(titleString) || Map.class.equals(pojoClass)) { - if (excelParams.get(titleString) != null - && excelParams.get(titleString).getType() == 2) { - picId = row.getRowNum() + "_" + cn; - saveImage(object, picId, excelParams, titleString, pictures, - params); - } else { - try { - saveFieldValue(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()); + row = rows.next(); + // Fix 如果row为无效行时候跳出 + if (sheet.getLastRowNum() - row.getRowNum() < params.getLastOfInvalidRow()) { + break; + } + errorMsg = new StringBuilder(); + // 判断是集合元素还是不是集合元素,如果是就继续加入这个集合,不是就创建新的对象 + // keyIndex 如果为空就不处理,仍然处理这一行 + if (params.getKeyIndex() != null + && (row.getCell(params.getKeyIndex()) == null + || StringUtils.isEmpty(getKeyValue(row.getCell(params.getKeyIndex())))) + && object != null) { + for (ExcelCollectionParams param : excelCollection) { + addListContinue(object, param, row, titlemap, targetId, pictures, params, errorMsg); + } + } else { + object = PoiPublicUtil.createObject(pojoClass, targetId); + try { + Set keys = titlemap.keySet(); + for (Integer cn : keys) { + Cell cell = row.getCell(cn); + String titleString = (String) titlemap.get(cn); + if (excelParams.containsKey(titleString) || Map.class.equals(pojoClass)) { + if (excelParams.get(titleString) != null + && excelParams.get(titleString).getType() == 2) { + picId = row.getRowNum() + "_" + cn; + saveImage(object, picId, excelParams, titleString, pictures, + params); + } else { + try { + saveFieldValue(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()); + } } } } } - } - //for (int i = row.getFirstCellNum(), le = titlemap.size(); i < le; i++) { + //for (int i = row.getFirstCellNum(), le = titlemap.size(); i < le; i++) { - //} - if (object instanceof IExcelDataModel) { - ((IExcelDataModel) object).setRowNum(row.getRowNum()); - } - for (ExcelCollectionParams param : excelCollection) { - addListContinue(object, param, row, titlemap, targetId, pictures, params, errorMsg); - } - if (verifyingDataValidity(object, row, params, pojoClass, 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); + //} + if (object instanceof IExcelDataModel) { + ((IExcelDataModel) object).setRowNum(row.getRowNum()); + } + for (ExcelCollectionParams param : excelCollection) { + addListContinue(object, param, row, titlemap, targetId, pictures, params, errorMsg); + } + if (verifyingDataValidity(object, row, params, pojoClass, 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); } - } catch (Exception e) { - LOGGER.error("excel import error , row num:{},obj:{}", readRow, ReflectionToStringBuilder.toString(object)); - throw new RuntimeException(e); } + readRow++; } - readRow++; } return collection; } @@ -273,10 +275,10 @@ public class ExcelImportService extends ImportBaseService { /** * 校验数据合法性 */ - private boolean verifyingDataValidity(Object object, Row row, ImportParams params, - Class pojoClass, StringBuilder fieldErrorMsg) { + public boolean verifyingDataValidity(Object object, Row row, ImportParams params, + Class pojoClass, StringBuilder fieldErrorMsg) { boolean isAdd = true; - Cell cell = null; + Cell cell = null; if (params.isNeedVerify()) { String errorMsg = PoiValidationUtil.validation(object, params.getVerifyGroup()); if (StringUtils.isNotEmpty(errorMsg)) { @@ -307,7 +309,7 @@ public class ExcelImportService extends ImportBaseService { verifyFail = true; } } - if((params.isNeedVerify() || params.getVerifyHandler() != null) && fieldErrorMsg.length() > 0){ + if ((params.isNeedVerify() || params.getVerifyHandler() != null) && fieldErrorMsg.length() > 0) { if (object instanceof IExcelModel) { IExcelModel model = (IExcelModel) object; model.setErrorMsg((StringUtils.isNoneBlank(model.getErrorMsg()) @@ -317,7 +319,7 @@ public class ExcelImportService extends ImportBaseService { cell = row.createCell(row.getLastCellNum()); } cell.setCellValue((StringUtils.isNoneBlank(cell.getStringCellValue()) - ? cell.getStringCellValue() + "," : "")+ fieldErrorMsg.toString()); + ? cell.getStringCellValue() + "," : "") + fieldErrorMsg.toString()); isAdd = false; verifyFail = true; } @@ -336,11 +338,11 @@ public class ExcelImportService extends ImportBaseService { private Map getTitleMap(Iterator rows, ImportParams params, List excelCollection, Map excelParams) { - Map titlemap = new LinkedHashMap(); - Iterator cellTitle; - String collectionName = null; + Map titlemap = new LinkedHashMap(); + Iterator cellTitle; + String collectionName = null; ExcelCollectionParams collectionParams = null; - Row row = null; + Row row = null; for (int j = 0; j < params.getHeadRows(); j++) { row = rows.next(); if (row == null) { @@ -348,7 +350,7 @@ public class ExcelImportService extends ImportBaseService { } cellTitle = row.cellIterator(); while (cellTitle.hasNext()) { - Cell cell = cellTitle.next(); + Cell cell = cellTitle.next(); String value = getKeyValue(cell); value = value.replace("\n", ""); int i = cell.getColumnIndex(); @@ -405,12 +407,12 @@ public class ExcelImportService extends ImportBaseService { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Excel import start ,class is {}", pojoClass); } - List result = new ArrayList(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ExcelImportResult importResult; + List result = new ArrayList(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ExcelImportResult importResult; try { byte[] buffer = new byte[1024]; - int len; + int len; while ((len = inputstream.read(buffer)) > -1) { baos.write(buffer, 0, len); } @@ -432,7 +434,7 @@ public class ExcelImportService extends ImportBaseService { for (int i = params.getStartSheetIndex(); i < params.getStartSheetIndex() + params.getSheetNum(); i++) { if (LOGGER.isDebugEnabled()) { - LOGGER.debug(" start to read excel by is ,startTime is {}", System.currentTimeMillis()); + LOGGER.debug(" start to read excel by is ,startTime is {}", new Date()); } if (isXSSFWorkbook) { pictures = PoiPublicUtil.getSheetPictrues07((XSSFSheet) book.getSheetAt(i), @@ -442,11 +444,11 @@ public class ExcelImportService extends ImportBaseService { (HSSFWorkbook) book); } if (LOGGER.isDebugEnabled()) { - LOGGER.debug(" end to read excel by is ,endTime is {}", System.currentTimeMillis()); + 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 {}", System.currentTimeMillis()); + LOGGER.debug(" end to read excel list by sheet ,endTime is {}", new Date()); } if (params.isReadSingleCell()) { readSingleCell(importResult, book.getSheetAt(i), params); @@ -585,9 +587,9 @@ public class ExcelImportService extends ImportBaseService { /** * 保存字段值(获取值,校验值,追加错误信息) */ - private void saveFieldValue(ImportParams params, Object object, Cell cell, - Map excelParams, String titleString, - Row row) throws Exception { + public void saveFieldValue(ImportParams params, Object object, Cell cell, + Map excelParams, String titleString, + Row row) throws Exception { Object value = cellValueServer.getValue(params.getDataHandler(), object, cell, excelParams, titleString, params.getDictHandler()); if (object instanceof Map) { @@ -620,12 +622,12 @@ public class ExcelImportService extends ImportBaseService { if (image == null) { return; } - byte[] data = image.getData(); + 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); + String path = getSaveUrl(excelParams.get(titleString), object); + File savefile = new File(path); if (!savefile.exists()) { savefile.mkdirs(); } diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/recursive/ExcelImportForkJoinWork.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/recursive/ExcelImportForkJoinWork.java new file mode 100644 index 0000000..2f43bc0 --- /dev/null +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/recursive/ExcelImportForkJoinWork.java @@ -0,0 +1,132 @@ +package cn.afterturn.easypoi.excel.imports.recursive; + +import cn.afterturn.easypoi.excel.entity.ImportParams; +import cn.afterturn.easypoi.excel.entity.params.ExcelImportEntity; +import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult; +import cn.afterturn.easypoi.excel.imports.ExcelImportService; +import cn.afterturn.easypoi.exception.excel.ExcelImportException; +import cn.afterturn.easypoi.exception.excel.enums.ExcelImportEnum; +import cn.afterturn.easypoi.handler.inter.IExcelDataModel; +import cn.afterturn.easypoi.util.PoiPublicUtil; +import org.apache.commons.lang3.builder.ReflectionToStringBuilder; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.RecursiveTask; + +/** + * 并行导入计算 + * 支持校验 + * 不支持图片 + * 不支持集合 + * + * @author by jueyue on 19-6-9. + */ +public class ExcelImportForkJoinWork extends RecursiveTask { + + private final static Logger LOGGER = LoggerFactory.getLogger(ExcelImportForkJoinWork.class); + + private int startRow; + private int endRow; + private Sheet sheet; + private ImportParams params; + private Class pojoClass; + private ExcelImportService importService; + private String targetId; + private Map titlemap; + private Map excelParams; + + public ExcelImportForkJoinWork(int startRow, int endRow, Sheet sheet, ImportParams params, + Class pojoClass, ExcelImportService importService, String targetId, + Map titlemap, Map excelParams) { + this.startRow = startRow; + this.endRow = endRow; + this.sheet = sheet; + this.params = params; + this.pojoClass = pojoClass; + this.importService = importService; + this.targetId = targetId; + this.titlemap = titlemap; + this.excelParams = excelParams; + } + + @Override + protected ExcelImportResult compute() { + long length = endRow - startRow; + ExcelImportResult result = null; + if (length <= params.getCritical()) { + LOGGER.debug("excel import concurrent task start {} , end {}", startRow, endRow); + return readRow(); + } else { + int middle = (startRow + endRow) / 2; + ExcelImportForkJoinWork right = new ExcelImportForkJoinWork(startRow, middle, sheet, params, pojoClass, importService, targetId, titlemap, excelParams); + right.fork(); + ExcelImportForkJoinWork left = new ExcelImportForkJoinWork(middle + 1, endRow, sheet, params, pojoClass, importService, targetId, titlemap, excelParams); + left.fork(); + //合并 + result = right.join(); + ExcelImportResult leftResult = left.join(); + result.getList().addAll(leftResult.getList()); + result.getFailList().addAll(leftResult.getFailList()); + } + return result; + } + + private ExcelImportResult readRow() { + StringBuilder errorMsg; + Row row; + Object object; + ExcelImportResult result = new ExcelImportResult(); + result.setFailList(new ArrayList()); + result.setList(new ArrayList()); + for (int i = startRow; i <= endRow; i++) { + row = sheet.getRow(i); + errorMsg = new StringBuilder(); + if (params.getKeyIndex() != null && (row.getCell(params.getKeyIndex()) == null)) { + continue; + } + object = PoiPublicUtil.createObject(pojoClass, targetId); + try { + Set keys = titlemap.keySet(); + for (Integer cn : keys) { + Cell cell = row.getCell(cn); + String titleString = (String) titlemap.get(cn); + if (excelParams.containsKey(titleString) || Map.class.equals(pojoClass)) { + try { + importService.saveFieldValue(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()); + } + if (importService.verifyingDataValidity(object, row, params, pojoClass, errorMsg)) { + result.getList().add(object); + } else { + result.getFailList().add(object); + } + } catch (ExcelImportException e) { + LOGGER.error("excel import error , row num:{},obj:{}", i, 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:{}", i, ReflectionToStringBuilder.toString(object)); + throw new RuntimeException(e); + } + } + return result; + } + +} diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/util/PoiPublicUtil.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/util/PoiPublicUtil.java index dd1ad4a..89421af 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/util/PoiPublicUtil.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/util/PoiPublicUtil.java @@ -1,13 +1,13 @@ /** * Copyright 2013-2015 JueYue (qrb.jueyue@gmail.com) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and @@ -15,51 +15,32 @@ */ package cn.afterturn.easypoi.util; -import static cn.afterturn.easypoi.util.PoiElUtil.*; - -import java.awt.image.BufferedImage; -import java.io.*; -import java.lang.reflect.Field; -import java.math.BigDecimal; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.imageio.ImageIO; - +import cn.afterturn.easypoi.cache.ImageCache; +import cn.afterturn.easypoi.entity.ImageEntity; +import cn.afterturn.easypoi.excel.annotation.Excel; +import cn.afterturn.easypoi.excel.annotation.ExcelCollection; +import cn.afterturn.easypoi.excel.annotation.ExcelEntity; +import cn.afterturn.easypoi.excel.annotation.ExcelIgnore; +import cn.afterturn.easypoi.word.entity.params.ExcelListEntity; import org.apache.commons.lang3.StringUtils; -import org.apache.poi.hssf.usermodel.HSSFClientAnchor; -import org.apache.poi.hssf.usermodel.HSSFPicture; -import org.apache.poi.hssf.usermodel.HSSFPictureData; -import org.apache.poi.hssf.usermodel.HSSFShape; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ooxml.POIXMLDocumentPart; import org.apache.poi.ss.usermodel.PictureData; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFPicture; -import org.apache.poi.xssf.usermodel.XSSFShape; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.usermodel.*; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import cn.afterturn.easypoi.cache.ImageCache; -import cn.afterturn.easypoi.excel.annotation.Excel; -import cn.afterturn.easypoi.excel.annotation.ExcelCollection; -import cn.afterturn.easypoi.excel.annotation.ExcelEntity; -import cn.afterturn.easypoi.excel.annotation.ExcelIgnore; -import cn.afterturn.easypoi.entity.ImageEntity; -import cn.afterturn.easypoi.word.entity.params.ExcelListEntity; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.util.*; + +import static cn.afterturn.easypoi.util.PoiElUtil.END_STR; +import static cn.afterturn.easypoi.util.PoiElUtil.START_STR; /** * EASYPOI 的公共基础类 @@ -74,7 +55,7 @@ public final class PoiPublicUtil { } - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({"unchecked"}) public static Map mapFor(Object... mapping) { Map map = new HashMap(); for (int i = 0; i < mapping.length; i += 2) { @@ -93,7 +74,7 @@ public final class PoiPublicUtil { Object obj = null; try { if (clazz.equals(Map.class)) { - return new LinkedHashMap(); + return new LinkedHashMap(); } obj = clazz.newInstance(); Field[] fields = getClassFields(clazz); @@ -104,10 +85,10 @@ public final class PoiPublicUtil { if (isCollection(field.getType())) { ExcelCollection collection = field.getAnnotation(ExcelCollection.class); PoiReflectorUtil.fromCache(clazz).setValue(obj, field.getName(), - collection.type().newInstance()); + collection.type().newInstance()); } else if (!isJavaClass(field) && !field.getType().isEnum()) { PoiReflectorUtil.fromCache(clazz).setValue(obj, field.getName(), - createObject(field.getType(), targetId)); + createObject(field.getType(), targetId)); } } @@ -127,7 +108,7 @@ public final class PoiPublicUtil { */ public static Field[] getClassFields(Class clazz) { List list = new ArrayList(); - Field[] fields; + Field[] fields; do { fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { @@ -145,11 +126,11 @@ public final class PoiPublicUtil { public static String getFileExtendName(byte[] photoByte) { String strFileExtendName = "JPG"; if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) - && (photoByte[3] == 56) && ((photoByte[4] == 55) || (photoByte[4] == 57)) - && (photoByte[5] == 97)) { + && (photoByte[3] == 56) && ((photoByte[4] == 55) || (photoByte[4] == 57)) + && (photoByte[5] == 97)) { strFileExtendName = "GIF"; } else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) - && (photoByte[9] == 70)) { + && (photoByte[9] == 70)) { strFileExtendName = "JPG"; } else if ((photoByte[0] == 66) && (photoByte[1] == 77)) { strFileExtendName = "BMP"; @@ -169,11 +150,12 @@ public final class PoiPublicUtil { public static boolean hasBom(InputStream in) throws IOException { byte[] head = new byte[3]; in.read(head); - if(head[0]==-17 && head[1]==-69 && head[2] ==-65) { + if (head[0] == -17 && head[1] == -69 && head[2] == -65) { return true; } return false; } + /** * 获取Excel2003图片 * @@ -186,16 +168,16 @@ public final class PoiPublicUtil { public static Map getSheetPictrues03(HSSFSheet sheet, HSSFWorkbook workbook) { Map sheetIndexPicMap = new HashMap(); - List pictures = workbook.getAllPictures(); + List pictures = workbook.getAllPictures(); if (!pictures.isEmpty()) { for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) { HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor(); if (shape instanceof HSSFPicture) { - HSSFPicture pic = (HSSFPicture) shape; - int pictureIndex = pic.getPictureIndex() - 1; - HSSFPictureData picData = pictures.get(pictureIndex); + HSSFPicture pic = (HSSFPicture) shape; + int pictureIndex = pic.getPictureIndex() - 1; + HSSFPictureData picData = pictures.get(pictureIndex); String picIndex = String.valueOf(anchor.getRow1()) + "_" - + String.valueOf(anchor.getCol1()); + + String.valueOf(anchor.getCol1()); sheetIndexPicMap.put(picIndex, picData); } } @@ -219,14 +201,14 @@ public final class PoiPublicUtil { Map sheetIndexPicMap = new HashMap(); for (POIXMLDocumentPart dr : sheet.getRelations()) { if (dr instanceof XSSFDrawing) { - XSSFDrawing drawing = (XSSFDrawing) dr; - List shapes = drawing.getShapes(); + XSSFDrawing drawing = (XSSFDrawing) dr; + List shapes = drawing.getShapes(); for (XSSFShape shape : shapes) { if (shape instanceof XSSFPicture) { - XSSFPicture pic = (XSSFPicture) shape; - XSSFClientAnchor anchor = pic.getPreferredSize(); - CTMarker ctMarker = anchor.getFrom(); - String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol(); + XSSFPicture pic = (XSSFPicture) shape; + XSSFClientAnchor anchor = pic.getPreferredSize(); + CTMarker ctMarker = anchor.getFrom(); + String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol(); sheetIndexPicMap.put(picIndex, pic.getPictureData()); } } @@ -252,15 +234,15 @@ public final class PoiPublicUtil { * @return */ public static boolean isJavaClass(Field field) { - Class fieldType = field.getType(); - boolean isBaseClass = false; + Class fieldType = field.getType(); + boolean isBaseClass = false; if (fieldType.isArray()) { isBaseClass = false; } else if (fieldType.isPrimitive() || fieldType.getPackage() == null - || "java.lang".equals(fieldType.getPackage().getName()) - || "java.math".equals(fieldType.getPackage().getName()) - || "java.sql".equals(fieldType.getPackage().getName()) - || "java.util".equals(fieldType.getPackage().getName())) { + || "java.lang".equals(fieldType.getPackage().getName()) + || "java.math".equals(fieldType.getPackage().getName()) + || "java.sql".equals(fieldType.getPackage().getName()) + || "java.util".equals(fieldType.getPackage().getName())) { isBaseClass = true; } return isBaseClass; @@ -280,19 +262,19 @@ public final class PoiPublicUtil { if (field.getAnnotation(ExcelIgnore.class) != null) { boo = true; } else if (boo && field.getAnnotation(ExcelCollection.class) != null - && isUseInThis(field.getAnnotation(ExcelCollection.class).name(), targetId) - && (exclusionsList == null || !exclusionsList - .contains(field.getAnnotation(ExcelCollection.class).name()))) { + && isUseInThis(field.getAnnotation(ExcelCollection.class).name(), targetId) + && (exclusionsList == null || !exclusionsList + .contains(field.getAnnotation(ExcelCollection.class).name()))) { boo = false; } else if (boo && field.getAnnotation(Excel.class) != null - && isUseInThis(field.getAnnotation(Excel.class).name(), targetId) - && (exclusionsList == null - || !exclusionsList.contains(field.getAnnotation(Excel.class).name()))) { + && isUseInThis(field.getAnnotation(Excel.class).name(), targetId) + && (exclusionsList == null + || !exclusionsList.contains(field.getAnnotation(Excel.class).name()))) { boo = false; } else if (boo && field.getAnnotation(ExcelEntity.class) != null - && isUseInThis(field.getAnnotation(ExcelEntity.class).name(), targetId) - && (exclusionsList == null || !exclusionsList - .contains(field.getAnnotation(ExcelEntity.class).name()))) { + && isUseInThis(field.getAnnotation(ExcelEntity.class).name(), targetId) + && (exclusionsList == null || !exclusionsList + .contains(field.getAnnotation(ExcelEntity.class).name()))) { boo = false; } return boo; @@ -307,7 +289,7 @@ public final class PoiPublicUtil { */ private static boolean isUseInThis(String exportName, String targetId) { return targetId == null || "".equals(exportName) || exportName.indexOf("_") < 0 - || exportName.indexOf(targetId) != -1; + || exportName.indexOf(targetId) != -1; } private static Integer getImageType(String type) { @@ -331,12 +313,12 @@ public final class PoiPublicUtil { *@author JueYue * 2013-11-20 *@param entity - *@return (byte[]) isAndType[0],(Integer)isAndType[1] + *@return (byte[]) isAndType[0],(Integer)isAndType[1] * @throws Exception */ public static Object[] getIsAndType(ImageEntity entity) throws Exception { Object[] result = new Object[2]; - String type; + String type; if (entity.getType().equals(ImageEntity.URL)) { result[0] = ImageCache.getImage(entity.getUrl()); type = entity.getUrl().split("/.")[entity.getUrl().split("/.").length - 1]; @@ -379,11 +361,11 @@ public final class PoiPublicUtil { String params = ""; while (currentText.indexOf(START_STR) != -1) { params = currentText.substring(currentText.indexOf(START_STR) + 2, - currentText.indexOf(END_STR)); + currentText.indexOf(END_STR)); Object obj = PoiElUtil.eval(params.trim(), map); //判断图片或者是集合 if (obj instanceof ImageEntity || obj instanceof List - || obj instanceof ExcelListEntity) { + || obj instanceof ExcelListEntity) { return obj; } else { currentText = currentText.replace(START_STR + params + END_STR, obj.toString()); @@ -414,10 +396,10 @@ public final class PoiPublicUtil { object = ((Map) object).get(paramsArr[index]); } else { object = PoiReflectorUtil.fromCache(object.getClass()).getValue(object, - paramsArr[index]); + paramsArr[index]); } return (index == paramsArr.length - 1) ? (object == null ? "" : object) - : getValueDoWhile(object, paramsArr, ++index); + : getValueDoWhile(object, paramsArr, ++index); } /** @@ -474,4 +456,13 @@ public final class PoiPublicUtil { } } + public static int getNumDigits(int num) { + int count = 0; + while (num > 0) { + num = num / 10; + count++; + } + return count; + } + }