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. 18
      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. 12
      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. 5
      src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java
  20. 7
      src/main/java/com/alibaba/excel/read/builder/ExcelReaderSheetBuilder.java
  21. 12
      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. 8
      src/main/java/com/alibaba/excel/util/DateUtils.java
  25. 5
      src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java
  26. 14
      src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java
  27. 17
      src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java
  28. 13
      src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java
  29. 26
      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. 56
      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>
</goals>
</execution>
<!-- 绑定pmd:pmd到site生命周期 -->
<execution>
<id>pmd-pmd-site</id>
<phase>site</phase>
<goals>
<goal>pmd</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>

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

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

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

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

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

@ -2,15 +2,17 @@ package com.alibaba.excel.analysis.v03;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.metadata.CellData;
/**
* Intercepts handle xls reads.
*
*
* @author Dan Zheng
*/
public interface XlsRecordHandler extends Comparable<XlsRecordHandler> {
/**
* Which tags are supported
*
*
* @param record
* @return
*/
@ -23,35 +25,35 @@ public interface XlsRecordHandler extends Comparable<XlsRecordHandler> {
/**
* Processing record
*
*
* @param record
*/
void processRecord(Record record);
/**
* Get row
*
*
* @return
*/
int getRow();
/**
* Get column
*
*
* @return
*/
int getColumn();
/**
* Get value
*
*
* @return
*/
String getValue();
CellData getCellData();
/**
* Get order
*
*
* @return
*/
int getOrder();

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.SstRecordHandler;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
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.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder;
import com.alibaba.excel.util.CollectionUtils;
@ -53,13 +56,13 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
private POIFSFileSystem fs;
private int lastRowNumber;
private int lastColumnNumber;
private boolean notAllEmpty = false;
/**
* For parsing Formulas
*/
private EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener;
private FormatTrackingHSSFListener formatListener;
private List<String> records;
private boolean notAllEmpty = false;
private List<CellData> records;
private List<ReadSheet> sheets = new ArrayList<ReadSheet>();
private HSSFWorkbook stubWorkbook;
private List<XlsRecordHandler> recordHandlers = new ArrayList<XlsRecordHandler>();
@ -67,13 +70,14 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
public XlsSaxAnalyser(AnalysisContext context) throws IOException {
this.analysisContext = context;
this.records = new ArrayList<String>();
this.records = new ArrayList<CellData>();
ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder();
if (readWorkbookHolder.getFile() != null) {
this.fs = new POIFSFileSystem(readWorkbookHolder.getFile());
} else {
this.fs = new POIFSFileSystem(readWorkbookHolder.getInputStream());
}
}
@Override
@ -110,8 +114,7 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
private void init() {
lastRowNumber = 0;
lastColumnNumber = 0;
records = new ArrayList<String>();
notAllEmpty = false;
records = new ArrayList<CellData>();
sheets = new ArrayList<ReadSheet>();
buildXlsRecordHandlers();
}
@ -120,25 +123,28 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
public void processRecord(Record record) {
int thisRow = -1;
int thisColumn = -1;
String thisStr = null;
CellData cellData = null;
for (XlsRecordHandler handler : this.recordHandlers) {
if (handler.support(record)) {
handler.processRecord(record);
thisRow = handler.getRow();
thisColumn = handler.getColumn();
thisStr = handler.getValue();
cellData = handler.getCellData();
if (cellData != null) {
records.add(cellData);
}
break;
}
}
// If we got something to print out, do so
if (thisStr != null) {
if (analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
thisStr = thisStr.trim();
if (cellData != null) {
if (analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()
&& CellDataTypeEnum.STRING == cellData.getType()) {
cellData.setStringValue(cellData.getStringValue().trim());
}
if (!"".equals(thisStr)) {
if (CellDataTypeEnum.EMPTY != cellData.getType()) {
notAllEmpty = true;
}
records.add(thisStr);
}
// Handle new row
@ -161,17 +167,17 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
// Handle end of row
if (record instanceof LastCellOfRowDummyRecord) {
int row = ((LastCellOfRowDummyRecord)record).getRow();
if (lastColumnNumber == -1) {
lastColumnNumber = 0;
}
if (notAllEmpty) {
analysisContext.readSheetHolder()
.notifyEndOneRow(new EachRowAnalysisFinishEvent(new ArrayList<String>(records)), analysisContext);
analysisContext.readRowHolder(
new ReadRowHolder(lastRowNumber, analysisContext.readSheetHolder().getGlobalConfiguration()));
analysisContext.readSheetHolder().notifyEndOneRow(new EachRowAnalysisFinishEvent(records),
analysisContext);
}
records.clear();
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 com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
/**
* Record handler
@ -24,12 +26,12 @@ public class BlankOrErrorRecordHandler extends AbstractXlsRecordHandler {
BlankRecord br = (BlankRecord)record;
this.row = br.getRow();
this.column = br.getColumn();
this.value = "";
this.cellData = new CellData(CellDataTypeEnum.EMPTY);
} else if (record.getSid() == BoolErrRecord.sid) {
BoolErrRecord ber = (BoolErrRecord)record;
this.row = ber.getRow();
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;
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.Record;
import org.apache.poi.hssf.record.StringRecord;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.metadata.CellData;
/**
* Record handler
@ -17,10 +17,6 @@ import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
public class FormulaRecordHandler extends AbstractXlsRecordHandler {
private int nextRow;
private int nextColumn;
/**
* Should we output the formula, or the value it has?
*/
private boolean outputFormulaValues = true;
private boolean outputNextStringRecord;
private FormatTrackingHSSFListener formatListener;
private HSSFWorkbook stubWorkbook;
@ -43,24 +39,20 @@ public class FormulaRecordHandler extends AbstractXlsRecordHandler {
this.row = frec.getRow();
this.column = frec.getColumn();
if (outputFormulaValues) {
if (Double.isNaN(frec.getValue())) {
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
nextRow = frec.getRow();
nextColumn = frec.getColumn();
} else {
this.value = formatListener.formatNumberDateCell(frec);
}
if (Double.isNaN(frec.getValue())) {
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
nextRow = frec.getRow();
nextColumn = frec.getColumn();
} else {
this.value = HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression());
this.cellData = new CellData(frec.getValue());
}
} else if (record.getSid() == StringRecord.sid) {
if (outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord)record;
this.value = srec.getString();
this.cellData = new CellData(srec.getString());
this.row = nextRow;
this.column = nextColumn;
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 com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.metadata.CellData;
/**
* Record handler
@ -21,7 +22,7 @@ public class LabelRecordHandler extends AbstractXlsRecordHandler {
LabelRecord lrec = (LabelRecord)record;
this.row = lrec.getRow();
this.column = lrec.getColumn();
this.value = lrec.getValue();
this.cellData = new CellData(lrec.getValue());
}
@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 com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
/**
* Record handler
@ -26,7 +28,7 @@ public class MissingCellDummyRecordHandler extends AbstractXlsRecordHandler {
MissingCellDummyRecord mcdr = (MissingCellDummyRecord)record;
this.row = mcdr.getRow();
this.column = mcdr.getColumn();
this.value = "";
this.cellData = new CellData(CellDataTypeEnum.EMPTY);
}
@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 com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
/**
* Record handler
@ -19,10 +21,9 @@ public class NoteRecordHandler extends AbstractXlsRecordHandler {
@Override
public void processRecord(Record record) {
NoteRecord nrec = (NoteRecord)record;
this.row = nrec.getRow();
this.column = nrec.getColumn();
this.value = "(TODO)";
this.cellData = new CellData(CellDataTypeEnum.EMPTY);
}
@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 com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.metadata.CellData;
/**
* Record handler
@ -28,8 +29,7 @@ public class NumberRecordHandler extends AbstractXlsRecordHandler {
NumberRecord numrec = (NumberRecord)record;
this.row = numrec.getRow();
this.column = numrec.getColumn();
// Format
this.value = formatListener.formatNumberDateCell(numrec);
this.cellData = new CellData(numrec.getValue());
}
@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 com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
/**
* Record handler
@ -22,7 +24,7 @@ public class RkRecordHandler extends AbstractXlsRecordHandler {
this.row = rkrec.getRow();
this.row = rkrec.getColumn();
this.value = "";
this.cellData = new CellData(CellDataTypeEnum.EMPTY);
}
@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 com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
/**
* Record handler
@ -25,13 +27,12 @@ public class SstRecordHandler extends AbstractXlsRecordHandler {
sstRecord = (SSTRecord)record;
} else if (record.getSid() == LabelSSTRecord.sid) {
LabelSSTRecord lsrec = (LabelSSTRecord)record;
this.row = lsrec.getRow();
this.column = lsrec.getColumn();
if (sstRecord == null) {
this.value = "";
this.cellData = new CellData(CellDataTypeEnum.EMPTY);
} else {
this.value = sstRecord.getString(lsrec.getSSTIndex()).toString();
this.cellData = new CellData(sstRecord.getString(lsrec.getSSTIndex()).toString());
}
}
}

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

@ -1,10 +1,12 @@
package com.alibaba.excel.analysis.v07;
import java.util.List;
import com.alibaba.excel.metadata.CellData;
/**
* Result holder
*
*
* @author jipengfei
*/
public interface XlsxRowResultHolder {
@ -15,21 +17,21 @@ public interface XlsxRowResultHolder {
/**
* Append current 'cellValue'
*
*
* @param currentCellValue
*/
void appendCurrentCellValue(String currentCellValue);
/**
* Get row content
*
*
* @return
*/
CellData[] getCurRowContent();
List<CellData> getCurRowContent();
/**
* get column size
*
*
* @return
*/
int getColumnSize();

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_TYPE_TAG;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
@ -33,7 +34,7 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
private String currentCellIndex;
private int curRow;
private int curCol;
private CellData[] curRowContent = new CellData[20];
private List<CellData> curRowContent = new ArrayList<CellData>();
private CellData currentCellData;
public DefaultCellHandler(AnalysisContext analysisContext) {
@ -42,7 +43,7 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
@Override
public void clearResult() {
curRowContent = new CellData[20];
curRowContent.clear();
}
@Override
@ -69,6 +70,7 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
// t="inlineStr" ,it's means String
// t="b" ,it's means Boolean
// t="e" ,it's means Error
// t="n" ,it's means Number
// t is null ,it's means Empty or Number
CellDataTypeEnum type = CellDataTypeEnum.buildFromCellType(attributes.getValue(CELL_VALUE_TYPE_TAG));
currentCellData = new CellData(type);
@ -82,7 +84,6 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
@Override
public void endHandle(String name) {
if (CELL_VALUE_TAG.equals(name)) {
ensureSize();
// Have to go "sharedStrings.xml" and get it
if (currentCellData.getType() == CellDataTypeEnum.STRING) {
String stringValue = analysisContext.readWorkbookHolder().getReadCache()
@ -92,25 +93,17 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
}
currentCellData.setStringValue(stringValue);
}
curRowContent[curCol] = currentCellData;
curRowContent.set(curCol, currentCellData);
}
// This is a special form of string
if (CELL_INLINE_STRING_VALUE_TAG.equals(name)) {
ensureSize();
XSSFRichTextString richTextString = new XSSFRichTextString(currentCellData.getStringValue());
String stringValue = richTextString.toString();
if (stringValue != null && analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
stringValue = stringValue.trim();
}
currentCellData.setStringValue(stringValue);
curRowContent[curCol] = currentCellData;
}
}
private void ensureSize() {
// try to size
if (curCol >= curRowContent.length) {
curRowContent = Arrays.copyOf(curRowContent, (int)(curCol * 1.5));
curRowContent.set(curCol, currentCellData);
}
}
@ -135,6 +128,7 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
case BOOLEAN:
currentCellData.setBooleanValue(BooleanUtils.valueOf(currentCellValue));
break;
case NUMBER:
case EMPTY:
currentCellData.setType(CellDataTypeEnum.NUMBER);
currentCellData.setDoubleValue(Double.valueOf(currentCellValue));
@ -145,7 +139,7 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
}
@Override
public CellData[] getCurRowContent() {
public List<CellData> getCurRowContent() {
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
public void endHandle(String name) {
analysisContext.readSheetHolder().notifyEndOneRow(
new EachRowAnalysisFinishEvent(rowResultHandler.getCurRowContent(), rowResultHandler.getColumnSize()),
analysisContext);
analysisContext.readSheetHolder()
.notifyEndOneRow(new EachRowAnalysisFinishEvent(rowResultHandler.getCurRowContent()), analysisContext);
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 com.alibaba.excel.analysis.ExcelExecutor;
import com.alibaba.excel.analysis.v07.XlsxSaxAnalyser;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.metadata.ReadSheet;
@ -65,6 +66,24 @@ public class AnalysisContextImpl implements AnalysisContext {
}
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) {
for (ReadSheet readSheetExcel : excelExecutor.sheetList()) {
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.GlobalConfiguration;
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
@ -33,23 +31,29 @@ public interface Converter<T> {
* Convert excel objects to Java objects
*
* @param cellData
* NotNull
* @param contentProperty
* Nullable
* @param globalConfiguration
* NotNull
* @return
* @throws Exception
*/
T convertToJavaData(@NotNull CellData cellData, @Nullable ExcelContentProperty contentProperty,
@NotNull GlobalConfiguration globalConfiguration) throws Exception;
T convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws Exception;
/**
* Convert Java objects to excel objects
*
* @param value
* NotNull
* @param contentProperty
* Nullable
* @param globalConfiguration
* NotNull
* @return
* @throws Exception
*/
CellData convertToExcelData(@NotNull T value, @Nullable ExcelContentProperty contentProperty,
@NotNull GlobalConfiguration globalConfiguration) throws Exception;
CellData convertToExcelData(T value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration)
throws Exception;
}

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

@ -33,17 +33,18 @@ public enum CellDataTypeEnum {
*/
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 {
TYPE_ROUTING_MAP.put("s", STRING);
TYPE_ROUTING_MAP.put("inlineStr", STRING);
TYPE_ROUTING_MAP.put("e", ERROR);
TYPE_ROUTING_MAP.put("b", BOOLEAN);
TYPE_ROUTING_MAP.put("n", NUMBER);
}
/**
* Build data types
*
*
* @param cellType
* @return
*/

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

@ -13,7 +13,7 @@ import com.alibaba.excel.read.metadata.ReadSheet;
/**
* Build sheet
*
*
* @author zhuangjiaju
*/
public class ExcelReaderSheetBuilder {
@ -149,7 +149,7 @@ public class ExcelReaderSheetBuilder {
/**
* Sax read
*
*
* @return
*/
public ExcelReaderSheetBuilder doRead() {
@ -174,7 +174,7 @@ public class ExcelReaderSheetBuilder {
/**
* Synchronous reads return results
*
*
* @return
*/
public List<Object> doReadSync() {
@ -184,6 +184,7 @@ public class ExcelReaderSheetBuilder {
SyncReadListener syncReadListener = new SyncReadListener();
registerReadListener(syncReadListener);
excelReader.read(build());
excelReader.finish();
return syncReadListener.getList();
}

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

@ -1,16 +1,20 @@
package com.alibaba.excel.read.listener.event;
import java.util.List;
import com.alibaba.excel.metadata.CellData;
/**
*
*
* Event
*
*
* @author jipengfei
*/
public interface AnalysisFinishEvent {
/**
* Get result
*
*
* @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;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.metadata.CellData;
@ -9,24 +8,13 @@ import com.alibaba.excel.metadata.CellData;
* @author jipengfei
*/
public class EachRowAnalysisFinishEvent implements AnalysisFinishEvent {
private Object result;
private List<CellData> result;
public EachRowAnalysisFinishEvent(Object content) {
public EachRowAnalysisFinishEvent(List<CellData> 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
public Object getAnalysisResult() {
public List<CellData> getAnalysisResult() {
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
public void notifyEndOneRow(AnalysisFinishEvent event, AnalysisContext analysisContext) {
List<CellData> cellDataList = (List<CellData>)event.getAnalysisResult();
List<CellData> cellDataList = event.getAnalysisResult();
ReadRowHolder readRowHolder = analysisContext.readRowHolder();
readRowHolder.setCurrentRowAnalysisResult(cellDataList);

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

@ -22,7 +22,7 @@ public class DateUtils {
/**
* convert string to date
*
*
* @param dateString
* @param dateFormat
* @return
@ -43,7 +43,7 @@ public class DateUtils {
* @throws ParseException
*/
public static Date parseDate(String dateString) throws ParseException {
return parseDate(switchDateFormat(dateString), null);
return parseDate(dateString, switchDateFormat(dateString));
}
/**
@ -74,7 +74,7 @@ public class DateUtils {
* Format date
* <p>
* yyyy-MM-dd HH:mm:ss
*
*
* @param date
* @return
*/
@ -84,7 +84,7 @@ public class DateUtils {
/**
* Format date
*
*
* @param date
* @param dateFormat
* @return

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()) {
value = ((String)value).trim();
}
Converter converter = excelContentProperty.getConverter();
Converter converter = null;
if (excelContentProperty != null) {
converter = excelContentProperty.getConverter();
}
if (converter == null) {
converter = currentWriteHolder.converterMap().get(ConverterKeyBuild.buildKey(clazz));
}

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

@ -1,8 +1,6 @@
package com.alibaba.excel.write.builder;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
@ -11,14 +9,13 @@ import java.util.List;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteWorkbook;
/**
* Build ExcelBuilder
*
*
* @author zhuangjiaju
*/
public class ExcelWriterBuilder {
@ -88,7 +85,7 @@ public class ExcelWriterBuilder {
* field. if false , you must use {@link com.alibaba.excel.annotation.ExcelProperty} to use a filed.
* <p>
* Default true
*
*
* @param convertAllFiled
* @return
* @deprecated Just to be compatible with historical data, The default is always going to be convert all filed.
@ -138,11 +135,8 @@ public class ExcelWriterBuilder {
}
public ExcelWriterBuilder file(File outputFile) {
try {
return file(new FileOutputStream(outputFile));
} catch (FileNotFoundException e) {
throw new ExcelGenerateException("Can not create file", e);
}
writeWorkbook.setFile(outputFile);
return this;
}
public ExcelWriterBuilder file(String outputPathName) {

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

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

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

@ -4,36 +4,37 @@ import org.apache.poi.ss.usermodel.Row;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.sun.istack.internal.Nullable;
/**
* intercepts handle row creation
*
*
* @author zhuangjiaju
*/
public interface RowWriteHandler extends WriteHandler {
/**
* called before create the row
*
*
* @param writeSheetHolder
* @param writeTableHolder
* Nullable
* @param rowIndex
* @param relativeRowIndex
* @param isHead
*/
void beforeRowCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, int rowIndex,
void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, int rowIndex,
int relativeRowIndex, boolean isHead);
/**
* called after the row is created
*
*
* @param writeSheetHolder
* @param writeTableHolder
* Nullable
* @param row
* @param relativeRowIndex
* @param isHead
*/
void afterRowCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, Row row,
void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
int relativeRowIndex, boolean isHead);
}

26
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
*/
private ExcelTypeEnum excelType;
/**
* Final output file
* <p>
* If 'outputStream' and 'file' all not empty,file first
*/
private File file;
/**
* Final output stream
* <p>
* If 'outputStream' and 'file' all not empty,file first
*/
private OutputStream outputStream;
/**
* <li>write: Template input stream
* <li>read: Read InputStream
* Template input stream
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
private InputStream templateInputStream;
/**
* <li>write: Template file
* <li>read: Read file
* Template file
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
@ -48,14 +54,14 @@ public class WriteWorkbook extends WriteBasicParameter {
* The default is all excel objects.Default is true.
* <li>if true , you can use {@link com.alibaba.excel.annotation.ExcelIgnore} ignore a field.
* <li>if false , you must use {@link com.alibaba.excel.annotation.ExcelProperty} to use a filed.
*
*
* @deprecated Just to be compatible with historical data, The default is always going to be convert all filed.
*/
@Deprecated
private Boolean convertAllFiled;
/**
* Write handler
*
*
* @deprecated please use {@link WriteHandler}
*/
@Deprecated
@ -69,6 +75,14 @@ public class WriteWorkbook extends WriteBasicParameter {
this.excelType = excelType;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public OutputStream getOutputStream() {
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
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(WorkbookWriteHandler.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 {
/**
* What 'ExcelWriteHeadProperty' does the currently operated cell need to execute
*
* @return
*/
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;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
@ -11,6 +13,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteWorkbook;
@ -30,6 +33,12 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
* current param
*/
private WriteWorkbook writeWorkbook;
/**
* Final output file
* <p>
* If 'outputStream' and 'file' all not empty,file first
*/
private File file;
/**
* Final output stream
*/
@ -66,7 +75,16 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
public WriteWorkbookHolder(WriteWorkbook writeWorkbook) {
super(writeWorkbook, null, writeWorkbook.getConvertAllFiled());
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.templateFile = writeWorkbook.getTemplateFile();
if (writeWorkbook.getAutoCloseStream() == null) {
@ -75,10 +93,11 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
this.autoCloseStream = writeWorkbook.getAutoCloseStream();
}
if (writeWorkbook.getExcelType() == null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("The default specified xlsx.");
if (file != null && file.getName().endsWith(ExcelTypeEnum.XLS.getValue())) {
this.excelType = ExcelTypeEnum.XLS;
} else {
this.excelType = ExcelTypeEnum.XLSX;
}
this.excelType = ExcelTypeEnum.XLSX;
} else {
this.excelType = writeWorkbook.getExcelType();
}
@ -114,6 +133,14 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
this.writeWorkbook = writeWorkbook;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public OutputStream getOutputStream() {
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.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
@ -73,56 +75,46 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty {
*/
public List<CellRange> headCellRangeList() {
List<CellRange> cellRangeList = new ArrayList<CellRange>();
int i = 0;
for (Map.Entry<Integer, Head> entry : getHeadMap().entrySet()) {
Head head = entry.getValue();
List<String> columnValues = head.getHeadNameList();
for (int j = 0; j < columnValues.size(); j++) {
int lastRow = getLastRangNum(j, columnValues.get(j), columnValues);
int lastColumn = getLastRangNum(i, columnValues.get(j), head.getHeadNameList());
if ((lastRow > j || lastColumn > i) && lastRow >= 0 && lastColumn >= 0) {
cellRangeList.add(new CellRange(j, lastRow, i, lastColumn));
Set<String> alreadyRangeSet = new HashSet<String>();
List<Head> headList = new ArrayList<Head>(getHeadMap().values());
for (int i = 0; i < headList.size(); i++) {
Head head = headList.get(i);
List<String> headNameList = head.getHeadNameList();
for (int j = 0; j < headNameList.size(); j++) {
if (alreadyRangeSet.contains(i + "-" + j)) {
continue;
}
}
i++;
}
return cellRangeList;
}
/**
* Get the last consecutive string position
*
* @param j
* current value position
* @param value
* value content
* @param values
* 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;
String headName = headNameList.get(j);
int endX = i;
int endY = j;
for (int k = i + 1; k < headList.size(); k++) {
if (headList.get(k).getHeadNameList().get(j).equals(headName)) {
alreadyRangeSet.add(k + "-" + j);
endX = k;
} else {
break;
}
}
// The current cells are not merged
if (endX == i) {
continue;
}
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.util.StyleUtil;
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
*
* @param head
* Nullable
* @return
*/
protected abstract WriteCellStyle headCellStyle(@Nullable Head head);
protected abstract WriteCellStyle headCellStyle(Head head);
/**
* Returns the column width corresponding to each column head
*
* @param head
* Nullable
* @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.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.sun.istack.internal.Nullable;
/**
* Column width style strategy
@ -44,7 +43,6 @@ public abstract class AbstractColumnWidthStyleStrategy implements CellWriteHandl
* @param relativeRowIndex
* @param isHead
*/
protected abstract void setColumnWidth(Sheet sheet, Cell cell, @Nullable Head head, int relativeRowIndex,
boolean isHead);
protected abstract void setColumnWidth(Sheet sheet, Cell cell, Head head, int relativeRowIndex, 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 com.alibaba.excel.metadata.Head;
import com.sun.istack.internal.Nullable;
/**
* Returns the column width according to each column header
@ -29,9 +28,10 @@ public abstract class AbstractHeadColumnWidthStyleStrategy extends AbstractColum
* <li>if return null,ignore
*
* @param head
* Nullable
* @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
* 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
public class SimpleData {
@ExcelProperty("字符串1")
private String string1;
@ExcelProperty("字符串2")
private String string2;
@ExcelProperty("姓名")
private String name;
}

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

@ -26,6 +26,10 @@ public class SimpleDataListener extends AnalysisEventListener<SimpleData> {
@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)));
}
}

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

@ -1,22 +1,70 @@
package com.alibaba.easyexcel.test.core.simple;
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.runners.MethodSorters;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
/**
* Simple data test
*
*
* @author zhuangjiaju
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
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
public void read() {
EasyExcelFactory.read(TestFileUtil.getPath() + "simple" + File.separator + "simple07Test.xlsx",
SimpleData.class, new SimpleDataListener()).sheet().doRead().finish();
public void T03SynchronousRead07() {
synchronousRead(file07);
}
@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();
}
}
return file;
}

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

Binary file not shown.
Loading…
Cancel
Save