Browse Source

兼容03

bugfix
zhuangjiaju 5 years ago
parent
commit
49a0174330
  1. 8
      pom.xml
  2. 4
      src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java
  3. 8
      src/main/java/com/alibaba/excel/analysis/v03/AbstractXlsRecordHandler.java
  4. 4
      src/main/java/com/alibaba/excel/analysis/v03/XlsRecordHandler.java
  5. 38
      src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java
  6. 6
      src/main/java/com/alibaba/excel/analysis/v03/handlers/BlankOrErrorRecordHandler.java
  7. 26
      src/main/java/com/alibaba/excel/analysis/v03/handlers/FormulaRecordHandler.java
  8. 3
      src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelRecordHandler.java
  9. 4
      src/main/java/com/alibaba/excel/analysis/v03/handlers/MissingCellDummyRecordHandler.java
  10. 5
      src/main/java/com/alibaba/excel/analysis/v03/handlers/NoteRecordHandler.java
  11. 4
      src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java
  12. 4
      src/main/java/com/alibaba/excel/analysis/v03/handlers/RkRecordHandler.java
  13. 7
      src/main/java/com/alibaba/excel/analysis/v03/handlers/SstRecordHandler.java
  14. 4
      src/main/java/com/alibaba/excel/analysis/v07/XlsxRowResultHolder.java
  15. 24
      src/main/java/com/alibaba/excel/analysis/v07/handlers/DefaultCellHandler.java
  16. 5
      src/main/java/com/alibaba/excel/analysis/v07/handlers/ProcessResultCellHandler.java
  17. 19
      src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java
  18. 16
      src/main/java/com/alibaba/excel/converters/Converter.java
  19. 3
      src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java
  20. 1
      src/main/java/com/alibaba/excel/read/builder/ExcelReaderSheetBuilder.java
  21. 6
      src/main/java/com/alibaba/excel/read/listener/event/AnalysisFinishEvent.java
  22. 18
      src/main/java/com/alibaba/excel/read/listener/event/EachRowAnalysisFinishEvent.java
  23. 2
      src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java
  24. 2
      src/main/java/com/alibaba/excel/util/DateUtils.java
  25. 5
      src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java
  26. 10
      src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java
  27. 11
      src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java
  28. 7
      src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java
  29. 22
      src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java
  30. 2
      src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java
  31. 2
      src/main/java/com/alibaba/excel/write/metadata/holder/WriteHolder.java
  32. 35
      src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java
  33. 86
      src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java
  34. 7
      src/main/java/com/alibaba/excel/write/style/AbstractColumnCellStyleStrategy.java
  35. 4
      src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java
  36. 4
      src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java
  37. 16
      src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationData.java
  38. 74
      src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java
  39. 36
      src/test/java/com/alibaba/easyexcel/test/core/annotation/SimpleDataListener.java
  40. 35
      src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java
  41. 50
      src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataListener.java
  42. 58
      src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java
  43. 53
      src/test/java/com/alibaba/easyexcel/test/core/converter/ReadConverterData.java
  44. 6
      src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleData.java
  45. 4
      src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataListener.java
  46. 54
      src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java
  47. 1
      src/test/java/com/alibaba/easyexcel/test/util/TestFileUtil.java
  48. BIN
      src/test/resources/simple/simple07Test.xlsx

8
pom.xml

@ -152,14 +152,6 @@
<goal>check</goal> <goal>check</goal>
</goals> </goals>
</execution> </execution>
<!-- 绑定pmd:pmd到site生命周期 -->
<execution>
<id>pmd-pmd-site</id>
<phase>site</phase>
<goals>
<goal>pmd</goal>
</goals>
</execution>
</executions> </executions>
<dependencies> <dependencies>
<dependency> <dependency>

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

@ -79,7 +79,9 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
} }
ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder(); ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder();
try { try {
readWorkbookHolder.getReadCache().destroy(); if (readWorkbookHolder.getReadCache() != null) {
readWorkbookHolder.getReadCache().destroy();
}
if (analysisContext.readWorkbookHolder().getAutoCloseStream() if (analysisContext.readWorkbookHolder().getAutoCloseStream()
&& readWorkbookHolder.getInputStream() != null) { && readWorkbookHolder.getInputStream() != null) {
readWorkbookHolder.getInputStream().close(); readWorkbookHolder.getInputStream().close();

8
src/main/java/com/alibaba/excel/analysis/v03/AbstractXlsRecordHandler.java

@ -1,5 +1,7 @@
package com.alibaba.excel.analysis.v03; package com.alibaba.excel.analysis.v03;
import com.alibaba.excel.metadata.CellData;
/** /**
* *
* @author Dan Zheng * @author Dan Zheng
@ -7,7 +9,7 @@ package com.alibaba.excel.analysis.v03;
public abstract class AbstractXlsRecordHandler implements XlsRecordHandler { public abstract class AbstractXlsRecordHandler implements XlsRecordHandler {
protected int row = -1; protected int row = -1;
protected int column = -1; protected int column = -1;
protected String value = null; protected CellData cellData;
@Override @Override
public int getRow() { public int getRow() {
@ -20,8 +22,8 @@ public abstract class AbstractXlsRecordHandler implements XlsRecordHandler {
} }
@Override @Override
public String getValue() { public CellData getCellData() {
return value; return cellData;
} }
@Override @Override

4
src/main/java/com/alibaba/excel/analysis/v03/XlsRecordHandler.java

@ -2,6 +2,8 @@ package com.alibaba.excel.analysis.v03;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.metadata.CellData;
/** /**
* Intercepts handle xls reads. * Intercepts handle xls reads.
* *
@ -47,7 +49,7 @@ public interface XlsRecordHandler extends Comparable<XlsRecordHandler> {
* *
* @return * @return
*/ */
String getValue(); CellData getCellData();
/** /**
* Get order * Get order

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

@ -27,9 +27,12 @@ import com.alibaba.excel.analysis.v03.handlers.NumberRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.RkRecordHandler; import com.alibaba.excel.analysis.v03.handlers.RkRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.SstRecordHandler; import com.alibaba.excel.analysis.v03.handlers.SstRecordHandler;
import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.exception.ExcelAnalysisException; import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.read.listener.event.EachRowAnalysisFinishEvent; import com.alibaba.excel.read.listener.event.EachRowAnalysisFinishEvent;
import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder; import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder;
import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.CollectionUtils;
@ -53,13 +56,13 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
private POIFSFileSystem fs; private POIFSFileSystem fs;
private int lastRowNumber; private int lastRowNumber;
private int lastColumnNumber; private int lastColumnNumber;
private boolean notAllEmpty = false;
/** /**
* For parsing Formulas * For parsing Formulas
*/ */
private EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener; private EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener;
private FormatTrackingHSSFListener formatListener; private FormatTrackingHSSFListener formatListener;
private List<String> records; private List<CellData> records;
private boolean notAllEmpty = false;
private List<ReadSheet> sheets = new ArrayList<ReadSheet>(); private List<ReadSheet> sheets = new ArrayList<ReadSheet>();
private HSSFWorkbook stubWorkbook; private HSSFWorkbook stubWorkbook;
private List<XlsRecordHandler> recordHandlers = new ArrayList<XlsRecordHandler>(); private List<XlsRecordHandler> recordHandlers = new ArrayList<XlsRecordHandler>();
@ -67,13 +70,14 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
public XlsSaxAnalyser(AnalysisContext context) throws IOException { public XlsSaxAnalyser(AnalysisContext context) throws IOException {
this.analysisContext = context; this.analysisContext = context;
this.records = new ArrayList<String>(); this.records = new ArrayList<CellData>();
ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder(); ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder();
if (readWorkbookHolder.getFile() != null) { if (readWorkbookHolder.getFile() != null) {
this.fs = new POIFSFileSystem(readWorkbookHolder.getFile()); this.fs = new POIFSFileSystem(readWorkbookHolder.getFile());
} else { } else {
this.fs = new POIFSFileSystem(readWorkbookHolder.getInputStream()); this.fs = new POIFSFileSystem(readWorkbookHolder.getInputStream());
} }
} }
@Override @Override
@ -110,8 +114,7 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
private void init() { private void init() {
lastRowNumber = 0; lastRowNumber = 0;
lastColumnNumber = 0; lastColumnNumber = 0;
records = new ArrayList<String>(); records = new ArrayList<CellData>();
notAllEmpty = false;
sheets = new ArrayList<ReadSheet>(); sheets = new ArrayList<ReadSheet>();
buildXlsRecordHandlers(); buildXlsRecordHandlers();
} }
@ -120,25 +123,28 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
public void processRecord(Record record) { public void processRecord(Record record) {
int thisRow = -1; int thisRow = -1;
int thisColumn = -1; int thisColumn = -1;
String thisStr = null; CellData cellData = null;
for (XlsRecordHandler handler : this.recordHandlers) { for (XlsRecordHandler handler : this.recordHandlers) {
if (handler.support(record)) { if (handler.support(record)) {
handler.processRecord(record); handler.processRecord(record);
thisRow = handler.getRow(); thisRow = handler.getRow();
thisColumn = handler.getColumn(); thisColumn = handler.getColumn();
thisStr = handler.getValue(); cellData = handler.getCellData();
if (cellData != null) {
records.add(cellData);
}
break; break;
} }
} }
// If we got something to print out, do so // If we got something to print out, do so
if (thisStr != null) { if (cellData != null) {
if (analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()) { if (analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()
thisStr = thisStr.trim(); && CellDataTypeEnum.STRING == cellData.getType()) {
cellData.setStringValue(cellData.getStringValue().trim());
} }
if (!"".equals(thisStr)) { if (CellDataTypeEnum.EMPTY != cellData.getType()) {
notAllEmpty = true; notAllEmpty = true;
} }
records.add(thisStr);
} }
// Handle new row // Handle new row
@ -161,17 +167,17 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
// Handle end of row // Handle end of row
if (record instanceof LastCellOfRowDummyRecord) { if (record instanceof LastCellOfRowDummyRecord) {
int row = ((LastCellOfRowDummyRecord)record).getRow(); int row = ((LastCellOfRowDummyRecord)record).getRow();
if (lastColumnNumber == -1) { if (lastColumnNumber == -1) {
lastColumnNumber = 0; lastColumnNumber = 0;
} }
if (notAllEmpty) { if (notAllEmpty) {
analysisContext.readSheetHolder() analysisContext.readRowHolder(
.notifyEndOneRow(new EachRowAnalysisFinishEvent(new ArrayList<String>(records)), analysisContext); new ReadRowHolder(lastRowNumber, analysisContext.readSheetHolder().getGlobalConfiguration()));
analysisContext.readSheetHolder().notifyEndOneRow(new EachRowAnalysisFinishEvent(records),
analysisContext);
} }
records.clear(); records.clear();
lastColumnNumber = -1; lastColumnNumber = -1;
notAllEmpty = false;
} }
} }

6
src/main/java/com/alibaba/excel/analysis/v03/handlers/BlankOrErrorRecordHandler.java

@ -5,6 +5,8 @@ import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
/** /**
* Record handler * Record handler
@ -24,12 +26,12 @@ public class BlankOrErrorRecordHandler extends AbstractXlsRecordHandler {
BlankRecord br = (BlankRecord)record; BlankRecord br = (BlankRecord)record;
this.row = br.getRow(); this.row = br.getRow();
this.column = br.getColumn(); this.column = br.getColumn();
this.value = ""; this.cellData = new CellData(CellDataTypeEnum.EMPTY);
} else if (record.getSid() == BoolErrRecord.sid) { } else if (record.getSid() == BoolErrRecord.sid) {
BoolErrRecord ber = (BoolErrRecord)record; BoolErrRecord ber = (BoolErrRecord)record;
this.row = ber.getRow(); this.row = ber.getRow();
this.column = ber.getColumn(); this.column = ber.getColumn();
this.value = ""; this.cellData = new CellData(CellDataTypeEnum.EMPTY);
} }
} }

26
src/main/java/com/alibaba/excel/analysis/v03/handlers/FormulaRecordHandler.java

@ -1,13 +1,13 @@
package com.alibaba.excel.analysis.v03.handlers; package com.alibaba.excel.analysis.v03.handlers;
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener; import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.hssf.record.FormulaRecord; import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.StringRecord; import org.apache.poi.hssf.record.StringRecord;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.metadata.CellData;
/** /**
* Record handler * Record handler
@ -17,10 +17,6 @@ import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
public class FormulaRecordHandler extends AbstractXlsRecordHandler { public class FormulaRecordHandler extends AbstractXlsRecordHandler {
private int nextRow; private int nextRow;
private int nextColumn; private int nextColumn;
/**
* Should we output the formula, or the value it has?
*/
private boolean outputFormulaValues = true;
private boolean outputNextStringRecord; private boolean outputNextStringRecord;
private FormatTrackingHSSFListener formatListener; private FormatTrackingHSSFListener formatListener;
private HSSFWorkbook stubWorkbook; private HSSFWorkbook stubWorkbook;
@ -43,24 +39,20 @@ public class FormulaRecordHandler extends AbstractXlsRecordHandler {
this.row = frec.getRow(); this.row = frec.getRow();
this.column = frec.getColumn(); this.column = frec.getColumn();
if (outputFormulaValues) { if (Double.isNaN(frec.getValue())) {
if (Double.isNaN(frec.getValue())) { // Formula result is a string
// Formula result is a string // This is stored in the next record
// This is stored in the next record outputNextStringRecord = true;
outputNextStringRecord = true; nextRow = frec.getRow();
nextRow = frec.getRow(); nextColumn = frec.getColumn();
nextColumn = frec.getColumn();
} else {
this.value = formatListener.formatNumberDateCell(frec);
}
} else { } else {
this.value = HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()); this.cellData = new CellData(frec.getValue());
} }
} else if (record.getSid() == StringRecord.sid) { } else if (record.getSid() == StringRecord.sid) {
if (outputNextStringRecord) { if (outputNextStringRecord) {
// String for formula // String for formula
StringRecord srec = (StringRecord)record; StringRecord srec = (StringRecord)record;
this.value = srec.getString(); this.cellData = new CellData(srec.getString());
this.row = nextRow; this.row = nextRow;
this.column = nextColumn; this.column = nextColumn;
outputNextStringRecord = false; outputNextStringRecord = false;

3
src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelRecordHandler.java

@ -4,6 +4,7 @@ import org.apache.poi.hssf.record.LabelRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.metadata.CellData;
/** /**
* Record handler * Record handler
@ -21,7 +22,7 @@ public class LabelRecordHandler extends AbstractXlsRecordHandler {
LabelRecord lrec = (LabelRecord)record; LabelRecord lrec = (LabelRecord)record;
this.row = lrec.getRow(); this.row = lrec.getRow();
this.column = lrec.getColumn(); this.column = lrec.getColumn();
this.value = lrec.getValue(); this.cellData = new CellData(lrec.getValue());
} }
@Override @Override

4
src/main/java/com/alibaba/excel/analysis/v03/handlers/MissingCellDummyRecordHandler.java

@ -4,6 +4,8 @@ import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
/** /**
* Record handler * Record handler
@ -26,7 +28,7 @@ public class MissingCellDummyRecordHandler extends AbstractXlsRecordHandler {
MissingCellDummyRecord mcdr = (MissingCellDummyRecord)record; MissingCellDummyRecord mcdr = (MissingCellDummyRecord)record;
this.row = mcdr.getRow(); this.row = mcdr.getRow();
this.column = mcdr.getColumn(); this.column = mcdr.getColumn();
this.value = ""; this.cellData = new CellData(CellDataTypeEnum.EMPTY);
} }
@Override @Override

5
src/main/java/com/alibaba/excel/analysis/v03/handlers/NoteRecordHandler.java

@ -4,6 +4,8 @@ import org.apache.poi.hssf.record.NoteRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
/** /**
* Record handler * Record handler
@ -19,10 +21,9 @@ public class NoteRecordHandler extends AbstractXlsRecordHandler {
@Override @Override
public void processRecord(Record record) { public void processRecord(Record record) {
NoteRecord nrec = (NoteRecord)record; NoteRecord nrec = (NoteRecord)record;
this.row = nrec.getRow(); this.row = nrec.getRow();
this.column = nrec.getColumn(); this.column = nrec.getColumn();
this.value = "(TODO)"; this.cellData = new CellData(CellDataTypeEnum.EMPTY);
} }
@Override @Override

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

@ -5,6 +5,7 @@ import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.metadata.CellData;
/** /**
* Record handler * Record handler
@ -28,8 +29,7 @@ public class NumberRecordHandler extends AbstractXlsRecordHandler {
NumberRecord numrec = (NumberRecord)record; NumberRecord numrec = (NumberRecord)record;
this.row = numrec.getRow(); this.row = numrec.getRow();
this.column = numrec.getColumn(); this.column = numrec.getColumn();
// Format this.cellData = new CellData(numrec.getValue());
this.value = formatListener.formatNumberDateCell(numrec);
} }
@Override @Override

4
src/main/java/com/alibaba/excel/analysis/v03/handlers/RkRecordHandler.java

@ -4,6 +4,8 @@ import org.apache.poi.hssf.record.RKRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
/** /**
* Record handler * Record handler
@ -22,7 +24,7 @@ public class RkRecordHandler extends AbstractXlsRecordHandler {
this.row = rkrec.getRow(); this.row = rkrec.getRow();
this.row = rkrec.getColumn(); this.row = rkrec.getColumn();
this.value = ""; this.cellData = new CellData(CellDataTypeEnum.EMPTY);
} }
@Override @Override

7
src/main/java/com/alibaba/excel/analysis/v03/handlers/SstRecordHandler.java

@ -5,6 +5,8 @@ import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.SSTRecord; import org.apache.poi.hssf.record.SSTRecord;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
/** /**
* Record handler * Record handler
@ -25,13 +27,12 @@ public class SstRecordHandler extends AbstractXlsRecordHandler {
sstRecord = (SSTRecord)record; sstRecord = (SSTRecord)record;
} else if (record.getSid() == LabelSSTRecord.sid) { } else if (record.getSid() == LabelSSTRecord.sid) {
LabelSSTRecord lsrec = (LabelSSTRecord)record; LabelSSTRecord lsrec = (LabelSSTRecord)record;
this.row = lsrec.getRow(); this.row = lsrec.getRow();
this.column = lsrec.getColumn(); this.column = lsrec.getColumn();
if (sstRecord == null) { if (sstRecord == null) {
this.value = ""; this.cellData = new CellData(CellDataTypeEnum.EMPTY);
} else { } else {
this.value = sstRecord.getString(lsrec.getSSTIndex()).toString(); this.cellData = new CellData(sstRecord.getString(lsrec.getSSTIndex()).toString());
} }
} }
} }

4
src/main/java/com/alibaba/excel/analysis/v07/XlsxRowResultHolder.java

@ -1,5 +1,7 @@
package com.alibaba.excel.analysis.v07; package com.alibaba.excel.analysis.v07;
import java.util.List;
import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.CellData;
/** /**
@ -25,7 +27,7 @@ public interface XlsxRowResultHolder {
* *
* @return * @return
*/ */
CellData[] getCurRowContent(); List<CellData> getCurRowContent();
/** /**
* get column size * get column size

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

@ -6,7 +6,8 @@ import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_TAG;
import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_VALUE_TAG; import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_VALUE_TAG;
import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_VALUE_TYPE_TAG; import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_VALUE_TYPE_TAG;
import java.util.Arrays; import java.util.ArrayList;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
@ -33,7 +34,7 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
private String currentCellIndex; private String currentCellIndex;
private int curRow; private int curRow;
private int curCol; private int curCol;
private CellData[] curRowContent = new CellData[20]; private List<CellData> curRowContent = new ArrayList<CellData>();
private CellData currentCellData; private CellData currentCellData;
public DefaultCellHandler(AnalysisContext analysisContext) { public DefaultCellHandler(AnalysisContext analysisContext) {
@ -42,7 +43,7 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
@Override @Override
public void clearResult() { public void clearResult() {
curRowContent = new CellData[20]; curRowContent.clear();
} }
@Override @Override
@ -69,6 +70,7 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
// t="inlineStr" ,it's means String // t="inlineStr" ,it's means String
// t="b" ,it's means Boolean // t="b" ,it's means Boolean
// t="e" ,it's means Error // t="e" ,it's means Error
// t="n" ,it's means Number
// 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);
@ -82,7 +84,6 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
@Override @Override
public void endHandle(String name) { public void endHandle(String name) {
if (CELL_VALUE_TAG.equals(name)) { if (CELL_VALUE_TAG.equals(name)) {
ensureSize();
// Have to go "sharedStrings.xml" and get it // Have to go "sharedStrings.xml" and get it
if (currentCellData.getType() == CellDataTypeEnum.STRING) { if (currentCellData.getType() == CellDataTypeEnum.STRING) {
String stringValue = analysisContext.readWorkbookHolder().getReadCache() String stringValue = analysisContext.readWorkbookHolder().getReadCache()
@ -92,25 +93,17 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
} }
currentCellData.setStringValue(stringValue); currentCellData.setStringValue(stringValue);
} }
curRowContent[curCol] = currentCellData; curRowContent.set(curCol, currentCellData);
} }
// This is a special form of string // This is a special form of string
if (CELL_INLINE_STRING_VALUE_TAG.equals(name)) { if (CELL_INLINE_STRING_VALUE_TAG.equals(name)) {
ensureSize();
XSSFRichTextString richTextString = new XSSFRichTextString(currentCellData.getStringValue()); XSSFRichTextString richTextString = new XSSFRichTextString(currentCellData.getStringValue());
String stringValue = richTextString.toString(); String stringValue = richTextString.toString();
if (stringValue != null && analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()) { if (stringValue != null && analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
stringValue = stringValue.trim(); stringValue = stringValue.trim();
} }
currentCellData.setStringValue(stringValue); currentCellData.setStringValue(stringValue);
curRowContent[curCol] = currentCellData; curRowContent.set(curCol, currentCellData);
}
}
private void ensureSize() {
// try to size
if (curCol >= curRowContent.length) {
curRowContent = Arrays.copyOf(curRowContent, (int)(curCol * 1.5));
} }
} }
@ -135,6 +128,7 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
case BOOLEAN: case BOOLEAN:
currentCellData.setBooleanValue(BooleanUtils.valueOf(currentCellValue)); currentCellData.setBooleanValue(BooleanUtils.valueOf(currentCellValue));
break; break;
case NUMBER:
case EMPTY: case EMPTY:
currentCellData.setType(CellDataTypeEnum.NUMBER); currentCellData.setType(CellDataTypeEnum.NUMBER);
currentCellData.setDoubleValue(Double.valueOf(currentCellValue)); currentCellData.setDoubleValue(Double.valueOf(currentCellValue));
@ -145,7 +139,7 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
} }
@Override @Override
public CellData[] getCurRowContent() { public List<CellData> getCurRowContent() {
return this.curRowContent; return this.curRowContent;
} }

5
src/main/java/com/alibaba/excel/analysis/v07/handlers/ProcessResultCellHandler.java

@ -33,9 +33,8 @@ public class ProcessResultCellHandler implements XlsxCellHandler {
@Override @Override
public void endHandle(String name) { public void endHandle(String name) {
analysisContext.readSheetHolder().notifyEndOneRow( analysisContext.readSheetHolder()
new EachRowAnalysisFinishEvent(rowResultHandler.getCurRowContent(), rowResultHandler.getColumnSize()), .notifyEndOneRow(new EachRowAnalysisFinishEvent(rowResultHandler.getCurRowContent()), analysisContext);
analysisContext);
rowResultHandler.clearResult(); rowResultHandler.clearResult();
} }

19
src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java

@ -6,6 +6,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.alibaba.excel.analysis.ExcelExecutor; import com.alibaba.excel.analysis.ExcelExecutor;
import com.alibaba.excel.analysis.v07.XlsxSaxAnalyser;
import com.alibaba.excel.exception.ExcelAnalysisException; import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.read.metadata.ReadSheet;
@ -65,6 +66,24 @@ public class AnalysisContextImpl implements AnalysisContext {
} }
private void selectSheet(ExcelExecutor excelExecutor) { private void selectSheet(ExcelExecutor excelExecutor) {
if (excelExecutor instanceof XlsxSaxAnalyser) {
selectSheet07(excelExecutor);
} else {
selectSheet03();
}
}
private void selectSheet03() {
if (readSheetHolder.getSheetNo() != null && readSheetHolder.getSheetNo() >= 0) {
return;
}
if (!StringUtils.isEmpty(readSheetHolder.getSheetName())) {
LOGGER.warn("Excel 2003 does not support matching sheets by name, defaults to the first one.");
}
readSheetHolder.setSheetNo(0);
}
private void selectSheet07(ExcelExecutor excelExecutor) {
if (readSheetHolder.getSheetNo() != null && readSheetHolder.getSheetNo() >= 0) { if (readSheetHolder.getSheetNo() != null && readSheetHolder.getSheetNo() >= 0) {
for (ReadSheet readSheetExcel : excelExecutor.sheetList()) { for (ReadSheet readSheetExcel : excelExecutor.sheetList()) {
if (readSheetExcel.getSheetNo().equals(readSheetHolder.getSheetNo())) { if (readSheetExcel.getSheetNo().equals(readSheetHolder.getSheetNo())) {

16
src/main/java/com/alibaba/excel/converters/Converter.java

@ -4,8 +4,6 @@ import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
/** /**
* Convert between Java objects and excel objects * Convert between Java objects and excel objects
@ -33,23 +31,29 @@ public interface Converter<T> {
* Convert excel objects to Java objects * Convert excel objects to Java objects
* *
* @param cellData * @param cellData
* NotNull
* @param contentProperty * @param contentProperty
* Nullable
* @param globalConfiguration * @param globalConfiguration
* NotNull
* @return * @return
* @throws Exception * @throws Exception
*/ */
T convertToJavaData(@NotNull CellData cellData, @Nullable ExcelContentProperty contentProperty, T convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
@NotNull GlobalConfiguration globalConfiguration) throws Exception; GlobalConfiguration globalConfiguration) throws Exception;
/** /**
* Convert Java objects to excel objects * Convert Java objects to excel objects
* *
* @param value * @param value
* NotNull
* @param contentProperty * @param contentProperty
* Nullable
* @param globalConfiguration * @param globalConfiguration
* NotNull
* @return * @return
* @throws Exception * @throws Exception
*/ */
CellData convertToExcelData(@NotNull T value, @Nullable ExcelContentProperty contentProperty, CellData convertToExcelData(T value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration)
@NotNull GlobalConfiguration globalConfiguration) throws Exception; throws Exception;
} }

3
src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java

@ -33,12 +33,13 @@ public enum CellDataTypeEnum {
*/ */
ERROR; ERROR;
private static final Map<String, CellDataTypeEnum> TYPE_ROUTING_MAP = new HashMap<String, CellDataTypeEnum>(8); private static final Map<String, CellDataTypeEnum> TYPE_ROUTING_MAP = new HashMap<String, CellDataTypeEnum>(16);
static { static {
TYPE_ROUTING_MAP.put("s", STRING); TYPE_ROUTING_MAP.put("s", STRING);
TYPE_ROUTING_MAP.put("inlineStr", STRING); TYPE_ROUTING_MAP.put("inlineStr", STRING);
TYPE_ROUTING_MAP.put("e", ERROR); TYPE_ROUTING_MAP.put("e", ERROR);
TYPE_ROUTING_MAP.put("b", BOOLEAN); TYPE_ROUTING_MAP.put("b", BOOLEAN);
TYPE_ROUTING_MAP.put("n", NUMBER);
} }
/** /**

1
src/main/java/com/alibaba/excel/read/builder/ExcelReaderSheetBuilder.java

@ -184,6 +184,7 @@ public class ExcelReaderSheetBuilder {
SyncReadListener syncReadListener = new SyncReadListener(); SyncReadListener syncReadListener = new SyncReadListener();
registerReadListener(syncReadListener); registerReadListener(syncReadListener);
excelReader.read(build()); excelReader.read(build());
excelReader.finish();
return syncReadListener.getList(); return syncReadListener.getList();
} }

6
src/main/java/com/alibaba/excel/read/listener/event/AnalysisFinishEvent.java

@ -1,5 +1,9 @@
package com.alibaba.excel.read.listener.event; package com.alibaba.excel.read.listener.event;
import java.util.List;
import com.alibaba.excel.metadata.CellData;
/** /**
* *
* Event * Event
@ -12,5 +16,5 @@ public interface AnalysisFinishEvent {
* *
* @return * @return
*/ */
Object getAnalysisResult(); List<CellData> getAnalysisResult();
} }

18
src/main/java/com/alibaba/excel/read/listener/event/EachRowAnalysisFinishEvent.java

@ -1,6 +1,5 @@
package com.alibaba.excel.read.listener.event; package com.alibaba.excel.read.listener.event;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.CellData;
@ -9,24 +8,13 @@ import com.alibaba.excel.metadata.CellData;
* @author jipengfei * @author jipengfei
*/ */
public class EachRowAnalysisFinishEvent implements AnalysisFinishEvent { public class EachRowAnalysisFinishEvent implements AnalysisFinishEvent {
private Object result; private List<CellData> result;
public EachRowAnalysisFinishEvent(Object content) { public EachRowAnalysisFinishEvent(List<CellData> content) {
this.result = content; this.result = content;
} }
public EachRowAnalysisFinishEvent(CellData[] content, int length) {
if (content != null) {
List<CellData> ls = new ArrayList<CellData>(length);
for (int i = 0; i <= length; i++) {
ls.add(content[i]);
}
result = ls;
}
}
@Override @Override
public Object getAnalysisResult() { public List<CellData> getAnalysisResult() {
return result; return result;
} }
} }

2
src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java

@ -107,7 +107,7 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
@Override @Override
public void notifyEndOneRow(AnalysisFinishEvent event, AnalysisContext analysisContext) { public void notifyEndOneRow(AnalysisFinishEvent event, AnalysisContext analysisContext) {
List<CellData> cellDataList = (List<CellData>)event.getAnalysisResult(); List<CellData> cellDataList = event.getAnalysisResult();
ReadRowHolder readRowHolder = analysisContext.readRowHolder(); ReadRowHolder readRowHolder = analysisContext.readRowHolder();
readRowHolder.setCurrentRowAnalysisResult(cellDataList); readRowHolder.setCurrentRowAnalysisResult(cellDataList);

2
src/main/java/com/alibaba/excel/util/DateUtils.java

@ -43,7 +43,7 @@ public class DateUtils {
* @throws ParseException * @throws ParseException
*/ */
public static Date parseDate(String dateString) throws ParseException { public static Date parseDate(String dateString) throws ParseException {
return parseDate(switchDateFormat(dateString), null); return parseDate(dateString, switchDateFormat(dateString));
} }
/** /**

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

@ -256,7 +256,10 @@ public class ExcelBuilderImpl implements ExcelBuilder {
if (value instanceof String && currentWriteHolder.globalConfiguration().getAutoTrim()) { if (value instanceof String && currentWriteHolder.globalConfiguration().getAutoTrim()) {
value = ((String)value).trim(); value = ((String)value).trim();
} }
Converter converter = excelContentProperty.getConverter(); Converter converter = null;
if (excelContentProperty != null) {
converter = excelContentProperty.getConverter();
}
if (converter == null) { if (converter == null) {
converter = currentWriteHolder.converterMap().get(ConverterKeyBuild.buildKey(clazz)); converter = currentWriteHolder.converterMap().get(ConverterKeyBuild.buildKey(clazz));
} }

10
src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java

@ -1,8 +1,6 @@
package com.alibaba.excel.write.builder; package com.alibaba.excel.write.builder;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.URI; import java.net.URI;
@ -11,7 +9,6 @@ import java.util.List;
import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteWorkbook; import com.alibaba.excel.write.metadata.WriteWorkbook;
@ -138,11 +135,8 @@ public class ExcelWriterBuilder {
} }
public ExcelWriterBuilder file(File outputFile) { public ExcelWriterBuilder file(File outputFile) {
try { writeWorkbook.setFile(outputFile);
return file(new FileOutputStream(outputFile)); return this;
} catch (FileNotFoundException e) {
throw new ExcelGenerateException("Can not create file", e);
}
} }
public ExcelWriterBuilder file(String outputPathName) { public ExcelWriterBuilder file(String outputPathName) {

11
src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java

@ -6,7 +6,6 @@ import org.apache.poi.ss.usermodel.Row;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.sun.istack.internal.Nullable;
/** /**
* intercepts handle cell creation * intercepts handle cell creation
@ -20,24 +19,26 @@ public interface CellWriteHandler extends WriteHandler {
* *
* @param writeSheetHolder * @param writeSheetHolder
* @param writeTableHolder * @param writeTableHolder
* Nullable
* @param row * @param row
* @param head * @param head
* @param relativeRowIndex * @param relativeRowIndex
* @param isHead * @param isHead
*/ */
void beforeCellCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, Row row, void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head,
Head head, int relativeRowIndex, boolean isHead); int relativeRowIndex, boolean isHead);
/** /**
* called after the cell is created * called after the cell is created
* *
* @param writeSheetHolder * @param writeSheetHolder
* @param writeTableHolder * @param writeTableHolder
* Nullable
* @param cell * @param cell
* @param head * @param head
* @param relativeRowIndex * @param relativeRowIndex
* @param isHead * @param isHead
*/ */
void afterCellCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, Cell cell, void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head,
Head head, int relativeRowIndex, boolean isHead); int relativeRowIndex, boolean isHead);
} }

7
src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java

@ -4,7 +4,6 @@ import org.apache.poi.ss.usermodel.Row;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.sun.istack.internal.Nullable;
/** /**
* intercepts handle row creation * intercepts handle row creation
@ -18,11 +17,12 @@ public interface RowWriteHandler extends WriteHandler {
* *
* @param writeSheetHolder * @param writeSheetHolder
* @param writeTableHolder * @param writeTableHolder
* Nullable
* @param rowIndex * @param rowIndex
* @param relativeRowIndex * @param relativeRowIndex
* @param isHead * @param isHead
*/ */
void beforeRowCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, int rowIndex, void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, int rowIndex,
int relativeRowIndex, boolean isHead); int relativeRowIndex, boolean isHead);
/** /**
@ -30,10 +30,11 @@ public interface RowWriteHandler extends WriteHandler {
* *
* @param writeSheetHolder * @param writeSheetHolder
* @param writeTableHolder * @param writeTableHolder
* Nullable
* @param row * @param row
* @param relativeRowIndex * @param relativeRowIndex
* @param isHead * @param isHead
*/ */
void afterRowCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, Row row, void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
int relativeRowIndex, boolean isHead); int relativeRowIndex, boolean isHead);
} }

22
src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java

@ -17,21 +17,27 @@ public class WriteWorkbook extends WriteBasicParameter {
* Excel type.The default is xlsx * Excel type.The default is xlsx
*/ */
private ExcelTypeEnum excelType; private ExcelTypeEnum excelType;
/**
* Final output file
* <p>
* If 'outputStream' and 'file' all not empty,file first
*/
private File file;
/** /**
* Final output stream * Final output stream
* <p>
* If 'outputStream' and 'file' all not empty,file first
*/ */
private OutputStream outputStream; private OutputStream outputStream;
/** /**
* <li>write: Template input stream * Template input stream
* <li>read: Read InputStream
* <p> * <p>
* If 'inputStream' and 'file' all not empty,file first * If 'inputStream' and 'file' all not empty,file first
*/ */
private InputStream templateInputStream; private InputStream templateInputStream;
/** /**
* <li>write: Template file * Template file
* <li>read: Read file
* <p> * <p>
* If 'inputStream' and 'file' all not empty,file first * If 'inputStream' and 'file' all not empty,file first
*/ */
@ -69,6 +75,14 @@ public class WriteWorkbook extends WriteBasicParameter {
this.excelType = excelType; this.excelType = excelType;
} }
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public OutputStream getOutputStream() { public OutputStream getOutputStream() {
return outputStream; return outputStream;
} }

2
src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java

@ -300,7 +300,7 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ
} }
// classify // classify
Map<Class<? extends WriteHandler>, List<WriteHandler>> result = Map<Class<? extends WriteHandler>, List<WriteHandler>> result =
new HashMap<Class<? extends WriteHandler>, List<WriteHandler>>(); new HashMap<Class<? extends WriteHandler>, List<WriteHandler>>(16);
result.put(WriteHandler.class, new ArrayList<WriteHandler>()); result.put(WriteHandler.class, new ArrayList<WriteHandler>());
result.put(WorkbookWriteHandler.class, new ArrayList<WriteHandler>()); result.put(WorkbookWriteHandler.class, new ArrayList<WriteHandler>());
result.put(SheetWriteHandler.class, new ArrayList<WriteHandler>()); result.put(SheetWriteHandler.class, new ArrayList<WriteHandler>());

2
src/main/java/com/alibaba/excel/write/metadata/holder/WriteHolder.java

@ -16,6 +16,8 @@ import com.alibaba.excel.write.property.ExcelWriteHeadProperty;
public interface WriteHolder extends ConfigurationHolder { public interface WriteHolder extends ConfigurationHolder {
/** /**
* What 'ExcelWriteHeadProperty' does the currently operated cell need to execute * What 'ExcelWriteHeadProperty' does the currently operated cell need to execute
*
* @return
*/ */
ExcelWriteHeadProperty excelWriteHeadProperty(); ExcelWriteHeadProperty excelWriteHeadProperty();

35
src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java

@ -1,6 +1,8 @@
package com.alibaba.excel.write.metadata.holder; package com.alibaba.excel.write.metadata.holder;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.HashMap; import java.util.HashMap;
@ -11,6 +13,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.alibaba.excel.enums.HolderEnum; import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteWorkbook; import com.alibaba.excel.write.metadata.WriteWorkbook;
@ -30,6 +33,12 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
* current param * current param
*/ */
private WriteWorkbook writeWorkbook; private WriteWorkbook writeWorkbook;
/**
* Final output file
* <p>
* If 'outputStream' and 'file' all not empty,file first
*/
private File file;
/** /**
* Final output stream * Final output stream
*/ */
@ -66,7 +75,16 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
public WriteWorkbookHolder(WriteWorkbook writeWorkbook) { public WriteWorkbookHolder(WriteWorkbook writeWorkbook) {
super(writeWorkbook, null, writeWorkbook.getConvertAllFiled()); super(writeWorkbook, null, writeWorkbook.getConvertAllFiled());
this.writeWorkbook = writeWorkbook; this.writeWorkbook = writeWorkbook;
this.outputStream = writeWorkbook.getOutputStream(); this.file = writeWorkbook.getFile();
if (file != null) {
try {
this.outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new ExcelGenerateException("Can not found file.", e);
}
} else {
this.outputStream = writeWorkbook.getOutputStream();
}
this.templateInputStream = writeWorkbook.getTemplateInputStream(); this.templateInputStream = writeWorkbook.getTemplateInputStream();
this.templateFile = writeWorkbook.getTemplateFile(); this.templateFile = writeWorkbook.getTemplateFile();
if (writeWorkbook.getAutoCloseStream() == null) { if (writeWorkbook.getAutoCloseStream() == null) {
@ -75,10 +93,11 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
this.autoCloseStream = writeWorkbook.getAutoCloseStream(); this.autoCloseStream = writeWorkbook.getAutoCloseStream();
} }
if (writeWorkbook.getExcelType() == null) { if (writeWorkbook.getExcelType() == null) {
if (LOGGER.isDebugEnabled()) { if (file != null && file.getName().endsWith(ExcelTypeEnum.XLS.getValue())) {
LOGGER.debug("The default specified xlsx."); this.excelType = ExcelTypeEnum.XLS;
} else {
this.excelType = ExcelTypeEnum.XLSX;
} }
this.excelType = ExcelTypeEnum.XLSX;
} else { } else {
this.excelType = writeWorkbook.getExcelType(); this.excelType = writeWorkbook.getExcelType();
} }
@ -114,6 +133,14 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
this.writeWorkbook = writeWorkbook; this.writeWorkbook = writeWorkbook;
} }
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public OutputStream getOutputStream() { public OutputStream getOutputStream() {
return outputStream; return outputStream;
} }

86
src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java

@ -2,8 +2,10 @@ package com.alibaba.excel.write.property;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.ContentRowHeight;
@ -73,56 +75,46 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty {
*/ */
public List<CellRange> headCellRangeList() { public List<CellRange> headCellRangeList() {
List<CellRange> cellRangeList = new ArrayList<CellRange>(); List<CellRange> cellRangeList = new ArrayList<CellRange>();
int i = 0; Set<String> alreadyRangeSet = new HashSet<String>();
for (Map.Entry<Integer, Head> entry : getHeadMap().entrySet()) { List<Head> headList = new ArrayList<Head>(getHeadMap().values());
Head head = entry.getValue(); for (int i = 0; i < headList.size(); i++) {
List<String> columnValues = head.getHeadNameList(); Head head = headList.get(i);
for (int j = 0; j < columnValues.size(); j++) { List<String> headNameList = head.getHeadNameList();
int lastRow = getLastRangNum(j, columnValues.get(j), columnValues); for (int j = 0; j < headNameList.size(); j++) {
int lastColumn = getLastRangNum(i, columnValues.get(j), head.getHeadNameList()); if (alreadyRangeSet.contains(i + "-" + j)) {
if ((lastRow > j || lastColumn > i) && lastRow >= 0 && lastColumn >= 0) { continue;
cellRangeList.add(new CellRange(j, lastRow, i, lastColumn));
} }
} String headName = headNameList.get(j);
i++; int endX = i;
} int endY = j;
return cellRangeList; for (int k = i + 1; k < headList.size(); k++) {
} if (headList.get(k).getHeadNameList().get(j).equals(headName)) {
alreadyRangeSet.add(k + "-" + j);
/** endX = k;
* Get the last consecutive string position } else {
* break;
* @param j }
* current value position }
* @param value // The current cells are not merged
* value content if (endX == i) {
* @param values continue;
* values
* @return the last consecutive string position
*/
private int getLastRangNum(int j, String value, List<String> values) {
if (value == null) {
return -1;
}
if (j > 0) {
String preValue = values.get(j - 1);
if (value.equals(preValue)) {
return -1;
}
}
int last = j;
for (int i = last + 1; i < values.size(); i++) {
String current = values.get(i);
if (value.equals(current)) {
last = i;
} else {
// if i>j && !value.equals(current) Indicates that the continuous range is exceeded
if (i > j) {
break;
} }
Set<String> tempAlreadyRangeSet = new HashSet<String>();
outer:
for (int k = j + 1; k < headNameList.size(); k++) {
for (int l = i; l < endX; l++) {
if (headList.get(l).getHeadNameList().get(k).equals(headName)) {
tempAlreadyRangeSet.add(k + "-" + j);
} else {
break outer;
}
}
endY = k;
alreadyRangeSet.addAll(tempAlreadyRangeSet);
}
cellRangeList.add(new CellRange(i, endY, j, endX));
} }
} }
return last; return cellRangeList;
} }
} }

7
src/main/java/com/alibaba/excel/write/style/AbstractColumnCellStyleStrategy.java

@ -10,7 +10,6 @@ import org.apache.poi.ss.usermodel.Workbook;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.StyleUtil; import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.metadata.style.WriteCellStyle; import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.sun.istack.internal.Nullable;
/** /**
* *
@ -73,16 +72,18 @@ public abstract class AbstractColumnCellStyleStrategy extends AbstractCellStyleS
* Returns the column width corresponding to each column head * Returns the column width corresponding to each column head
* *
* @param head * @param head
* Nullable
* @return * @return
*/ */
protected abstract WriteCellStyle headCellStyle(@Nullable Head head); protected abstract WriteCellStyle headCellStyle(Head head);
/** /**
* Returns the column width corresponding to each column head * Returns the column width corresponding to each column head
* *
* @param head * @param head
* Nullable
* @return * @return
*/ */
protected abstract WriteCellStyle contentCellStyle(@Nullable Head head); protected abstract WriteCellStyle contentCellStyle(Head head);
} }

4
src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java

@ -9,7 +9,6 @@ import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.sun.istack.internal.Nullable;
/** /**
* Column width style strategy * Column width style strategy
@ -44,7 +43,6 @@ public abstract class AbstractColumnWidthStyleStrategy implements CellWriteHandl
* @param relativeRowIndex * @param relativeRowIndex
* @param isHead * @param isHead
*/ */
protected abstract void setColumnWidth(Sheet sheet, Cell cell, @Nullable Head head, int relativeRowIndex, protected abstract void setColumnWidth(Sheet sheet, Cell cell, Head head, int relativeRowIndex, boolean isHead);
boolean isHead);
} }

4
src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java

@ -4,7 +4,6 @@ import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.sun.istack.internal.Nullable;
/** /**
* Returns the column width according to each column header * Returns the column width according to each column header
@ -29,9 +28,10 @@ public abstract class AbstractHeadColumnWidthStyleStrategy extends AbstractColum
* <li>if return null,ignore * <li>if return null,ignore
* *
* @param head * @param head
* Nullable
* @return the width in units of 1/256th of a character width . Using the Calibri font as an example, the maximum * @return the width in units of 1/256th of a character width . Using the Calibri font as an example, the maximum
* digit width of 11 point font size is 7 pixels (at 96 dpi). If you set a column width to be eight * digit width of 11 point font size is 7 pixels (at 96 dpi). If you set a column width to be eight
* characters wide, e.g. you need return 8*256 * characters wide, e.g. you need return 8*256
*/ */
protected abstract Integer columnWidth(@Nullable Head head); protected abstract Integer columnWidth(Head head);
} }

16
src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationData.java

@ -0,0 +1,16 @@
package com.alibaba.easyexcel.test.core.annotation;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class AnnotationData {
@ExcelProperty("日期")
private Date name;
}

74
src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java

@ -0,0 +1,74 @@
package com.alibaba.easyexcel.test.core.annotation;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.alibaba.easyexcel.test.core.simple.SimpleData;
import com.alibaba.easyexcel.test.core.simple.SimpleDataListener;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
/**
* Annotation data test
*
* @author zhuangjiaju
*/
public class AnnotationDataTest {
private File file07 = TestFileUtil.createNewFile("simple07.xlsx");
private File file03 = TestFileUtil.createNewFile("simple03.xls");
@Test
public void readAndWrite07() {
EasyExcelFactory.write(file07, com.alibaba.easyexcel.test.core.simple.SimpleData.class).sheet().doWrite(data())
.finish();
EasyExcelFactory.read(file07, com.alibaba.easyexcel.test.core.simple.SimpleData.class,
new com.alibaba.easyexcel.test.core.simple.SimpleDataListener()).sheet().doRead().finish();
}
@Test
public void synchronousRead07() {
// Synchronous read file
List<Object> list = EasyExcelFactory.read(file07).head(com.alibaba.easyexcel.test.core.simple.SimpleData.class)
.sheet().doReadSync();
Assert.assertEquals(list.size(), 10);
Assert.assertTrue(list.get(0) instanceof com.alibaba.easyexcel.test.core.simple.SimpleData);
Assert.assertEquals(((com.alibaba.easyexcel.test.core.simple.SimpleData)list.get(0)).getName(), "姓名0");
}
@Test
public void readAndWrite03() {
EasyExcelFactory.write(file03, com.alibaba.easyexcel.test.core.simple.SimpleData.class).sheet().doWrite(data())
.finish();
EasyExcelFactory.read(file03, com.alibaba.easyexcel.test.core.simple.SimpleData.class, new SimpleDataListener())
.sheet().doRead().finish();
}
@Test
public void synchronousRead03() {
// Synchronous read file
List<Object> list = EasyExcelFactory.read(file03).head(com.alibaba.easyexcel.test.core.simple.SimpleData.class)
.sheet().doReadSync();
Assert.assertEquals(list.size(), 10);
Assert.assertTrue(list.get(0) instanceof com.alibaba.easyexcel.test.core.simple.SimpleData);
Assert.assertEquals(((com.alibaba.easyexcel.test.core.simple.SimpleData)list.get(0)).getName(), "姓名0");
}
private List<com.alibaba.easyexcel.test.core.simple.SimpleData> data() {
List<com.alibaba.easyexcel.test.core.simple.SimpleData> list =
new ArrayList<com.alibaba.easyexcel.test.core.simple.SimpleData>();
for (int i = 0; i < 10; i++) {
com.alibaba.easyexcel.test.core.simple.SimpleData simpleData = new SimpleData();
simpleData.setName("姓名" + i);
list.add(simpleData);
}
return list;
}
}

36
src/test/java/com/alibaba/easyexcel/test/core/annotation/SimpleDataListener.java

@ -0,0 +1,36 @@
package com.alibaba.easyexcel.test.core.annotation;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.easyexcel.test.core.simple.SimpleData;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class SimpleDataListener extends AnalysisEventListener<SimpleData> {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleDataListener.class);
List<SimpleData> list = new ArrayList<SimpleData>();
@Override
public void invoke(SimpleData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 10);
Assert.assertEquals(list.get(0).getName(), "姓名0");
Assert.assertEquals((int)(context.readSheetHolder().getSheetNo()), 0);
Assert.assertEquals(
context.readSheetHolder().getExcelReadHeadProperty().getHeadMap().get(0).getHeadNameList().get(0), "姓名");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

35
src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java

@ -0,0 +1,35 @@
package com.alibaba.easyexcel.test.core.converter;
import java.math.BigDecimal;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class ConverterData {
@ExcelProperty("日期")
private Date date;
@ExcelProperty("布尔")
private Boolean booleanData;
@ExcelProperty("大数")
private BigDecimal bigDecimal;
@ExcelProperty("长整型")
private Long longData;
@ExcelProperty("整型")
private Integer integerData;
@ExcelProperty("短整型")
private Short shortData;
@ExcelProperty("字节型")
private Byte byteData;
@ExcelProperty("双精度浮点型")
private Double doubleData;
@ExcelProperty("浮点型")
private Float floatData;
@ExcelProperty("字符串")
private String string;
}

50
src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataListener.java

@ -0,0 +1,50 @@
package com.alibaba.easyexcel.test.core.converter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelCommonException;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class ConverterDataListener extends AnalysisEventListener<ConverterData> {
private static final Logger LOGGER = LoggerFactory.getLogger(ConverterDataListener.class);
List<ConverterData> list = new ArrayList<ConverterData>();
@Override
public void invoke(ConverterData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 1);
ConverterData data = list.get(0);
try {
Assert.assertEquals(data.getDate(), DateUtils.parseDate("2020-01-01 01:01:01"));
} catch (ParseException e) {
throw new ExcelCommonException("Test Exception", e);
}
Assert.assertEquals(data.getBooleanData(), Boolean.TRUE);
Assert.assertEquals(data.getBigDecimal().doubleValue(), BigDecimal.ONE.doubleValue(), 0.0);
Assert.assertEquals((long)data.getLongData(), 1L);
Assert.assertEquals((long)data.getIntegerData(), 1L);
Assert.assertEquals((long)data.getShortData(), 1L);
Assert.assertEquals((long)data.getByteData(), 1L);
Assert.assertEquals(data.getDoubleData(), 1.0, 0.0);
Assert.assertEquals(data.getFloatData(), (float)1.0, 0.0);
Assert.assertEquals(data.getString(), "测试");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

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

@ -0,0 +1,58 @@
package com.alibaba.easyexcel.test.core.converter;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.util.DateUtils;
/**
* Annotation data test
*
* @author zhuangjiaju
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ConverterDataTest {
private File file07 = TestFileUtil.createNewFile("converter07.xlsx");
private File file03 = TestFileUtil.createNewFile("converter03.xls");
@Test
public void T01ReadAndWrite07() throws Exception {
readAndWrite(file07);
}
@Test
public void T02ReadAndWrite03() throws Exception {
readAndWrite(file03);
}
private void readAndWrite(File file) throws Exception {
EasyExcelFactory.write(file, ConverterData.class).sheet().doWrite(data()).finish();
EasyExcelFactory.read(file, ConverterData.class, new ConverterDataListener()).sheet().doRead().finish();
}
private List<ConverterData> data() throws Exception {
List<ConverterData> list = new ArrayList<ConverterData>();
ConverterData converterData = new ConverterData();
converterData.setDate(DateUtils.parseDate("2020-01-01 01:01:01"));
converterData.setBooleanData(Boolean.TRUE);
converterData.setBigDecimal(BigDecimal.ONE);
converterData.setLongData(1L);
converterData.setIntegerData(1);
converterData.setShortData((short)1);
converterData.setByteData((byte)1);
converterData.setDoubleData(1.0);
converterData.setFloatData((float)1.0);
converterData.setString("测试");
list.add(converterData);
return list;
}
}

53
src/test/java/com/alibaba/easyexcel/test/core/converter/ReadConverterData.java

@ -0,0 +1,53 @@
package com.alibaba.easyexcel.test.core.converter;
import java.math.BigDecimal;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class ReadConverterData {
@ExcelProperty("日期")
private Date date;
@ExcelProperty("日期字符串")
private String dateString;
@ExcelProperty("布尔")
private Boolean booleanData;
@ExcelProperty("布尔字符串")
private String booleanString;
@ExcelProperty("大数")
private BigDecimal bigDecimal;
@ExcelProperty("大数字符串")
private String bigDecimalString;
@ExcelProperty("长整型")
private Long longData;
@ExcelProperty("长整型字符串")
private String longString;
@ExcelProperty("整型")
private Integer integerData;
@ExcelProperty("整型字符串")
private String integerString;
@ExcelProperty("短整型")
private Short shortData;
@ExcelProperty("短整型字符串")
private String shortString;
@ExcelProperty("字节型")
private Byte byteData;
@ExcelProperty("字节型字符串")
private String byteString;
@ExcelProperty("双精度浮点型")
private Double doulbleData;
@ExcelProperty("双精度浮点型字符串")
private String doulbleString;
@ExcelProperty("浮点型")
private Float FloatData;
@ExcelProperty("浮点型字符串")
private String FloatString;
@ExcelProperty("字符串")
private String string;
}

6
src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleData.java

@ -9,8 +9,6 @@ import lombok.Data;
*/ */
@Data @Data
public class SimpleData { public class SimpleData {
@ExcelProperty("字符串1") @ExcelProperty("姓名")
private String string1; private String name;
@ExcelProperty("字符串2")
private String string2;
} }

4
src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataListener.java

@ -26,6 +26,10 @@ public class SimpleDataListener extends AnalysisEventListener<SimpleData> {
@Override @Override
public void doAfterAllAnalysed(AnalysisContext context) { public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 10); Assert.assertEquals(list.size(), 10);
Assert.assertEquals(list.get(0).getName(), "姓名0");
Assert.assertEquals((int)(context.readSheetHolder().getSheetNo()), 0);
Assert.assertEquals(
context.readSheetHolder().getExcelReadHeadProperty().getHeadMap().get(0).getHeadNameList().get(0), "姓名");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0))); LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
} }
} }

54
src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java

@ -1,8 +1,13 @@
package com.alibaba.easyexcel.test.core.simple; package com.alibaba.easyexcel.test.core.simple;
import java.io.File; import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test; import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory; import com.alibaba.excel.EasyExcelFactory;
@ -12,11 +17,54 @@ import com.alibaba.excel.EasyExcelFactory;
* *
* @author zhuangjiaju * @author zhuangjiaju
*/ */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SimpleDataTest { public class SimpleDataTest {
private File file07 = TestFileUtil.createNewFile("simple07.xlsx");
private File file03 = TestFileUtil.createNewFile("simple03.xls");
@Test
public void T01ReadAndWrite() {
readAndWrite(file07);
}
@Test
public void T02ReadAndWrite03() {
readAndWrite(file03);
}
private void readAndWrite(File file) {
EasyExcelFactory.write(file, SimpleData.class).sheet().doWrite(data()).finish();
EasyExcelFactory.read(file, SimpleData.class, new SimpleDataListener()).sheet().doRead().finish();
}
@Test @Test
public void read() { public void T03SynchronousRead07() {
EasyExcelFactory.read(TestFileUtil.getPath() + "simple" + File.separator + "simple07Test.xlsx", synchronousRead(file07);
SimpleData.class, new SimpleDataListener()).sheet().doRead().finish(); }
@Test
public void T04SynchronousRead03() {
synchronousRead(file03);
}
private void synchronousRead(File file) {
// Synchronous read file
List<Object> list = EasyExcelFactory.read(file).head(SimpleData.class).sheet().doReadSync();
Assert.assertEquals(list.size(), 10);
Assert.assertTrue(list.get(0) instanceof SimpleData);
Assert.assertEquals(((SimpleData)list.get(0)).getName(), "姓名0");
}
private List<SimpleData> data() {
List<SimpleData> list = new ArrayList<SimpleData>();
for (int i = 0; i < 10; i++) {
SimpleData simpleData = new SimpleData();
simpleData.setName("姓名" + i);
list.add(simpleData);
}
return list;
} }
} }

1
src/test/java/com/alibaba/easyexcel/test/util/TestFileUtil.java

@ -22,7 +22,6 @@ public class TestFileUtil {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
} }
} }
return file; return file;
} }

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

Binary file not shown.
Loading…
Cancel
Save