From 5857d49f044c6884af703ba25adca3fb481f17a8 Mon Sep 17 00:00:00 2001 From: jueyue Date: Sat, 22 Jun 2019 16:29:42 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A5=BD=E5=A5=BD=E5=AD=A6=E4=B9=A0,=E6=8A=8As?= =?UTF-8?q?ax=E5=8E=9F=E7=90=86=E8=AE=A4=E8=AF=81=E7=9C=8B=E4=BA=86?= =?UTF-8?q?=E7=9C=8B,=E6=A2=B3=E7=90=86=E4=BA=86=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=96=B0=E7=9A=84=E7=89=88=E6=9C=AC,=E8=A7=A3=E5=86=B3?= =?UTF-8?q?=E4=BA=86=E4=B8=80=E4=BA=9B=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/entity/enmus/CellValueType.java | 2 +- .../easypoi/excel/entity/sax/SaxConstant.java | 59 ++++++++ .../graph/builder/ExcelChartBuildService.java | 5 +- .../excel/graph/entity/ExcelGraphDefined.java | 9 +- .../excel/imports/CellValueService.java | 2 - .../excel/imports/ExcelImportService.java | 4 +- .../excel/imports/sax/SaxReadExcel.java | 67 +++++---- .../excel/imports/sax/SheetHandler.java | 134 +++++++++++------- .../excel/imports/sax/parse/SaxRowRead.java | 133 +++++++++-------- .../easypoi/util/PoiExcelTempUtil.java | 12 +- 10 files changed, 273 insertions(+), 154 deletions(-) create mode 100644 easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/sax/SaxConstant.java diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/enmus/CellValueType.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/enmus/CellValueType.java index 091de69..ae6f551 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/enmus/CellValueType.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/enmus/CellValueType.java @@ -22,6 +22,6 @@ package cn.afterturn.easypoi.excel.entity.enmus; */ public enum CellValueType { - String , Number , Boolean , Date , TElement , Null , None; + String , Number , Boolean , Date , TElement , Null ,Formula, None; } diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/sax/SaxConstant.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/sax/SaxConstant.java new file mode 100644 index 0000000..5d2056b --- /dev/null +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/entity/sax/SaxConstant.java @@ -0,0 +1,59 @@ +package cn.afterturn.easypoi.excel.entity.sax; + +/** + * @author by jueyue on 19-6-20. + */ +public interface SaxConstant { + + /** + * Row 表达式 + */ + public static String ROW = "row"; + /** + * cell 表达式 + */ + public static String COL = "c"; + /** + * tElement 表达式 + */ + public static String T_ELEMENT = "t"; + /** + * cell 类型 + */ + public static String TYPE = "t"; + /** + * style 缩写 + */ + public static String STYLE = "s"; + /** + * String 缩写 + */ + public static String STRING = "s"; + /** + * date 缩写 + */ + public static String DATE = "d"; + /** + * number 缩写 + */ + public static String NUMBER = "n"; + /** + * 计算表达式 + */ + public static String FORMULA = "str"; + /** + * Boolean 缩写 + */ + public static String BOOLEAN = "b"; + /** + * 类型值为“inlineStr”,表示这个单元格的字符串并没有用共享字符串池子的值 + */ + public static String INLINE_STR = "inlineStr"; + + + /** + * value 缩写 + */ + public static String VALUE = "v"; + +} diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/graph/builder/ExcelChartBuildService.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/graph/builder/ExcelChartBuildService.java index 4bc5db7..cfa22fc 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/graph/builder/ExcelChartBuildService.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/graph/builder/ExcelChartBuildService.java @@ -3,6 +3,7 @@ */ package cn.afterturn.easypoi.excel.graph.builder; +import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; @@ -23,8 +24,6 @@ import org.apache.poi.ss.usermodel.charts.ScatterChartData; import org.apache.poi.ss.usermodel.charts.ValueAxis; import org.apache.poi.ss.util.CellRangeAddress; -import com.google.common.collect.Lists; - import cn.afterturn.easypoi.excel.graph.constant.ExcelGraphElementType; import cn.afterturn.easypoi.excel.graph.constant.ExcelGraphType; import cn.afterturn.easypoi.excel.graph.entity.ExcelGraph; @@ -97,7 +96,7 @@ public class ExcelChartBuildService } List valueList=graph.getValueList(); - List> chartValueList=Lists.newArrayList(); + List> chartValueList= new ArrayList<>(); if(valueList!=null&&valueList.size()>0){ for(ExcelGraphElement ele:valueList){ ChartDataSource source=DataSources.fromNumericCellRange(dataSourceSheet, new CellRangeAddress(ele.getStartRowNum(),ele.getEndRowNum(),ele.getStartColNum(),ele.getEndColNum())); diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/graph/entity/ExcelGraphDefined.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/graph/entity/ExcelGraphDefined.java index 7bd5ca2..64265ce 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/graph/entity/ExcelGraphDefined.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/graph/entity/ExcelGraphDefined.java @@ -3,10 +3,9 @@ */ package cn.afterturn.easypoi.excel.graph.entity; +import java.util.ArrayList; import java.util.List; -import com.google.common.collect.Lists; - import cn.afterturn.easypoi.excel.graph.constant.ExcelGraphType; /** @@ -18,10 +17,10 @@ import cn.afterturn.easypoi.excel.graph.constant.ExcelGraphType; public class ExcelGraphDefined implements ExcelGraph { private ExcelGraphElement category; - public List valueList=Lists.newArrayList(); - public List titleCell=Lists.newArrayList(); + public List valueList= new ArrayList<>(); + public List titleCell= new ArrayList<>(); private Integer graphType=ExcelGraphType.LINE_CHART; - public List title=Lists.newArrayList(); + public List title= new ArrayList<>(); @Override public ExcelGraphElement getCategory() 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 fb474c4..93661ba 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 @@ -106,8 +106,6 @@ public class CellValueService { } else if (("class java.sql.Timestamp").equals(classFullName)) { result = new Timestamp(((Date) result).getTime()); } - } else if (CellType.NUMERIC == cell.getCellType() && DateUtil.isCellDateFormatted(cell)) { - result = DateUtil.getJavaDate(cell.getNumericCellValue()); } else { switch (cell.getCellType()) { case STRING: 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 2acc509..de5cd69 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 @@ -178,7 +178,7 @@ public class ExcelImportService extends ImportBaseService { Row row = null; Object object = null; String picId; - int readRow = 0; + int readRow = 1; //跳过无效行 for (int i = 0; i < params.getStartRows(); i++) { rows.next(); @@ -214,7 +214,7 @@ public class ExcelImportService extends ImportBaseService { if (row.getLastCellNum()<0) { continue; } - if(isMap) { + if(isMap && object != null) { ((Map) object).put("excelRowNum", row.getRowNum()); } errorMsg = new StringBuilder(); diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/sax/SaxReadExcel.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/sax/SaxReadExcel.java index 4fc25ec..92d1888 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/sax/SaxReadExcel.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/sax/SaxReadExcel.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,14 +15,15 @@ */ package cn.afterturn.easypoi.excel.imports.sax; -import java.io.InputStream; -import java.util.Iterator; -import java.util.List; - +import cn.afterturn.easypoi.excel.entity.ImportParams; +import cn.afterturn.easypoi.excel.imports.sax.parse.ISaxRowRead; +import cn.afterturn.easypoi.excel.imports.sax.parse.SaxRowRead; +import cn.afterturn.easypoi.exception.excel.ExcelImportException; import cn.afterturn.easypoi.handler.inter.IReadHandler; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.model.SharedStringsTable; +import org.apache.poi.xssf.model.StylesTable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.ContentHandler; @@ -31,15 +32,15 @@ import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; -import cn.afterturn.easypoi.excel.entity.ImportParams; -import cn.afterturn.easypoi.excel.imports.sax.parse.ISaxRowRead; -import cn.afterturn.easypoi.excel.imports.sax.parse.SaxRowRead; -import cn.afterturn.easypoi.exception.excel.ExcelImportException; +import java.io.InputStream; +import java.util.Iterator; +import java.util.List; /** * 基于SAX Excel大数据读取,读取Excel 07版本,不支持图片读取 + * * @author JueYue - * 2014年12月29日 下午9:41:38 + * 2014年12月29日 下午9:41:38 * @version 1.0 */ @SuppressWarnings("rawtypes") @@ -61,20 +62,26 @@ public class SaxReadExcel { private List readExcel(OPCPackage opcPackage, Class pojoClass, ImportParams params, ISaxRowRead rowRead, IReadHandler handler) { try { - XSSFReader xssfReader = new XSSFReader(opcPackage); - SharedStringsTable sst = xssfReader.getSharedStringsTable(); + XSSFReader xssfReader = new XSSFReader(opcPackage); + SharedStringsTable sharedStringsTable = xssfReader.getSharedStringsTable(); + StylesTable stylesTable = xssfReader.getStylesTable(); if (rowRead == null) { rowRead = new SaxRowRead(pojoClass, params, handler); } - XMLReader parser = fetchSheetParser(sst, rowRead); - Iterator sheets = xssfReader.getSheetsData(); - int sheetIndex = 0; - while (sheets.hasNext() && sheetIndex < params.getSheetNum()) { + XMLReader parser = fetchSheetParser(sharedStringsTable, stylesTable, rowRead); + Iterator sheets = xssfReader.getSheetsData(); + int sheetIndex = 0; + while (sheets.hasNext() && sheetIndex < params.getSheetNum() + params.getStartSheetIndex()) { + if (sheetIndex < params.getStartSheetIndex()) { + sheets.next(); + } else { + InputStream sheet = sheets.next(); + InputSource sheetSource = new InputSource(sheet); + parser.parse(sheetSource); + sheet.close(); + } sheetIndex++; - InputStream sheet = sheets.next(); - InputSource sheetSource = new InputSource(sheet); - parser.parse(sheetSource); - sheet.close(); + } if (handler != null) { handler.doAfterAll(); @@ -86,10 +93,10 @@ public class SaxReadExcel { } } - private XMLReader fetchSheetParser(SharedStringsTable sst, + private XMLReader fetchSheetParser(SharedStringsTable sharedStringsTable, StylesTable stylesTable, ISaxRowRead rowRead) throws SAXException { - XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); - ContentHandler handler = new SheetHandler(sst, rowRead); + XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); + ContentHandler handler = new SheetHandler(sharedStringsTable, stylesTable, rowRead); parser.setContentHandler(handler); return parser; } diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/sax/SheetHandler.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/sax/SheetHandler.java index 4d5393a..b087b20 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/sax/SheetHandler.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/sax/SheetHandler.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,48 +15,50 @@ */ package cn.afterturn.easypoi.excel.imports.sax; -import java.math.BigDecimal; -import java.util.Date; -import java.util.List; - +import cn.afterturn.easypoi.excel.entity.enmus.CellValueType; +import cn.afterturn.easypoi.excel.entity.sax.SaxReadCellEntity; +import cn.afterturn.easypoi.excel.imports.sax.parse.ISaxRowRead; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; +import org.apache.poi.xssf.model.StylesTable; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; -import com.google.common.collect.Lists; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; -import cn.afterturn.easypoi.excel.entity.enmus.CellValueType; -import cn.afterturn.easypoi.excel.entity.sax.SaxReadCellEntity; -import cn.afterturn.easypoi.excel.imports.sax.parse.ISaxRowRead; +import static cn.afterturn.easypoi.excel.entity.sax.SaxConstant.*; /** * 回调接口 + * * @author JueYue - * 2014年12月29日 下午9:50:09 + * 2014年12月29日 下午9:50:09 */ public class SheetHandler extends DefaultHandler { - private SharedStringsTable sst; - private String lastContents; + private SharedStringsTable sharedStringsTable; + private StylesTable stylesTable; + private String lastContents; - //当前行 - private int curRow = 0; - //当前列 - private int curCol = 0; + /** 当前行**/ + private int curRow = 0; + /**当前列 **/ + private int curCol = 0; - private CellValueType type; + private CellValueType type; - private ISaxRowRead read; + private ISaxRowRead read; - //存储行记录的容器 - private List rowlist = Lists.newArrayList(); + private List rowList = new ArrayList<>(); - public SheetHandler(SharedStringsTable sst, ISaxRowRead rowRead) { - this.sst = sst; + public SheetHandler(SharedStringsTable sharedStringsTable, StylesTable stylesTable, ISaxRowRead rowRead) { + this.sharedStringsTable = sharedStringsTable; + this.stylesTable = stylesTable; this.read = rowRead; } @@ -65,22 +67,50 @@ public class SheetHandler extends DefaultHandler { Attributes attributes) throws SAXException { // 置空 lastContents = ""; - // c => 单元格 - if ("c".equals(name)) { - // 如果下一个元素是 SST 的索引,则将nextIsString标记为true - String cellType = attributes.getValue("t"); - if ("s".equals(cellType)) { + if (COL.equals(name)) { + String cellType = attributes.getValue(TYPE); + if (STRING.equals(cellType)) { type = CellValueType.String; return; } - //日期格式 - cellType = attributes.getValue("s"); - if ("1".equals(cellType)) { + if (BOOLEAN.equals(cellType)) { + type = CellValueType.Boolean; + return; + } + if (DATE.equals(cellType)) { type = CellValueType.Date; - } else if ("2".equals(cellType)) { + return; + } + if (INLINE_STR.equals(cellType)) { + type = CellValueType.String; + return; + } + if (FORMULA.equals(cellType)) { + type = CellValueType.Formula; + return; + } + if (NUMBER.equals(cellType)) { type = CellValueType.Number; + return; } - } else if ("t".equals(name)) {//当元素为t时 + try { + short nfId = (short) stylesTable.getCellXfAt(Integer.parseInt(attributes.getValue(STYLE))).getNumFmtId(); + String numberFormat = stylesTable.getNumberFormats().get(nfId).toUpperCase(); + if (StringUtils.isNotEmpty(numberFormat)) { + if (numberFormat.contains("Y") || numberFormat.contains("M") || numberFormat.contains("D") + || numberFormat.contains("H") || numberFormat.contains("S") || numberFormat.contains("年") + || numberFormat.contains("月") || numberFormat.contains("日") || numberFormat.contains("时") + || numberFormat.contains("分") || numberFormat.contains("秒")) { + type = CellValueType.Date; + return; + } + } + } catch (NumberFormatException e) { + + } + // 没别的了就是数字了 + type = CellValueType.Number; + } else if (T_ELEMENT.equals(name)) { type = CellValueType.TElement; } @@ -94,7 +124,7 @@ public class SheetHandler extends DefaultHandler { if (CellValueType.String.equals(type)) { try { int idx = Integer.parseInt(lastContents); - lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); + lastContents = sharedStringsTable.getItemAt(idx).getString(); } catch (Exception e) { } @@ -102,36 +132,36 @@ public class SheetHandler extends DefaultHandler { //t元素也包含字符串 if (CellValueType.TElement.equals(type)) { String value = lastContents.trim(); - rowlist.add(curCol, new SaxReadCellEntity(CellValueType.String, value)); + rowList.add(curCol, new SaxReadCellEntity(CellValueType.String, value)); curCol++; type = CellValueType.None; // v => 单元格的值,如果单元格是字符串则v标签的值为该字符串在SST中的索引 // 将单元格内容加入rowlist中,在这之前先去掉字符串前后的空白符 - } else if ("v".equals(name)) { + } else if (VALUE.equals(name)) { String value = lastContents.trim(); value = "".equals(value) ? " " : value; if (CellValueType.Date.equals(type)) { Date date = HSSFDateUtil.getJavaDate(Double.valueOf(value)); - rowlist.add(curCol, new SaxReadCellEntity(CellValueType.Date, date)); + rowList.add(curCol, new SaxReadCellEntity(CellValueType.Date, date)); } else if (CellValueType.Number.equals(type)) { BigDecimal bd = new BigDecimal(value); - rowlist.add(curCol, new SaxReadCellEntity(CellValueType.Number, bd)); + rowList.add(curCol, new SaxReadCellEntity(CellValueType.Number, bd)); } else if (CellValueType.String.equals(type)) { - rowlist.add(curCol, new SaxReadCellEntity(CellValueType.String, value)); + rowList.add(curCol, new SaxReadCellEntity(CellValueType.String, value)); } curCol++; //如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法 - } else if("c".equals(name) && StringUtils.isEmpty(lastContents)){ - rowlist.add(curCol,new SaxReadCellEntity(CellValueType.String,"")); + } else if (COL.equals(name) && StringUtils.isEmpty(lastContents)) { + rowList.add(curCol, new SaxReadCellEntity(CellValueType.String, "")); curCol++; - } else if ("row".equals(name)) { - read.parse(curRow, rowlist); - rowlist.clear(); + } else if (ROW.equals(name)) { + read.parse(curRow, rowList); + rowList.clear(); curRow++; curCol = 0; } - } + } @Override public void characters(char[] ch, int start, int length) throws SAXException { diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/sax/parse/SaxRowRead.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/sax/parse/SaxRowRead.java index d46403e..7a61dcf 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/sax/parse/SaxRowRead.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/excel/imports/sax/parse/SaxRowRead.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,20 +15,6 @@ */ package cn.afterturn.easypoi.excel.imports.sax.parse; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import cn.afterturn.easypoi.handler.inter.IReadHandler; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.Lists; - import cn.afterturn.easypoi.excel.annotation.ExcelTarget; import cn.afterturn.easypoi.excel.entity.ImportParams; import cn.afterturn.easypoi.excel.entity.params.ExcelCollectionParams; @@ -37,58 +23,77 @@ import cn.afterturn.easypoi.excel.entity.sax.SaxReadCellEntity; import cn.afterturn.easypoi.excel.imports.CellValueService; import cn.afterturn.easypoi.excel.imports.base.ImportBaseService; import cn.afterturn.easypoi.exception.excel.ExcelImportException; +import cn.afterturn.easypoi.handler.inter.IReadHandler; import cn.afterturn.easypoi.util.PoiPublicUtil; import cn.afterturn.easypoi.util.PoiReflectorUtil; +import com.google.common.collect.Lists; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.Field; +import java.util.*; /** * 当行读取数据 + * * @author JueYue - * 2015年1月1日 下午7:59:39 + * 2015年1月1日 下午7:59:39 */ -@SuppressWarnings({ "rawtypes", "unchecked" }) +@SuppressWarnings({"rawtypes", "unchecked"}) public class SaxRowRead extends ImportBaseService implements ISaxRowRead { - private static final Logger LOGGER = LoggerFactory - .getLogger(SaxRowRead.class); - /** 需要返回的数据 **/ - private List list; - /** 导出的对象 **/ - private Class pojoClass; - /** 导入参数 **/ - private ImportParams params; - /** 列表头对应关系 **/ - private Map titlemap = new HashMap(); - /** 当前的对象**/ - private Object object = null; + private static final Logger LOGGER = LoggerFactory + .getLogger(SaxRowRead.class); + /** + * 需要返回的数据 + **/ + private List list; + /** + * 导出的对象 + **/ + private Class pojoClass; + /** + * 导入参数 + **/ + private ImportParams params; + /** + * 列表头对应关系 + **/ + private Map titlemap = new HashMap(); + /** + * 当前的对象 + **/ + private Object object = null; - private Map excelParams = new HashMap(); + private Map excelParams = new HashMap(); - private List excelCollection = new ArrayList(); + private List excelCollection = new ArrayList(); - private String targetId; + private String targetId; private CellValueService cellValueServer; - private IReadHandler hanlder; + private IReadHandler handler; - public SaxRowRead(Class pojoClass, ImportParams params, IReadHandler hanlder) { + public SaxRowRead(Class pojoClass, ImportParams params, IReadHandler handler) { list = Lists.newArrayList(); this.params = params; this.pojoClass = pojoClass; cellValueServer = new CellValueService(); - this.hanlder = hanlder; + this.handler = handler; initParams(pojoClass, params); } private void initParams(Class pojoClass, ImportParams params) { try { - Field[] fileds = PoiPublicUtil.getClassFields(pojoClass); + 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); + getAllExcelField(targetId, fileds, excelParams, excelCollection, pojoClass, null, null); } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new ExcelImportException(e.getMessage()); @@ -125,33 +130,38 @@ public class SaxRowRead extends ImportBaseService implements ISaxRowRead { /** * 集合元素处理 + * * @param datas */ private void addListData(List datas) throws Exception { // 判断是集合元素还是不是集合元素,如果是就继续加入这个集合,不是就创建新的对象 if (params.getKeyIndex() != null && (datas.get(params.getKeyIndex()) == null - || StringUtils.isEmpty(String.valueOf(datas.get(params.getKeyIndex()).getValue()))) - && object != null) { + || StringUtils.isEmpty(String.valueOf(datas.get(params.getKeyIndex()).getValue()))) + && object != null) { for (ExcelCollectionParams param : excelCollection) { addListContinue(object, param, datas, titlemap, targetId, params); } } else { - object = PoiPublicUtil.createObject(pojoClass, targetId); + if (Map.class.equals(pojoClass)) { + object = new HashMap<>(); + } else { + object = PoiPublicUtil.createObject(pojoClass, targetId); + } SaxReadCellEntity entity; for (int i = 0, le = datas.size(); i < le; i++) { entity = datas.get(i); String titleString = (String) titlemap.get(i); - if (excelParams.containsKey(titleString)) { + if (excelParams.containsKey(titleString) || Map.class.equals(pojoClass)) { saveFieldValue(params, object, entity, excelParams, titleString); } } - if (object != null && hanlder != null) { - hanlder.handler(object); + if (object != null && handler != null) { + handler.handler(object); } for (ExcelCollectionParams param : excelCollection) { addListContinue(object, param, datas, titlemap, targetId, params); } - if (hanlder == null) { + if (handler == null) { list.add(object); } } @@ -160,6 +170,7 @@ public class SaxRowRead extends ImportBaseService implements ISaxRowRead { /** * 向List里面继续添加元素 + * * @param object * @param param * @param datas @@ -172,9 +183,9 @@ public class SaxRowRead extends ImportBaseService implements ISaxRowRead { List datas, Map titlemap, String targetId, ImportParams params) throws Exception { Collection collection = (Collection) PoiReflectorUtil.fromCache(pojoClass).getValue(object, - param.getName()); - Object entity = PoiPublicUtil.createObject(param.getType(), targetId); - boolean isUsed = false;// 是否需要加上这个对象 + param.getName()); + Object entity = PoiPublicUtil.createObject(param.getType(), targetId); + boolean isUsed = false; for (int i = 0; i < datas.size(); i++) { String titleString = (String) titlemap.get(i); if (param.getExcelParams().containsKey(titleString)) { @@ -189,23 +200,29 @@ public class SaxRowRead extends ImportBaseService implements ISaxRowRead { /** * 设置值 + * * @param params * @param object * @param entity * @param excelParams * @param titleString - * @throws Exception + * @throws Exception */ private void saveFieldValue(ImportParams params, Object object, SaxReadCellEntity entity, Map excelParams, String titleString) throws Exception { - Object value = cellValueServer.getValue(params.getDataHandler(), object, entity, - excelParams, titleString); - setValues(excelParams.get(titleString), object, value); + if (Map.class.equals(pojoClass)) { + ((Map)object).put(titleString,entity.getValue()); + } else { + Object value = cellValueServer.getValue(params.getDataHandler(), object, entity, + excelParams, titleString); + setValues(excelParams.get(titleString), object, value); + } } /** * put 表头数据 + * * @param datas */ private void addHeadData(List datas) { diff --git a/easypoi-base/src/main/java/cn/afterturn/easypoi/util/PoiExcelTempUtil.java b/easypoi-base/src/main/java/cn/afterturn/easypoi/util/PoiExcelTempUtil.java index 53869e6..ad3be5d 100644 --- a/easypoi-base/src/main/java/cn/afterturn/easypoi/util/PoiExcelTempUtil.java +++ b/easypoi-base/src/main/java/cn/afterturn/easypoi/util/PoiExcelTempUtil.java @@ -1,5 +1,6 @@ package cn.afterturn.easypoi.util; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import java.util.Date; @@ -23,10 +24,19 @@ public class PoiExcelTempUtil { * @param endRow */ public static void reset(Sheet sheet, int startRow, int endRow) { + if (sheet.getWorkbook() instanceof HSSFWorkbook) { + return; + } for (int i = startRow; i <= endRow; i++) { - Row row = sheet.getRow(i); + Row row = sheet.getRow(i); + if (row == null) { + continue; + } int cellNum = row.getLastCellNum(); for (int j = 0; j < cellNum; j++) { + if (row.getCell(j) == null) { + continue; + } Map map = copyCell(row.getCell(j)); row.removeCell(row.getCell(j)); Cell cell = row.createCell(j);