Browse Source

优化读写逻辑

bugfix
zhuangjiaju 5 years ago
parent
commit
8c697950a5
  1. 2
      src/main/java/com/alibaba/excel/ExcelReader.java
  2. 16
      src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java
  3. 3
      src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java
  4. 2
      src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java
  5. 21
      src/main/java/com/alibaba/excel/analysis/v07/SharedStringsTableHandler.java
  6. 6
      src/main/java/com/alibaba/excel/analysis/v07/XlsxHandlerFactory.java
  7. 5
      src/main/java/com/alibaba/excel/analysis/v07/XlsxRowHandler.java
  8. 13
      src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java
  9. 26
      src/main/java/com/alibaba/excel/analysis/v07/handlers/DefaultCellHandler.java
  10. 4
      src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java
  11. 35
      src/main/java/com/alibaba/excel/context/WriteContextImpl.java
  12. 14
      src/main/java/com/alibaba/excel/converters/string/StringNumberConverter.java
  13. 26
      src/main/java/com/alibaba/excel/metadata/CellData.java
  14. 4
      src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java
  15. 2
      src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java
  16. 1
      src/test/java/com/alibaba/easyexcel/test/core/converter/ReadAllConverterData.java
  17. 1
      src/test/java/com/alibaba/easyexcel/test/core/converter/ReadAllConverterDataListener.java
  18. 138
      src/test/java/com/alibaba/easyexcel/test/temp/StyleTest.java
  19. 53
      src/test/java/com/alibaba/easyexcel/test/temp/poi/PoiFormatTest.java
  20. BIN
      src/test/resources/converter/converter03.xls
  21. BIN
      src/test/resources/converter/converter07.xlsx
  22. BIN
      src/test/resources/simple/simple07.xlsx
  23. 1
      update.md

2
src/main/java/com/alibaba/excel/ExcelReader.java

@ -285,7 +285,7 @@ public class ExcelReader {
} }
try { try {
excelAnalyser.finish(); excelAnalyser.finish();
} catch (Exception e) { } catch (Throwable e) {
LOGGER.warn("Destroy object failed", e); LOGGER.warn("Destroy object failed", e);
} }
} }

16
src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java

@ -1,7 +1,5 @@
package com.alibaba.excel.analysis; package com.alibaba.excel.analysis;
import java.io.IOException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -34,7 +32,7 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
} catch (RuntimeException e) { } catch (RuntimeException e) {
finish(); finish();
throw e; throw e;
} catch (Exception e) { } catch (Throwable e) {
finish(); finish();
throw new ExcelAnalysisException(e); throw new ExcelAnalysisException(e);
} }
@ -72,7 +70,7 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
} catch (RuntimeException e) { } catch (RuntimeException e) {
finish(); finish();
throw e; throw e;
} catch (Exception e) { } catch (Throwable e) {
finish(); finish();
throw new ExcelAnalysisException(e); throw new ExcelAnalysisException(e);
} }
@ -88,14 +86,22 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
if (readWorkbookHolder.getReadCache() != null) { if (readWorkbookHolder.getReadCache() != null) {
readWorkbookHolder.getReadCache().destroy(); readWorkbookHolder.getReadCache().destroy();
} }
} catch (Throwable e) {
throw new ExcelAnalysisException("Can not close IO", e);
}
try {
if (analysisContext.readWorkbookHolder().getAutoCloseStream() if (analysisContext.readWorkbookHolder().getAutoCloseStream()
&& readWorkbookHolder.getInputStream() != null) { && readWorkbookHolder.getInputStream() != null) {
readWorkbookHolder.getInputStream().close(); readWorkbookHolder.getInputStream().close();
} }
} catch (Throwable e) {
throw new ExcelAnalysisException("Can not close IO", e);
}
try {
if (readWorkbookHolder.getTempFile() != null) { if (readWorkbookHolder.getTempFile() != null) {
FileUtils.delete(readWorkbookHolder.getTempFile()); FileUtils.delete(readWorkbookHolder.getTempFile());
} }
} catch (IOException e) { } catch (Throwable e) {
throw new ExcelAnalysisException("Can not close IO", e); throw new ExcelAnalysisException("Can not close IO", e);
} }
} }

3
src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java

@ -14,7 +14,10 @@ import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest; import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener; import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener;
import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord; import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
import org.apache.poi.hssf.record.ExtendedFormatRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.StyleRecord;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;

2
src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java

@ -30,6 +30,8 @@ public class NumberRecordHandler extends AbstractXlsRecordHandler {
this.row = numrec.getRow(); this.row = numrec.getRow();
this.column = numrec.getColumn(); this.column = numrec.getColumn();
this.cellData = new CellData(numrec.getValue()); this.cellData = new CellData(numrec.getValue());
this.cellData.setDataFormat(formatListener.getFormatIndex(numrec));
this.cellData.setDataFormatString(formatListener.getFormatString(numrec));
} }
@Override @Override

21
src/main/java/com/alibaba/excel/analysis/v07/SharedStringsTableHandler.java

@ -1,5 +1,6 @@
package com.alibaba.excel.analysis.v07; package com.alibaba.excel.analysis.v07;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.DefaultHandler;
import com.alibaba.excel.cache.ReadCache; import com.alibaba.excel.cache.ReadCache;
@ -11,22 +12,40 @@ import com.alibaba.excel.cache.ReadCache;
*/ */
public class SharedStringsTableHandler extends DefaultHandler { public class SharedStringsTableHandler extends DefaultHandler {
private static final String T_TAG = "t"; private static final String T_TAG = "t";
private static final String SI_TAG = "si";
/**
* The final piece of data
*/
private String currentData; private String currentData;
/**
* Current element data
*/
private String currentElementData;
private ReadCache readCache; private ReadCache readCache;
public SharedStringsTableHandler(ReadCache readCache) { public SharedStringsTableHandler(ReadCache readCache) {
this.readCache = readCache; this.readCache = readCache;
} }
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) {
if (SI_TAG.equals(name)) {
currentData = "";
}
}
@Override @Override
public void endElement(String uri, String localName, String name) { public void endElement(String uri, String localName, String name) {
if (T_TAG.equals(name)) { if (T_TAG.equals(name)) {
currentData += currentElementData;
} else if (SI_TAG.equals(name)) {
readCache.put(currentData); readCache.put(currentData);
} }
} }
@Override @Override
public void characters(char[] ch, int start, int length) { public void characters(char[] ch, int start, int length) {
currentData = new String(ch, start, length); currentElementData = new String(ch, start, length);
} }
} }

6
src/main/java/com/alibaba/excel/analysis/v07/XlsxHandlerFactory.java

@ -3,6 +3,8 @@ package com.alibaba.excel.analysis.v07;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.poi.xssf.model.StylesTable;
import com.alibaba.excel.analysis.v07.handlers.CountRowCellHandler; import com.alibaba.excel.analysis.v07.handlers.CountRowCellHandler;
import com.alibaba.excel.analysis.v07.handlers.DefaultCellHandler; import com.alibaba.excel.analysis.v07.handlers.DefaultCellHandler;
import com.alibaba.excel.analysis.v07.handlers.ProcessResultCellHandler; import com.alibaba.excel.analysis.v07.handlers.ProcessResultCellHandler;
@ -14,10 +16,10 @@ import com.alibaba.excel.context.AnalysisContext;
* @author Dan Zheng * @author Dan Zheng
*/ */
public class XlsxHandlerFactory { public class XlsxHandlerFactory {
public static List<XlsxCellHandler> buildCellHandlers(AnalysisContext analysisContext) { public static List<XlsxCellHandler> buildCellHandlers(AnalysisContext analysisContext, StylesTable stylesTable) {
List<XlsxCellHandler> result = new ArrayList<XlsxCellHandler>(); List<XlsxCellHandler> result = new ArrayList<XlsxCellHandler>();
result.add(new CountRowCellHandler(analysisContext)); result.add(new CountRowCellHandler(analysisContext));
DefaultCellHandler defaultCellHandler = new DefaultCellHandler(analysisContext); DefaultCellHandler defaultCellHandler = new DefaultCellHandler(analysisContext, stylesTable);
result.add(defaultCellHandler); result.add(defaultCellHandler);
result.add(new ProcessResultCellHandler(analysisContext, defaultCellHandler)); result.add(new ProcessResultCellHandler(analysisContext, defaultCellHandler));
return result; return result;

5
src/main/java/com/alibaba/excel/analysis/v07/XlsxRowHandler.java

@ -2,6 +2,7 @@ package com.alibaba.excel.analysis.v07;
import java.util.List; import java.util.List;
import org.apache.poi.xssf.model.StylesTable;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.DefaultHandler;
@ -17,8 +18,8 @@ public class XlsxRowHandler extends DefaultHandler {
private List<XlsxCellHandler> cellHandlers; private List<XlsxCellHandler> cellHandlers;
private XlsxRowResultHolder rowResultHolder; private XlsxRowResultHolder rowResultHolder;
public XlsxRowHandler(AnalysisContext analysisContext) { public XlsxRowHandler(AnalysisContext analysisContext, StylesTable stylesTable) {
this.cellHandlers = XlsxHandlerFactory.buildCellHandlers(analysisContext); this.cellHandlers = XlsxHandlerFactory.buildCellHandlers(analysisContext, stylesTable);
for (XlsxCellHandler cellHandler : cellHandlers) { for (XlsxCellHandler cellHandler : cellHandlers) {
if (cellHandler instanceof XlsxRowResultHolder) { if (cellHandler instanceof XlsxRowResultHolder) {
this.rowResultHolder = (XlsxRowResultHolder)cellHandler; this.rowResultHolder = (XlsxRowResultHolder)cellHandler;

13
src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java

@ -15,6 +15,7 @@ import javax.xml.parsers.SAXParserFactory;
import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.xssf.eventusermodel.XSSFReader; import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFRelation; import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr;
@ -47,6 +48,10 @@ public class XlsxSaxAnalyser implements ExcelExecutor {
private AnalysisContext analysisContext; private AnalysisContext analysisContext;
private List<ReadSheet> sheetList; private List<ReadSheet> sheetList;
private Map<Integer, InputStream> sheetMap; private Map<Integer, InputStream> sheetMap;
/**
* Current style information
*/
private StylesTable stylesTable;
public XlsxSaxAnalyser(AnalysisContext analysisContext) throws Exception { public XlsxSaxAnalyser(AnalysisContext analysisContext) throws Exception {
this.analysisContext = analysisContext; this.analysisContext = analysisContext;
@ -64,9 +69,9 @@ public class XlsxSaxAnalyser implements ExcelExecutor {
analysisSharedStringsTable(sharedStringsTablePackagePart.getInputStream(), readWorkbookHolder); analysisSharedStringsTable(sharedStringsTablePackagePart.getInputStream(), readWorkbookHolder);
XSSFReader xssfReader = new XSSFReader(pkg); XSSFReader xssfReader = new XSSFReader(pkg);
analysisUse1904WindowDate(xssfReader, readWorkbookHolder); analysisUse1904WindowDate(xssfReader, readWorkbookHolder);
stylesTable = xssfReader.getStylesTable();
sheetList = new ArrayList<ReadSheet>(); sheetList = new ArrayList<ReadSheet>();
sheetMap = new HashMap<Integer, InputStream>(); sheetMap = new HashMap<Integer, InputStream>();
XSSFReader.SheetIterator ite = (XSSFReader.SheetIterator)xssfReader.getSheetsData(); XSSFReader.SheetIterator ite = (XSSFReader.SheetIterator)xssfReader.getSheetsData();
@ -94,12 +99,12 @@ public class XlsxSaxAnalyser implements ExcelExecutor {
} }
if (size < USE_MAP_CACHE_SIZE) { if (size < USE_MAP_CACHE_SIZE) {
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.info("Use map cache.size:{}", size); LOGGER.debug("Use map cache.size:{}", size);
} }
readWorkbookHolder.setReadCache(new MapCache()); readWorkbookHolder.setReadCache(new MapCache());
} else { } else {
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.info("Use ehcache.size:{}", size); LOGGER.debug("Use ehcache.size:{}", size);
} }
readWorkbookHolder.setReadCache(new Ehcache()); readWorkbookHolder.setReadCache(new Ehcache());
} }
@ -178,7 +183,7 @@ public class XlsxSaxAnalyser implements ExcelExecutor {
@Override @Override
public void execute() { public void execute() {
parseXmlSource(sheetMap.get(analysisContext.readSheetHolder().getSheetNo()), parseXmlSource(sheetMap.get(analysisContext.readSheetHolder().getSheetNo()),
new XlsxRowHandler(analysisContext)); new XlsxRowHandler(analysisContext, stylesTable));
} }
} }

26
src/main/java/com/alibaba/excel/analysis/v07/handlers/DefaultCellHandler.java

@ -1,5 +1,6 @@
package com.alibaba.excel.analysis.v07.handlers; package com.alibaba.excel.analysis.v07.handlers;
import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_DATA_FORMAT_TAG;
import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_FORMULA_TAG; import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_FORMULA_TAG;
import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_INLINE_STRING_VALUE_TAG; import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_INLINE_STRING_VALUE_TAG;
import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_TAG; import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_TAG;
@ -9,6 +10,9 @@ import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_VALUE_TYPE_TAG;
import java.util.Map; import java.util.Map;
import java.util.TreeMap; import java.util.TreeMap;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
@ -36,9 +40,14 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
private int curCol; private int curCol;
private Map<Integer, CellData> curRowContent = new TreeMap<Integer, CellData>(); private Map<Integer, CellData> curRowContent = new TreeMap<Integer, CellData>();
private CellData currentCellData; private CellData currentCellData;
/**
* Current style information
*/
private StylesTable stylesTable;
public DefaultCellHandler(AnalysisContext analysisContext) { public DefaultCellHandler(AnalysisContext analysisContext, StylesTable stylesTable) {
this.analysisContext = analysisContext; this.analysisContext = analysisContext;
this.stylesTable = stylesTable;
} }
@Override @Override
@ -75,6 +84,21 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
// t is null ,it's means Empty or Number // t is null ,it's means Empty or Number
CellDataTypeEnum type = CellDataTypeEnum.buildFromCellType(attributes.getValue(CELL_VALUE_TYPE_TAG)); CellDataTypeEnum type = CellDataTypeEnum.buildFromCellType(attributes.getValue(CELL_VALUE_TYPE_TAG));
currentCellData = new CellData(type); currentCellData = new CellData(type);
// Put in data transformation information
String dateFormatIndex = attributes.getValue(CELL_DATA_FORMAT_TAG);
if (dateFormatIndex != null) {
int dateFormatIndexInteger = Integer.parseInt(dateFormatIndex);
XSSFCellStyle xssfCellStyle = stylesTable.getStyleAt(dateFormatIndexInteger);
int dataFormat = xssfCellStyle.getDataFormat();
String dataFormatString = xssfCellStyle.getDataFormatString();
currentCellData.setDataFormat(dataFormat);
if (dataFormatString == null) {
currentCellData.setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormat));
} else {
currentCellData.setDataFormatString(dataFormatString);
}
}
} }
// cell is formula // cell is formula
if (CELL_FORMULA_TAG.equals(name)) { if (CELL_FORMULA_TAG.equals(name)) {

4
src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java

@ -11,6 +11,10 @@ public class ExcelXmlConstants {
public static final String ROW_TAG = "row"; public static final String ROW_TAG = "row";
public static final String CELL_TAG = "c"; public static final String CELL_TAG = "c";
public static final String CELL_VALUE_TYPE_TAG = "t"; public static final String CELL_VALUE_TYPE_TAG = "t";
/**
* Number formatted label
*/
public static final String CELL_DATA_FORMAT_TAG = "s";
public static final String CELL_FORMULA_TAG = "f"; public static final String CELL_FORMULA_TAG = "f";
public static final String CELL_VALUE_TAG = "v"; public static final String CELL_VALUE_TAG = "v";
/** /**

35
src/main/java/com/alibaba/excel/context/WriteContextImpl.java

@ -1,6 +1,5 @@
package com.alibaba.excel.context; package com.alibaba.excel.context;
import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -347,19 +346,29 @@ public class WriteContextImpl implements WriteContext {
try { try {
writeWorkbookHolder.getWorkbook().write(writeWorkbookHolder.getOutputStream()); writeWorkbookHolder.getWorkbook().write(writeWorkbookHolder.getOutputStream());
writeWorkbookHolder.getWorkbook().close(); writeWorkbookHolder.getWorkbook().close();
if (writeWorkbookHolder.getAutoCloseStream()) { } catch (Throwable e) {
if (writeWorkbookHolder.getOutputStream() != null) { throw new ExcelGenerateException("Can not close IO", e);
writeWorkbookHolder.getOutputStream().close(); }
} try {
if (writeWorkbookHolder.getTemplateInputStream() != null) { if (writeWorkbookHolder.getAutoCloseStream() && writeWorkbookHolder.getOutputStream() != null) {
writeWorkbookHolder.getTemplateInputStream().close(); writeWorkbookHolder.getOutputStream().close();
} }
} else { } catch (Throwable e) {
if (writeWorkbookHolder.getFile() != null && writeWorkbookHolder.getOutputStream() != null) { throw new ExcelGenerateException("Can not close IO", e);
writeWorkbookHolder.getOutputStream().close(); }
} try {
if (writeWorkbookHolder.getAutoCloseStream() && writeWorkbookHolder.getTemplateInputStream() != null) {
writeWorkbookHolder.getTemplateInputStream().close();
}
} catch (Throwable e) {
throw new ExcelGenerateException("Can not close IO", e);
}
try {
if (!writeWorkbookHolder.getAutoCloseStream() && writeWorkbookHolder.getFile() != null
&& writeWorkbookHolder.getOutputStream() != null) {
writeWorkbookHolder.getOutputStream().close();
} }
} catch (IOException e) { } catch (Throwable e) {
throw new ExcelGenerateException("Can not close IO", e); throw new ExcelGenerateException("Can not close IO", e);
} }
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {

14
src/main/java/com/alibaba/excel/converters/string/StringNumberConverter.java

@ -1,6 +1,7 @@
package com.alibaba.excel.converters.string; package com.alibaba.excel.converters.string;
import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.DateUtil;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
@ -38,6 +39,19 @@ public class StringNumberConverter implements Converter<String> {
contentProperty.getDateTimeFormatProperty().getFormat()); contentProperty.getDateTimeFormatProperty().getFormat());
} }
// If there are "NumberFormat", read as number // If there are "NumberFormat", read as number
if (contentProperty != null && contentProperty.getNumberFormatProperty() != null) {
return NumberUtils.format(cellData.getDoubleValue(), contentProperty);
}
// Excel defines formatting
if (cellData.getDataFormat() != null) {
if (DateUtil.isADateFormat(cellData.getDataFormat(), cellData.getDataFormatString())) {
return DateUtils.format(HSSFDateUtil.getJavaDate(cellData.getDoubleValue(),
globalConfiguration.getUse1904windowing(), null));
} else {
return NumberUtils.format(cellData.getDoubleValue(), contentProperty);
}
}
// Default conversion number
return NumberUtils.format(cellData.getDoubleValue(), contentProperty); return NumberUtils.format(cellData.getDoubleValue(), contentProperty);
} }

26
src/main/java/com/alibaba/excel/metadata/CellData.java

@ -23,6 +23,14 @@ public class CellData {
private Boolean booleanValue; private Boolean booleanValue;
private Boolean formula; private Boolean formula;
private String formulaValue; private String formulaValue;
/**
* The number formatting
*/
private Integer dataFormat;
/**
* The string of number formatting
*/
private String dataFormatString;
public CellData(CellData other) { public CellData(CellData other) {
this.type = other.type; this.type = other.type;
@ -31,6 +39,8 @@ public class CellData {
this.booleanValue = other.booleanValue; this.booleanValue = other.booleanValue;
this.formula = other.formula; this.formula = other.formula;
this.formulaValue = other.formulaValue; this.formulaValue = other.formulaValue;
this.dataFormat = other.dataFormat;
this.dataFormatString = other.dataFormatString;
} }
public CellData(String stringValue) { public CellData(String stringValue) {
@ -123,6 +133,22 @@ public class CellData {
this.formulaValue = formulaValue; this.formulaValue = formulaValue;
} }
public Integer getDataFormat() {
return dataFormat;
}
public void setDataFormat(Integer dataFormat) {
this.dataFormat = dataFormat;
}
public String getDataFormatString() {
return dataFormatString;
}
public void setDataFormatString(String dataFormatString) {
this.dataFormatString = dataFormatString;
}
@Override @Override
public String toString() { public String toString() {
switch (type) { switch (type) {

4
src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java

@ -51,7 +51,7 @@ public class ExcelBuilderImpl implements ExcelBuilder {
} catch (RuntimeException e) { } catch (RuntimeException e) {
finish(); finish();
throw e; throw e;
} catch (Exception e) { } catch (Throwable e) {
finish(); finish();
throw new ExcelGenerateException(e); throw new ExcelGenerateException(e);
} }
@ -88,7 +88,7 @@ public class ExcelBuilderImpl implements ExcelBuilder {
} catch (RuntimeException e) { } catch (RuntimeException e) {
finish(); finish();
throw e; throw e;
} catch (Exception e) { } catch (Throwable e) {
finish(); finish();
throw new ExcelGenerateException(e); throw new ExcelGenerateException(e);
} }

2
src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java

@ -53,7 +53,7 @@ public class ConverterDataTest {
} }
@Test @Test
public void T03ReadAllConverter03() { public void T04ReadAllConverter03() {
readAllConverter("converter" + File.separator + "converter03.xls"); readAllConverter("converter" + File.separator + "converter03.xls");
} }

1
src/test/java/com/alibaba/easyexcel/test/core/converter/ReadAllConverterData.java

@ -42,4 +42,5 @@ public class ReadAllConverterData {
private String stringError; private String stringError;
private String stringFormulaNumber; private String stringFormulaNumber;
private String stringFormulaString; private String stringFormulaString;
private String stringNumberDate;
} }

1
src/test/java/com/alibaba/easyexcel/test/core/converter/ReadAllConverterDataListener.java

@ -64,6 +64,7 @@ public class ReadAllConverterDataListener extends AnalysisEventListener<ReadAllC
Assert.assertEquals(data.getStringBoolean(), "true"); Assert.assertEquals(data.getStringBoolean(), "true");
Assert.assertEquals(data.getStringString(), "测试"); Assert.assertEquals(data.getStringString(), "测试");
Assert.assertEquals(data.getStringError(), "#VALUE!"); Assert.assertEquals(data.getStringError(), "#VALUE!");
Assert.assertEquals(data.getStringNumberDate(), "2020-01-01 01:01:01");
Assert.assertEquals(data.getStringFormulaNumber(), "2.0"); Assert.assertEquals(data.getStringFormulaNumber(), "2.0");
Assert.assertEquals(data.getStringFormulaString(), "1测试"); Assert.assertEquals(data.getStringFormulaString(), "1测试");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0))); LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));

138
src/test/java/com/alibaba/easyexcel/test/temp/StyleTest.java

@ -0,0 +1,138 @@
package com.alibaba.easyexcel.test.temp;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.ExcelStyleDateFormatter;
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.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
/**
* 临时测试
*
* @author Jiaju Zhuang
**/
@Ignore
public class StyleTest {
private static final Logger LOGGER = LoggerFactory.getLogger(StyleTest.class);
@Test
public void test() {
List<Object> list = EasyExcel.read("D:\\test\\styleTest.xls").sheet().headRowNumber(0).doReadSync();
for (Object data : list) {
LOGGER.info("返回数据:{}", JSON.toJSONString(data));
}
}
@Test
public void poi() throws Exception {
InputStream is = new FileInputStream("D:\\test\\styleTest.xls");
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
HSSFRow hssfRow = hssfSheet.getRow(0);
System.out.println(hssfRow.getCell(0).getCellStyle().getDataFormatString());
DataFormatter formatter = new DataFormatter();
System.out.println(hssfRow.getCell(0).getNumericCellValue());
System.out.println(hssfRow.getCell(1).getNumericCellValue());
System.out.println(hssfRow.getCell(2).getNumericCellValue());
System.out.println(hssfRow.getCell(0).getCellStyle().getDataFormatString());
System.out.println(hssfRow.getCell(1).getCellStyle().getDataFormatString());
System.out.println(hssfRow.getCell(2).getCellStyle().getDataFormatString());
}
@Test
public void poi07() throws Exception {
InputStream is = new FileInputStream("D:\\test\\styleTest.xlsx");
Workbook workbook = WorkbookFactory.create(is); // 这种方式 Excel 2003/2007/2010 都是可以处理的
Sheet sheet = workbook.getSheetAt(0);
Row hssfRow = sheet.getRow(0);
System.out.println(hssfRow.getCell(0).getCellStyle().getDataFormatString());
DataFormatter formatter = new DataFormatter();
System.out.println(hssfRow.getCell(0).getNumericCellValue());
System.out.println(hssfRow.getCell(1).getNumericCellValue());
System.out.println(hssfRow.getCell(2).getNumericCellValue());
System.out.println(hssfRow.getCell(0).getCellStyle().getDataFormat());
System.out.println(hssfRow.getCell(1).getCellStyle().getDataFormat());
System.out.println(hssfRow.getCell(2).getCellStyle().getDataFormat());
System.out.println(hssfRow.getCell(3).getCellStyle().getDataFormat());
System.out.println(hssfRow.getCell(0).getCellStyle().getDataFormatString());
System.out.println(hssfRow.getCell(1).getCellStyle().getDataFormatString());
System.out.println(hssfRow.getCell(2).getCellStyle().getDataFormatString());
System.out.println(hssfRow.getCell(3).getCellStyle().getDataFormatString());
isDate(hssfRow.getCell(0));
isDate(hssfRow.getCell(1));
isDate(hssfRow.getCell(2));
isDate(hssfRow.getCell(3));
}
@Test
public void poi0701() throws Exception {
InputStream is = new FileInputStream("D:\\test\\f1.xlsx");
Workbook workbook = WorkbookFactory.create(is); // 这种方式 Excel 2003/2007/2010 都是可以处理的
Sheet sheet = workbook.getSheetAt(0);
print(sheet.getRow(0).getCell(0));
print(sheet.getRow(1).getCell(0));
print(sheet.getRow(2).getCell(0));
print(sheet.getRow(3).getCell(0));
}
private void print(Cell cell) {
System.out.println(
DateUtil.isADateFormat(cell.getCellStyle().getDataFormat(), cell.getCellStyle().getDataFormatString()));
System.out.println(cell.getCellStyle().getDataFormat());
System.out.println(cell.getCellStyle().getDataFormatString());
DataFormatter f = new DataFormatter();
System.out.println(f.formatCellValue(cell));
if (cell.getCellStyle().getDataFormatString() != null) {
}
ExcelStyleDateFormatter ff = new ExcelStyleDateFormatter(cell.getCellStyle().getDataFormatString());
}
@Test
public void testFormatter() throws Exception {
ExcelStyleDateFormatter ff = new ExcelStyleDateFormatter("yyyy年m月d日");
System.out.println(ff.format(new Date()));
}
private void isDate(Cell cell) {
System.out.println(
DateUtil.isADateFormat(cell.getCellStyle().getDataFormat(), cell.getCellStyle().getDataFormatString()));
System.out.println(HSSFDateUtil.isCellDateFormatted(cell));
DataFormatter f = new DataFormatter();
System.out.println(f.formatCellValue(cell));
}
@Test
public void testBuiltinFormats() throws Exception {
System.out.println(BuiltinFormats.getBuiltinFormat(48));
System.out.println(BuiltinFormats.getBuiltinFormat(57));
System.out.println(BuiltinFormats.getBuiltinFormat(28));
}
}

53
src/test/java/com/alibaba/easyexcel/test/temp/poi/PoiFormatTest.java

@ -0,0 +1,53 @@
package com.alibaba.easyexcel.test.temp.poi;
import java.io.File;
import java.io.IOException;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.easyexcel.test.util.TestFileUtil;
/**
* 测试poi
*
* @author Jiaju Zhuang
**/
@Ignore
public class PoiFormatTest {
private static final Logger LOGGER = LoggerFactory.getLogger(PoiFormatTest.class);
@Test
public void lastRowNum() throws IOException {
String file = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(file));
SXSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
LOGGER.info("一共行数:{}", xssfSheet.getLastRowNum());
SXSSFRow row = xssfSheet.getRow(0);
LOGGER.info("第一行数据:{}", row);
xssfSheet.createRow(20);
LOGGER.info("一共行数:{}", xssfSheet.getLastRowNum());
}
@Test
public void lastRowNumXSSF() throws IOException {
String file = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file);
LOGGER.info("一共:{}个sheet", xssfWorkbook.getNumberOfSheets());
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
LOGGER.info("一共行数:{}", xssfSheet.getLastRowNum());
XSSFRow row = xssfSheet.getRow(0);
LOGGER.info("第一行数据:{}", row);
xssfSheet.createRow(20);
LOGGER.info("一共行数:{}", xssfSheet.getLastRowNum());
}
}

BIN
src/test/resources/converter/converter03.xls

Binary file not shown.

BIN
src/test/resources/converter/converter07.xlsx

Binary file not shown.

BIN
src/test/resources/simple/simple07.xlsx

Binary file not shown.

1
update.md

@ -5,6 +5,7 @@
* 极大优化读大文件的内存和效率 * 极大优化读大文件的内存和效率
* sheetNo 改成0开始 * sheetNo 改成0开始
* 读支持指定列名 * 读支持指定列名
* 升级poi 到4.0.1
# 1.2.4 # 1.2.4
修复read()方法存在的bug 修复read()方法存在的bug
# 1.2.1 # 1.2.1

Loading…
Cancel
Save