diff --git a/src/main/java/com/alibaba/excel/EasyExcelFactory.java b/src/main/java/com/alibaba/excel/EasyExcelFactory.java
index 758d465..7df3750 100644
--- a/src/main/java/com/alibaba/excel/EasyExcelFactory.java
+++ b/src/main/java/com/alibaba/excel/EasyExcelFactory.java
@@ -1,15 +1,16 @@
package com.alibaba.excel;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.event.WriteHandler;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
-
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
+import com.alibaba.excel.write.builder.ExcelWriterBuilder;
/**
* Reader and writer factory class
@@ -69,7 +70,7 @@ public class EasyExcelFactory {
* @return new ExcelWriter.
*/
public static ExcelWriter getWriter(OutputStream outputStream) {
- return new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, true);
+ return writerBuilder().outputFile(outputStream).build();
}
/**
@@ -81,7 +82,11 @@ public class EasyExcelFactory {
* @return new ExcelWriter
*/
public static ExcelWriter getWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) {
- return new ExcelWriter(outputStream, typeEnum, needHead);
+ if (needHead) {
+ return writerBuilder().outputFile(outputStream).excelType(typeEnum).build();
+ } else {
+ return writerBuilder().outputFile(outputStream).excelType(typeEnum).doNotNeedHead().build();
+ }
}
/**
@@ -94,8 +99,13 @@ public class EasyExcelFactory {
* @return new ExcelWriter
*/
public static ExcelWriter getWriterWithTemp(InputStream temp, OutputStream outputStream, ExcelTypeEnum typeEnum,
- boolean needHead) {
- return new ExcelWriter(temp, outputStream, typeEnum, needHead);
+ boolean needHead) {
+ if (needHead) {
+ return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).build();
+ } else {
+ return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).doNotNeedHead()
+ .build();
+ }
}
/**
@@ -109,12 +119,26 @@ public class EasyExcelFactory {
* @param handler User-defined callback
* @return new ExcelWriter
*/
- public static ExcelWriter getWriterWithTempAndHandler(InputStream temp,
- OutputStream outputStream,
- ExcelTypeEnum typeEnum,
- boolean needHead,
- WriteHandler handler) {
- return new ExcelWriter(temp, outputStream, typeEnum, needHead, handler);
+ public static ExcelWriter getWriterWithTempAndHandler(InputStream temp, OutputStream outputStream,
+ ExcelTypeEnum typeEnum, boolean needHead, WriteHandler handler) {
+ if (needHead) {
+ return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum)
+ .registerWriteHandler(handler).build();
+ } else {
+ return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).doNotNeedHead()
+ .registerWriteHandler(handler).build();
+ }
+ }
+
+ public static ExcelWriterBuilder writerBuilder() {
+ return new ExcelWriterBuilder();
}
+ public static ExcelWriterBuilder writerSheetBuilder() {
+ return new ExcelWriterBuilder();
+ }
+
+ public static ExcelWriterBuilder writerTableBuilder() {
+ return new ExcelWriterBuilder();
+ }
}
diff --git a/src/main/java/com/alibaba/excel/ExcelWriter.java b/src/main/java/com/alibaba/excel/ExcelWriter.java
index 652ab99..0b50857 100644
--- a/src/main/java/com/alibaba/excel/ExcelWriter.java
+++ b/src/main/java/com/alibaba/excel/ExcelWriter.java
@@ -2,30 +2,23 @@ package com.alibaba.excel;
import java.io.InputStream;
import java.io.OutputStream;
+import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
-import com.alibaba.excel.converters.BooleanConverter;
import com.alibaba.excel.converters.Converter;
-import com.alibaba.excel.converters.ConverterRegistryCenter;
-import com.alibaba.excel.converters.DateConverter;
-import com.alibaba.excel.converters.DoubleConverter;
-import com.alibaba.excel.converters.FloatConverter;
-import com.alibaba.excel.converters.IntegerConverter;
-import com.alibaba.excel.converters.LongConverter;
-import com.alibaba.excel.converters.StringConverter;
import com.alibaba.excel.event.WriteHandler;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
-import com.alibaba.excel.parameter.GenerateParam;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.ExcelBuilder;
import com.alibaba.excel.write.ExcelBuilderImpl;
-import com.alibaba.excel.write.merge.MergeStrategy;
+import com.alibaba.excel.write.handler.WriteHandler;
/**
- * Excel Writer This tool is used to write value out to Excel via POI. This object can perform the
- * following two functions.
+ * Excel Writer This tool is used to write value out to Excel via POI. This object can perform the following two
+ * functions.
*
*
* 1. Create a new empty Excel workbook, write the value to the stream after the value is filled.
@@ -35,103 +28,107 @@ import com.alibaba.excel.write.merge.MergeStrategy;
* @author jipengfei
*/
public class ExcelWriter {
-
private ExcelBuilder excelBuilder;
/**
* Create new writer
*
- * @param outputStream the java OutputStream you wish to write the value to
- * @param typeEnum 03 or 07
+ * @param templateInputStream
+ * Append value after a POI file ,Can be null(the template POI filesystem that contains the Workbook
+ * stream)
+ * @param outputStream
+ * the java OutputStream you wish to write the value to
+ * @param excelType
+ * 03 or 07
+ * @param needHead
+ * @param customConverterMap
+ * @param customWriteHandlerList
*/
- public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum) {
- this(outputStream, typeEnum, true);
+ public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum excelType,
+ boolean needHead, Map customConverterMap, List customWriteHandlerList) {
+ excelBuilder = new ExcelBuilderImpl(templateInputStream, outputStream, excelType, needHead, customConverterMap,
+ customWriteHandlerList);
}
- @Deprecated
- private Class extends BaseRowModel> objectClass;
-
/**
- * @param generateParam
+ * Create new writer
+ *
+ * @param outputStream
+ * the java OutputStream you wish to write the value to
+ * @param typeEnum
+ * 03 or 07
+ * @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter
*/
@Deprecated
- public ExcelWriter(GenerateParam generateParam) {
- this(generateParam.getOutputStream(), generateParam.getType(), generateParam.isNeedHead());
- this.objectClass = generateParam.getClazz();
+ public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum) {
+ this(outputStream, typeEnum, true);
}
/**
*
* Create new writer
- *
- * @param outputStream the java OutputStream you wish to write the value to
- * @param typeEnum 03 or 07
- * @param needHead Do you need to write the header to the file?
+ *
+ * @param outputStream
+ * the java OutputStream you wish to write the value to
+ * @param typeEnum
+ * 03 or 07
+ * @param needHead
+ * Do you need to write the header to the file?
+ * @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter
*/
+ @Deprecated
public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) {
this(null, outputStream, typeEnum, needHead, null, null);
}
/**
* Create new writer
- *
- * @param templateInputStream Append value after a POI file ,Can be null(the template POI
- * filesystem that contains the Workbook stream)
- * @param outputStream the java OutputStream you wish to write the value to
- * @param typeEnum 03 or 07
+ *
+ * @param templateInputStream
+ * Append value after a POI file ,Can be null(the template POI filesystem that contains the Workbook
+ * stream)
+ * @param outputStream
+ * the java OutputStream you wish to write the value to
+ * @param typeEnum
+ * 03 or 07
+ * @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter
*/
+ @Deprecated
public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum,
- Boolean needHead) {
+ Boolean needHead) {
this(templateInputStream, outputStream, typeEnum, needHead, null, null);
}
-
/**
* Create new writer
- *
- * @param templateInputStream Append value after a POI file ,Can be null(the template POI
- * filesystem that contains the Workbook stream)
- * @param outputStream the java OutputStream you wish to write the value to
- * @param typeEnum 03 or 07
- * @param writeHandler User-defined callback
+ *
+ * @param templateInputStream
+ * Append value after a POI file ,Can be null(the template POI filesystem that contains the Workbook
+ * stream)
+ * @param outputStream
+ * the java OutputStream you wish to write the value to
+ * @param typeEnum
+ * 03 or 07
+ * @param writeHandler
+ * User-defined callback
+ * @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter
*/
+ @Deprecated
public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum,
- Boolean needHead, WriteHandler writeHandler) {
- this(templateInputStream, outputStream, typeEnum, needHead, writeHandler, null);
- }
-
- public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum,
- Boolean needHead, WriteHandler writeHandler, List converters) {
- excelBuilder = new ExcelBuilderImpl(templateInputStream, outputStream, typeEnum, needHead, writeHandler,
- converters);
- if (this.excelBuilder instanceof ConverterRegistryCenter) {
- ConverterRegistryCenter registryCenter = (ConverterRegistryCenter)this.excelBuilder;
- initConverters(registryCenter, converters);
- }
+ Boolean needHead, WriteHandler writeHandler) {
+ List customWriteHandlerList = new ArrayList();
+ customWriteHandlerList.add(writeHandler);
+ excelBuilder =
+ new ExcelBuilderImpl(templateInputStream, outputStream, typeEnum, needHead, null, customWriteHandlerList);
}
- private void initConverters(ConverterRegistryCenter registryCenter, List converters) {
- registerDefaultConverters(registryCenter);
- if (converters != null && converters.size() > 0) {
- for (Converter c : converters) {
- registryCenter.register(c);
- }
- }
- }
- private void registerDefaultConverters(ConverterRegistryCenter registryCenter) {
- registryCenter.register(new StringConverter());
- registryCenter.register(new DateConverter(null));
- registryCenter.register(new IntegerConverter());
- registryCenter.register(new DoubleConverter());
- registryCenter.register(new LongConverter());
- registryCenter.register(new FloatConverter());
- registryCenter.register(new BooleanConverter());
- }
/**
- * Write value to a sheet
- *
- * @param data Data to be written
- * @param sheet Write to this sheet
+ * Write data to a sheet
+ *
+ * @param data
+ * Data to be written
+ * @param sheet
+ * Write to this sheet
* @return this current writer
*/
public ExcelWriter write(List extends BaseRowModel> data, Sheet sheet) {
@@ -139,29 +136,30 @@ public class ExcelWriter {
return this;
}
-
/**
* Write value to a sheet
- *
- * @param data Data to be written
- * @return this current writer
+ *
+ * @param data
+ * Data to be written
+ * @param sheet
+ * Write to this sheet
+ * @param table
+ * Write to this table
+ * @return this
*/
- @Deprecated
- public ExcelWriter write(List data) {
- if (objectClass != null) {
- return this.write(data, new Sheet(1, 0, objectClass));
- } else {
- return this.write0(data, new Sheet(1, 0, objectClass));
-
- }
+ public ExcelWriter write(List extends BaseRowModel> data, Sheet sheet, Table table) {
+ excelBuilder.addContent(data, sheet, table);
+ return this;
}
/**
*
* Write value to a sheet
- *
- * @param data Data to be written
- * @param sheet Write to this sheet
+ *
+ * @param data
+ * Data to be written
+ * @param sheet
+ * Write to this sheet
* @return this
*/
public ExcelWriter write1(List> data, Sheet sheet) {
@@ -171,9 +169,11 @@ public class ExcelWriter {
/**
* Write value to a sheet
- *
- * @param data Data to be written
- * @param sheet Write to this sheet
+ *
+ * @param data
+ * Data to be written
+ * @param sheet
+ * Write to this sheet
* @return this
*/
public ExcelWriter write0(List> data, Sheet sheet) {
@@ -183,23 +183,13 @@ public class ExcelWriter {
/**
* Write value to a sheet
- *
- * @param data Data to be written
- * @param sheet Write to this sheet
- * @param table Write to this table
- * @return this
- */
- public ExcelWriter write(List extends BaseRowModel> data, Sheet sheet, Table table) {
- excelBuilder.addContent(data, sheet, table);
- return this;
- }
-
- /**
- * Write value to a sheet
- *
- * @param data Data to be written
- * @param sheet Write to this sheet
- * @param table Write to this table
+ *
+ * @param data
+ * Data to be written
+ * @param sheet
+ * Write to this sheet
+ * @param table
+ * Write to this table
* @return this
*/
public ExcelWriter write0(List> data, Sheet sheet, Table table) {
@@ -207,22 +197,15 @@ public class ExcelWriter {
return this;
}
- /**
- * Merge Cells,Indexes are zero-based.
- *
- * @param strategies the merge strategies.
- */
- public ExcelWriter merge(List strategies) {
- excelBuilder.merge(strategies);
- return this;
- }
-
/**
* Write value to a sheet
- *
- * @param data Data to be written
- * @param sheet Write to this sheet
- * @param table Write to this table
+ *
+ * @param data
+ * Data to be written
+ * @param sheet
+ * Write to this sheet
+ * @param table
+ * Write to this table
* @return
*/
public ExcelWriter write1(List> data, Sheet sheet, Table table) {
@@ -236,4 +219,5 @@ public class ExcelWriter {
public void finish() {
excelBuilder.finish();
}
+
}
diff --git a/src/main/java/com/alibaba/excel/analysis/BaseSaxAnalyser.java b/src/main/java/com/alibaba/excel/analysis/BaseSaxAnalyser.java
index f4decde..453e26f 100644
--- a/src/main/java/com/alibaba/excel/analysis/BaseSaxAnalyser.java
+++ b/src/main/java/com/alibaba/excel/analysis/BaseSaxAnalyser.java
@@ -1,16 +1,19 @@
package com.alibaba.excel.analysis;
-import java.util.ArrayList;
import java.util.Collection;
+import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Map;
import java.util.Map.Entry;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.BooleanConverter;
import com.alibaba.excel.converters.Converter;
+import com.alibaba.excel.converters.ConverterKey;
import com.alibaba.excel.converters.ConverterRegistryCenter;
import com.alibaba.excel.converters.DateConverter;
+import com.alibaba.excel.converters.Double2Converter;
import com.alibaba.excel.converters.DoubleConverter;
import com.alibaba.excel.converters.FloatConverter;
import com.alibaba.excel.converters.IntegerConverter;
@@ -31,9 +34,10 @@ public abstract class BaseSaxAnalyser implements ConverterRegistryCenter, Analys
protected AnalysisContext analysisContext;
private LinkedHashMap> listeners =
- new LinkedHashMap>();
+ new LinkedHashMap>();
+
+ private Map converters = new HashMap();
- private LinkedHashMap converters = new LinkedHashMap();
/**
* execute method
*/
@@ -50,13 +54,17 @@ public abstract class BaseSaxAnalyser implements ConverterRegistryCenter, Analys
public void register(Converter converter) {
converters.put(converter.getName(), converter);
}
-
+
@Override
public void beforeAnalysis() {
registerDefaultConverters();
}
-
+
private void registerDefaultConverters() {
+ Double2Converter double2Converter = new Double2Converter();
+ converters.put(ConverterKey.buildConverterKey(double2Converter.supportJavaTypeKey(),
+ double2Converter.supportExcelTypeKey()), double2Converter);
+
StringConverter s = new StringConverter();
converters.put(s.getName(), s);
DateConverter d = new DateConverter(this.analysisContext);
@@ -77,6 +85,7 @@ public abstract class BaseSaxAnalyser implements ConverterRegistryCenter, Analys
public Collection getConverters() {
return converters.values();
}
+
@Override
public void analysis(Sheet sheetParam) {
analysisContext.setCurrentSheet(sheetParam);
@@ -92,6 +101,7 @@ public abstract class BaseSaxAnalyser implements ConverterRegistryCenter, Analys
public AnalysisContext getAnalysisContext() {
return analysisContext;
}
+
/**
*/
@Override
@@ -109,9 +119,9 @@ public abstract class BaseSaxAnalyser implements ConverterRegistryCenter, Analys
public void notify(AnalysisFinishEvent event) {
analysisContext.setCurrentRowAnalysisResult(event.getAnalysisResult());
/** Parsing header content **/
- if (analysisContext.getCurrentRowNum() < analysisContext.getCurrentSheet().getHeadLineMun()) {
- if (analysisContext.getCurrentRowNum() <= analysisContext.getCurrentSheet().getHeadLineMun() - 1) {
- buildExcelHeadProperty(null, (List) analysisContext.getCurrentRowAnalysisResult());
+ if (analysisContext.getCurrentRowNum() < analysisContext.getCurrentSheet().getReadHeadRowNumber()) {
+ if (analysisContext.getCurrentRowNum() <= analysisContext.getCurrentSheet().getReadHeadRowNumber() - 1) {
+ buildExcelHeadProperty(null, (List)analysisContext.getCurrentRowAnalysisResult());
}
} else {
for (Entry> entry : listeners.entrySet()) {
@@ -120,10 +130,9 @@ public abstract class BaseSaxAnalyser implements ConverterRegistryCenter, Analys
}
}
-
private void buildExcelHeadProperty(Class extends BaseRowModel> clazz, List headOneRow) {
- ExcelHeadProperty excelHeadProperty = ExcelHeadProperty
- .buildExcelHeadProperty(this.analysisContext.getExcelHeadProperty(), clazz, headOneRow);
+ ExcelHeadProperty excelHeadProperty =
+ ExcelHeadProperty.buildExcelHeadProperty(this.analysisContext.getExcelHeadProperty(), clazz, headOneRow);
this.analysisContext.setExcelHeadProperty(excelHeadProperty);
}
}
diff --git a/src/main/java/com/alibaba/excel/analysis/v07/XlsxRowResultHolder.java b/src/main/java/com/alibaba/excel/analysis/v07/XlsxRowResultHolder.java
index 6320618..6269b3b 100644
--- a/src/main/java/com/alibaba/excel/analysis/v07/XlsxRowResultHolder.java
+++ b/src/main/java/com/alibaba/excel/analysis/v07/XlsxRowResultHolder.java
@@ -1,11 +1,13 @@
package com.alibaba.excel.analysis.v07;
+import com.alibaba.excel.metadata.CellData;
+
public interface XlsxRowResultHolder {
void clearResult();
void appendCurrentCellValue(String currentCellValue);
-
- String[] getCurRowContent();
+
+ CellData[] getCurRowContent();
int getColumnSize();
}
diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/DefaultCellHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/DefaultCellHandler.java
index abce458..2135311 100644
--- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/DefaultCellHandler.java
+++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/DefaultCellHandler.java
@@ -1,60 +1,61 @@
package com.alibaba.excel.analysis.v07.handlers;
-import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_VALUE_TAG;
+import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_FORMULA_TAG;
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_1;
+import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_VALUE_TYPE_TAG;
import java.util.Arrays;
+import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.xssf.model.SharedStringsTable;
-import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import com.alibaba.excel.analysis.v07.XlsxCellHandler;
import com.alibaba.excel.analysis.v07.XlsxRowResultHolder;
-import com.alibaba.excel.annotation.FieldType;
import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.AnalysisContext;
+import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.event.AnalysisEventRegistryCenter;
+import com.alibaba.excel.metadata.CellData;
+import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.util.PositionUtils;
+import com.alibaba.excel.util.StringUtils;
public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder {
- private String currentCellIndex;
-
- private FieldType currentCellType;
-
- private int curRow;
-
- private int curCol;
-
- private String[] curRowContent = new String[20];
-
- private String currentCellValue;
-
private final AnalysisContext analysisContext;
-
private final AnalysisEventRegistryCenter registerCenter;
-
private final SharedStringsTable sst;
+ private String currentTag;
+ private String currentCellIndex;
+ private int curRow;
+ private int curCol;
+ private CellData[] curRowContent = new CellData[20];
+ private CellData currentCellData;
- public DefaultCellHandler(AnalysisContext analysisContext, AnalysisEventRegistryCenter registerCenter, SharedStringsTable sst) {
+ public DefaultCellHandler(AnalysisContext analysisContext, AnalysisEventRegistryCenter registerCenter,
+ SharedStringsTable sst) {
this.analysisContext = analysisContext;
this.registerCenter = registerCenter;
this.sst = sst;
}
-
+
@Override
public void clearResult() {
- curRowContent = new String[20];
+ curRowContent = new CellData[20];
}
@Override
public boolean support(String name) {
- return CELL_VALUE_TAG.equals(name) || CELL_VALUE_TAG_1.equals(name) || CELL_TAG.equals(name);
+ return CELL_VALUE_TAG.equals(name) || CELL_FORMULA_TAG.equals(name) || CELL_VALUE_TAG_1.equals(name)
+ || CELL_TAG.equals(name);
}
@Override
public void startHandle(String name, Attributes attributes) {
+ currentTag = name;
+ // start a cell
if (CELL_TAG.equals(name)) {
currentCellIndex = attributes.getValue(ExcelXmlConstants.POSITION);
int nextRow = PositionUtils.getRow(currentCellIndex);
@@ -65,51 +66,67 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
analysisContext.setCurrentRowNum(curRow);
curCol = PositionUtils.getCol(currentCellIndex);
- String cellType = attributes.getValue("t");
- currentCellType = FieldType.EMPTY;
- if (cellType != null && cellType.equals("s")) {
- currentCellType = FieldType.STRING;
- }
+ // t="s" ,it's means String
+ // t="b" ,it's means Boolean
+ // t is null ,it's means Empty or Number
+ CellDataTypeEnum type = CellDataTypeEnum.buildFromCellType(attributes.getValue(CELL_VALUE_TYPE_TAG));
+ currentCellData = new CellData(type);
}
- if (name.equals(CELL_VALUE_TAG) || name.equals(CELL_VALUE_TAG_1)) {
- // initialize current cell value
- currentCellValue = "";
+ // cell is formula
+ if (CELL_FORMULA_TAG.equals(name)) {
+ currentCellData.setReadIsFormula(Boolean.TRUE);
}
}
@Override
public void endHandle(String name) {
- ensureSize();
if (CELL_VALUE_TAG.equals(name)) {
- switch (currentCellType) {
- case STRING:
- int idx = Integer.parseInt(currentCellValue);
- currentCellValue = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
- currentCellType = FieldType.EMPTY;
- break;
+ ensureSize();
+ // Have to go "sharedStrings.xml" and get it
+ if (currentCellData.getType() == CellDataTypeEnum.STRING) {
+ RichTextString richTextString = sst.getItemAt(Integer.parseInt(currentCellData.getStringValue()));
+ currentCellData.setStringValue(richTextString.toString());
}
- curRowContent[curCol] = currentCellValue;
- } else if (CELL_VALUE_TAG_1.equals(name)) {
- curRowContent[curCol] = currentCellValue;
+ curRowContent[curCol] = currentCellData;
}
}
-
-
private void ensureSize() {
// try to size
if (curCol >= curRowContent.length) {
- curRowContent = Arrays.copyOf(curRowContent, (int) (curCol * 1.5));
+ curRowContent = Arrays.copyOf(curRowContent, (int)(curCol * 1.5));
}
}
@Override
public void appendCurrentCellValue(String currentCellValue) {
- this.currentCellValue += currentCellValue;
+ if (StringUtils.isEmpty(currentCellValue)) {
+ return;
+ }
+ if (CELL_FORMULA_TAG.equals(currentTag)) {
+ currentCellData.setReadFormula(currentCellValue);
+ return;
+ }
+ CellDataTypeEnum oldType = currentCellData.getType();
+ switch (oldType) {
+ case STRING:
+ case ERROR:
+ currentCellData.setStringValue(currentCellValue);
+ break;
+ case BOOLEAN:
+ currentCellData.setBooleanValue(BooleanUtils.valueOf(currentCellValue));
+ break;
+ case EMPTY:
+ currentCellData.setType(CellDataTypeEnum.NUMBER);
+ currentCellData.setDoubleValue(Double.valueOf(currentCellValue));
+ break;
+ default:
+ throw new IllegalStateException("Cannot set values now");
+ }
}
@Override
- public String[] getCurRowContent() {
+ public CellData[] getCurRowContent() {
return this.curRowContent;
}
diff --git a/src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java b/src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java
index dcd2d5a..b3e7c20 100644
--- a/src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java
+++ b/src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java
@@ -10,7 +10,9 @@ public class ExcelXmlConstants {
public static final String ROW_TAG = "row";
public static final String CELL_TAG = "c";
+ public static final String CELL_FORMULA_TAG = "f";
public static final String CELL_VALUE_TAG = "v";
+ public static final String CELL_VALUE_TYPE_TAG = "t";
public static final String CELL_VALUE_TAG_1 = "t";
diff --git a/src/main/java/com/alibaba/excel/context/WriteContext.java b/src/main/java/com/alibaba/excel/context/WriteContext.java
index 3a24606..17d978d 100644
--- a/src/main/java/com/alibaba/excel/context/WriteContext.java
+++ b/src/main/java/com/alibaba/excel/context/WriteContext.java
@@ -1,37 +1,47 @@
package com.alibaba.excel.context;
-import java.io.OutputStream;
-
-import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
-import com.alibaba.excel.converters.ConverterRegistryCenter;
-import com.alibaba.excel.event.WriteHandler;
import com.alibaba.excel.metadata.ExcelHeadProperty;
-import com.alibaba.excel.metadata.SheetHolder;
import com.alibaba.excel.metadata.Table;
+import com.alibaba.excel.metadata.holder.ConfigurationSelector;
+/**
+ * Write context
+ *
+ * @author jipengfei
+ */
public interface WriteContext {
+ /**
+ * If the current sheet already exists, select it; if not, create it
+ *
+ * @param sheet
+ */
+ void currentSheet(com.alibaba.excel.metadata.Sheet sheet);
- Sheet getCurrentSheet();
-
- boolean needHead();
+ /**
+ * If the current table already exists, select it; if not, create it
+ *
+ * @param table
+ */
+ void currentTable(Table table);
- ExcelHeadProperty getExcelHeadProperty();
+ /**
+ * Configuration of currently operated cell
+ *
+ * @return
+ */
+ ConfigurationSelector configurationSelector();
- void currentSheet(com.alibaba.excel.metadata.Sheet sheet);
-
- void currentTable(Table table);
+ Sheet getCurrentSheet();
- OutputStream getOutputStream();
+ ExcelHeadProperty getExcelHeadProperty();
Workbook getWorkbook();
- @Deprecated
- WriteHandler getWriteHandler();
-
- CellStyle getCurrentContentStyle();
-
- ConverterRegistryCenter getConverterRegistryCenter();
+ /**
+ * close
+ */
+ void finish();
}
diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java
index d1404f7..b543b67 100644
--- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java
+++ b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java
@@ -3,28 +3,44 @@ package com.alibaba.excel.context;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterRegistryCenter;
-import com.alibaba.excel.event.WriteHandler;
+import com.alibaba.excel.converters.bigdecimal.BigDecimalNumberConverter;
+import com.alibaba.excel.converters.date.DateStringConverter;
+import com.alibaba.excel.event.NotRepeatExecutor;
+import com.alibaba.excel.event.Order;
+import com.alibaba.excel.exception.ExcelGenerateException;
+import com.alibaba.excel.metadata.CellStyle;
import com.alibaba.excel.metadata.ExcelHeadProperty;
+import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.metadata.Head;
-import com.alibaba.excel.metadata.SheetHolder;
import com.alibaba.excel.metadata.Table;
-import com.alibaba.excel.metadata.TableHolder;
+import com.alibaba.excel.metadata.holder.ConfigurationSelector;
+import com.alibaba.excel.metadata.holder.SheetHolder;
+import com.alibaba.excel.metadata.holder.TableHolder;
+import com.alibaba.excel.metadata.holder.WorkbookHolder;
import com.alibaba.excel.support.ExcelTypeEnum;
-import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.util.WorkBookUtil;
-import com.alibaba.excel.write.style.CellStyleStrategy;
+import com.alibaba.excel.write.handler.WriteHandler;
+import com.alibaba.excel.write.style.RowCellStyleStrategy;
+import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
/**
* A context is the main anchorage point of a excel writer.
@@ -32,10 +48,13 @@ import com.alibaba.excel.write.style.CellStyleStrategy;
* @author jipengfei
*/
public class WriteContextImpl implements WriteContext {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(WriteContextImpl.class);
+
/**
- * prevent duplicate creation of sheet objects
+ * The Workbook currently written
*/
- private final Map hasBeenInitializedSheet = new HashMap();
+ private WorkbookHolder currentWorkbookHolder;
/**
* Current sheet holder
*/
@@ -45,37 +64,122 @@ public class WriteContextImpl implements WriteContext {
*/
private TableHolder currentTableHolder;
/**
- * Excel type
+ * Configuration of currently operated cell
*/
- private ExcelTypeEnum excelType;
-
+ private ConfigurationSelector currentConfigurationSelector;
/**
- * POI Workbook
+ * Excel type
*/
- private Workbook workbook;
-
+ private ExcelTypeEnum excelType;
/**
* Final output stream
*/
private OutputStream outputStream;
-
/**
- * If sheet and table don't have {@link CellStyleStrategy} , use this one. If they have, use their own
+ * Final output stream
*/
- private CellStyleStrategy defalutCellStyleStrategy;
+ private InputStream templateInputStream;
+
+ public WriteContextImpl(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum excelType,
+ Boolean needHead, Map customConverterMap, List customWriteHandlerList) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Begin to Initialization 'WriteContextImpl'");
+ }
+ initCurrentWorkbookHolder(needHead, customConverterMap, customWriteHandlerList);
+ this.excelType = excelType;
+ this.outputStream = outputStream;
+ this.templateInputStream = templateInputStream;
+ try {
+ currentWorkbookHolder.setWorkbook(WorkBookUtil.createWorkBook(templateInputStream, excelType));
+ } catch (IOException e) {
+ throw new ExcelGenerateException("Create workbook failure", e);
+ }
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Initialization 'WriteContextImpl' complete");
+ }
+ }
+
+ private void initCurrentWorkbookHolder(Boolean needHead, Map customConverterMap,
+ List customWriteHandlerList) {
+ currentWorkbookHolder = new WorkbookHolder();
+ if (needHead == null) {
+ currentWorkbookHolder.setNeedHead(Boolean.TRUE);
+ } else {
+ currentWorkbookHolder.setNeedHead(needHead);
+ }
+ List handlerList = new ArrayList();
+ if (customWriteHandlerList != null && !customWriteHandlerList.isEmpty()) {
+ handlerList.addAll(customWriteHandlerList);
+ }
+ handlerList.addAll(loadDefaultHandler());
+ currentWorkbookHolder.setWriteHandlerList(sortAndClearUpHandler(handlerList));
+ Map converterMap = loadDefaultConverter();
+ if (customConverterMap != null && !customConverterMap.isEmpty()) {
+ converterMap.putAll(customConverterMap);
+ }
+ currentWorkbookHolder.setConverterMap(converterMap);
+ currentWorkbookHolder.setHasBeenInitializedSheet(new HashMap());
+ currentConfigurationSelector = currentWorkbookHolder;
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("CurrentConfigurationSelector is currentWorkbookHolder");
+ }
+ }
- private WriteHandler writeHandler;
+ private List sortAndClearUpHandler(List handlerList) {
+ // sort
+ Map> orderExcelWriteHandlerMap =
+ new TreeMap>();
+ for (WriteHandler handler : handlerList) {
+ int order = Integer.MIN_VALUE;
+ if (handler instanceof Order) {
+ order = ((Order)handler).order();
+ }
+ if (orderExcelWriteHandlerMap.containsKey(order)) {
+ orderExcelWriteHandlerMap.get(order).add(handler);
+ } else {
+ List tempHandlerList = new ArrayList();
+ tempHandlerList.add(handler);
+ orderExcelWriteHandlerMap.put(order, tempHandlerList);
+ }
+ }
+ // clean up
+ Set alreadyExistedHandlerSet = new HashSet();
+ List result = new ArrayList();
+ for (Map.Entry> entry : orderExcelWriteHandlerMap.entrySet()) {
+ for (WriteHandler handler : entry.getValue()) {
+ if (handler instanceof NotRepeatExecutor) {
+ String uniqueValue = ((NotRepeatExecutor)handler).uniqueValue();
+ if (alreadyExistedHandlerSet.contains(uniqueValue)) {
+ continue;
+ }
+ alreadyExistedHandlerSet.add(uniqueValue);
+ }
+ result.add(handler);
+ }
+ }
+ return result;
+ }
- private ConverterRegistryCenter registryCenter;
+ private List loadDefaultHandler() {
+ List handlerList = new ArrayList();
+ CellStyle headCellStyle = new CellStyle();
+ Font font = new Font();
+ headCellStyle.setFont(font);
+ font.setFontName("宋体");
+ font.setBold(true);
+ headCellStyle.setIndexedColors(IndexedColors.GREY_25_PERCENT);
+ handlerList.add(new RowCellStyleStrategy(headCellStyle, new ArrayList()));
+ handlerList.add(new SimpleColumnWidthStyleStrategy(20));
+ return handlerList;
+ }
- public WriteContextImpl(InputStream templateInputStream, OutputStream out, ExcelTypeEnum excelType,
- boolean needHead, WriteHandler writeHandler, ConverterRegistryCenter registryCenter) throws IOException {
- this.needHead = needHead;
- this.outputStream = out;
- this.writeHandler = writeHandler;
- this.workbook = WorkBookUtil.createWorkBook(templateInputStream, excelType);
- this.defaultCellStyle = StyleUtil.buildDefaultCellStyle(this.workbook);
- this.registryCenter = registryCenter;
+ private Map loadDefaultConverter() {
+ Map converterMap = new HashMap();
+ DateStringConverter dateStringConverter = new DateStringConverter();
+ converterMap.put(dateStringConverter.supportJavaTypeKey(), dateStringConverter);
+ BigDecimalNumberConverter bigDecimalNumberConverter = new BigDecimalNumberConverter();
+ converterMap.put(bigDecimalNumberConverter.supportJavaTypeKey(), bigDecimalNumberConverter);
+ return converterMap;
}
/**
@@ -86,83 +190,82 @@ public class WriteContextImpl implements WriteContext {
if (sheet == null) {
throw new IllegalArgumentException("Sheet argument cannot be null");
}
- if (hasBeenInitializedSheet.containsKey(sheet.getSheetNo())) {
- currentSheetHolder = hasBeenInitializedSheet.get(sheet.getSheetNo());
- return;
+ if (sheet.getSheetNo() == null || sheet.getSheetNo() <= 0) {
+ sheet.setSheetNo(0);
}
- // create sheet
- currentSheetParam = sheet;
- try {
- this.currentSheet = workbook.getSheetAt(sheet.getSheetNo() - 1);
- } catch (Exception e) {
- this.currentSheet = WorkBookUtil.createSheet(workbook, sheet);
- if (null != writeHandler) {
- this.writeHandler.sheet(sheet.getSheetNo(), currentSheet);
+ if (currentWorkbookHolder.getHasBeenInitializedSheet().containsKey(sheet.getSheetNo())) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Sheet:{} is already existed", sheet.getSheetNo());
}
+ currentSheetHolder = currentWorkbookHolder.getHasBeenInitializedSheet().get(sheet.getSheetNo());
+ currentConfigurationSelector = currentSheetHolder;
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("CurrentConfigurationSelector is currentSheetHolder");
+ }
+ return;
}
+ initCurrentSheetHolder(sheet);
// Initialization current sheet
- initCurrentSheet();
- }
-
- private void initCurrentSheet() {
- // Initialization head
- initExcelHeadProperty();
- // Initialization cell style strategy
- initCellStyleStrategy();
- // Initialization sheet head
- initSheetHead();
+ initCurrentSheet(sheet);
}
- private void initCellStyleStrategy() {
- if (currentSheetParam.getCellStyleStrategy() != null) {
- currentSheetHolder.setCellStyleStrategy(currentSheetParam.getCellStyleStrategy());
+ private void initCurrentSheetHolder(com.alibaba.excel.metadata.Sheet sheet) {
+ currentSheetHolder = new SheetHolder();
+ currentSheetHolder.setSheetParam(sheet);
+ if (sheet.getNeedHead() == null) {
+ currentSheetHolder.setNeedHead(currentConfigurationSelector.needHead());
+ } else {
+ currentSheetHolder.setNeedHead(sheet.getNeedHead());
}
- currentSheetHolder.setCellStyleStrategy(defalutCellStyleStrategy);
- }
-
- private void initTableCellStyleStrategy() {
- if (.getCellStyleStrategy() != null) {
- currentSheetHolder.setCellStyleStrategy(currentSheetParam.getCellStyleStrategy());
+ if (sheet.getWriteRelativeHeadRowIndex() == null) {
+ currentSheetHolder.setWriteRelativeHeadRowIndex(currentConfigurationSelector.writeRelativeHeadRowIndex());
+ } else {
+ currentSheetHolder.setNeedHead(sheet.getWriteRelativeHeadRowIndex());
}
- currentSheetHolder.setCellStyleStrategy(defalutCellStyleStrategy);
- }
- /**
- * init excel header
- */
- private void initExcelHeadProperty() {
- currentSheetHolder
- .setExcelHeadProperty(new ExcelHeadProperty(currentSheetParam.getClazz(), currentSheetParam.getHead()));
- }
+ List handlerList = new ArrayList();
+ if (sheet.getCustomWriteHandlerList() != null && !sheet.getCustomWriteHandlerList().isEmpty()) {
+ handlerList.addAll(sheet.getCustomWriteHandlerList());
+ }
+ handlerList.addAll(currentConfigurationSelector.writeHandlerList());
+ currentSheetHolder.setWriteHandlerList(sortAndClearUpHandler(handlerList));
- /**
- * init table excel header
- */
- private void initTableExcelHeadProperty() {
- currentTableHolder.setExcelHeadProperty(
- new ExcelHeadProperty(getCurrentTableParam().getClazz(), getCurrentTableParam().getHead()));
+ Map converterMap = new HashMap(currentConfigurationSelector.converterMap());
+ if (sheet.getCustomConverterMap() != null && !sheet.getCustomConverterMap().isEmpty()) {
+ converterMap.putAll(sheet.getCustomConverterMap());
+ }
+ currentWorkbookHolder.setConverterMap(converterMap);
+ currentSheetHolder.setHasBeenInitializedTable(new HashMap());
+ currentWorkbookHolder.getHasBeenInitializedSheet().put(sheet.getSheetNo(), currentSheetHolder);
+ currentConfigurationSelector = currentSheetHolder;
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("CurrentConfigurationSelector is currentSheetHolder");
+ }
}
- /**
- * init sheet column with
- */
- public void initSheetColumnWidth() {
- for (Head head : currentSheetHolder.getExcelHeadProperty().getHeadList()) {
- currentSheet.setColumnWidth(head.getColumnIndex(), currentSheetHolder.getColumnWidthStyleStrategy()
- .columnWidth(head.getColumnIndex(), head.getFieldName()));
+ private void initCurrentSheet(com.alibaba.excel.metadata.Sheet sheet) {
+ Sheet currentSheet;
+ try {
+ currentSheet = currentWorkbookHolder.getWorkbook().getSheetAt(sheet.getSheetNo());
+ } catch (Exception e) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.info("Can not find sheet:{} ,now create it", sheet.getSheetNo());
+ }
+ currentSheet = WorkBookUtil.createSheet(currentWorkbookHolder.getWorkbook(), sheet);
}
+ currentSheetHolder.setSheet(currentSheet);
+ // Initialization head
+ currentSheetHolder.setExcelHeadProperty(new ExcelHeadProperty(sheet.getClazz(), sheet.getHead()));
+ // Initialization head
+ initHead();
}
- public void initSheetHead() {
- if (!currentSheetHolder.isNeedHead() || !currentSheetHolder.getExcelHeadProperty().hasHead()) {
+ public void initHead(ExcelHeadProperty excelHeadPropert) {
+ if (!currentConfigurationSelector.needHead() || !currentSheetHolder.getExcelHeadProperty().hasHead()) {
return;
}
int startRow = getCurrentSheet().getLastRowNum();
- if (startRow > 0) {
- startRow += 4;
- } else {
- startRow = getCurrentSheetParam().getStartRow();
- }
+ startRow += currentConfigurationSelector.writeRelativeHeadRowIndex();
// Combined head
addMergedRegionToCurrentSheet(startRow);
for (int i = startRow; i < currentSheetHolder.getExcelHeadProperty().getHeadRowNumber() + startRow; i++) {
@@ -174,8 +277,6 @@ public class WriteContextImpl implements WriteContext {
}
addOneRowOfHeadDataToExcel(row, i, currentSheetHolder.getExcelHeadProperty().getHeadList());
}
- // Initialization sheet column width
- initSheetColumnWidth();
}
public void initTableHead() {
@@ -270,15 +371,6 @@ public class WriteContextImpl implements WriteContext {
return this.needHead;
}
- @Override
- public Sheet getCurrentSheet() {
- return currentSheetHolder.getSheet();
- }
-
- public void setCurrentSheet(Sheet currentSheet) {
- this.currentSheet = currentSheet;
- }
-
public String getCurrentSheetName() {
return currentSheetHolder.getCurrentSheetParam();
}
@@ -333,4 +425,20 @@ public class WriteContextImpl implements WriteContext {
public ConverterRegistryCenter getConverterRegistryCenter() {
return registryCenter;
}
+
+ @Override
+ public void finish() {
+ try {
+ workbook.write(outputStream);
+ workbook.close();
+ if (outputStream != null) {
+ outputStream.close();
+ }
+ if (templateInputStream != null) {
+ templateInputStream.close();
+ }
+ } catch (IOException e) {
+ throw new ExcelGenerateException("Can not close IO", e);
+ }
+ }
}
diff --git a/src/main/java/com/alibaba/excel/converters/BigDecimalConverter.java b/src/main/java/com/alibaba/excel/converters/BigDecimalConverter.java
deleted file mode 100644
index feee369..0000000
--- a/src/main/java/com/alibaba/excel/converters/BigDecimalConverter.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.alibaba.excel.converters;
-
-import java.math.BigDecimal;
-
-import org.apache.poi.ss.usermodel.Cell;
-
-import com.alibaba.excel.metadata.ExcelColumnProperty;
-
-public class BigDecimalConverter implements Converter {
- @Override
- public String getName() {
- return "big-decimal-converter";
- }
-
- @Override
- public boolean support(ExcelColumnProperty columnProperty) {
- return BigDecimal.class.equals(columnProperty.getField().getType());
- }
- @Override
- public Object convert(String value, ExcelColumnProperty columnProperty) {
- return new BigDecimal(value);
- }
- @Override
- public Cell convert(Cell cell, Object value, ExcelColumnProperty columnProperty) {
- cell.setCellValue(Double.parseDouble(value.toString()));
- return cell;
- }
- @Override
- public boolean support(Object cellValue) {
- return cellValue instanceof BigDecimal;
- }
-
-}
diff --git a/src/main/java/com/alibaba/excel/converters/BooleanConverter.java b/src/main/java/com/alibaba/excel/converters/BooleanConverter.java
deleted file mode 100644
index bca16d7..0000000
--- a/src/main/java/com/alibaba/excel/converters/BooleanConverter.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.alibaba.excel.converters;
-
-import java.lang.reflect.Field;
-
-import org.apache.poi.ss.usermodel.Cell;
-
-import com.alibaba.excel.metadata.ExcelColumnProperty;
-
-public class BooleanConverter implements Converter {
- @Override
- public String getName() {
- return "boolean-converter";
- }
- @Override
- public boolean support(ExcelColumnProperty columnProperty) {
- Field field = columnProperty.getField();
- return Boolean.class.equals(field.getType()) || boolean.class.equals(field.getType());
- }
- @Override
- public Object convert(String value, ExcelColumnProperty columnProperty) {
- String valueLower = value.toLowerCase();
- if (valueLower.equals("true") || valueLower.equals("false")) {
- return Boolean.parseBoolean(value.toLowerCase());
- }
- Integer integer = Integer.parseInt(value);
- if (integer == 0) {
- return false;
- } else {
- return true;
- }
- }
- @Override
- public Cell convert(Cell cell, Object value, ExcelColumnProperty columnProperty) {
- cell.setCellValue(String.valueOf(value));
- return cell;
- }
-
- @Override
- public boolean support(Object cellValue) {
- return cellValue instanceof Boolean || boolean.class.equals(cellValue.getClass());
- }
-}
diff --git a/src/main/java/com/alibaba/excel/converters/Converter.java b/src/main/java/com/alibaba/excel/converters/Converter.java
index 11bbcdb..7a9a11b 100644
--- a/src/main/java/com/alibaba/excel/converters/Converter.java
+++ b/src/main/java/com/alibaba/excel/converters/Converter.java
@@ -1,13 +1,17 @@
package com.alibaba.excel.converters;
-import org.apache.poi.ss.usermodel.Cell;
-
+import com.alibaba.excel.enums.CellDataTypeEnum;
+import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.ExcelColumnProperty;
+import com.sun.istack.internal.NotNull;
+
+public interface Converter {
+
+ Class supportJavaTypeKey();
+
+ CellDataTypeEnum supportExcelTypeKey();
+
+ T convertToJavaData(@NotNull CellData cellData, ExcelColumnProperty columnProperty) throws Exception;
-public interface Converter {
- String getName();
- boolean support(ExcelColumnProperty columnProperty);
- boolean support(Object cellValue);
- Object convert(String value, ExcelColumnProperty columnProperty);
- Cell convert(Cell cell, Object value, ExcelColumnProperty columnProperty);
+ CellData convertToExcelData(@NotNull T value, ExcelColumnProperty columnProperty) throws Exception;
}
diff --git a/src/main/java/com/alibaba/excel/converters/ConverterKey.java b/src/main/java/com/alibaba/excel/converters/ConverterKey.java
new file mode 100644
index 0000000..037ba81
--- /dev/null
+++ b/src/main/java/com/alibaba/excel/converters/ConverterKey.java
@@ -0,0 +1,48 @@
+package com.alibaba.excel.converters;
+
+import com.alibaba.excel.enums.CellDataTypeEnum;
+
+/**
+ * Converter unique key
+ *
+ * @author zhuangjiaju
+ */
+public class ConverterKey {
+
+ private Class javaTypeKey;
+ private CellDataTypeEnum excelTypeKey;
+
+ public ConverterKey(Class javaTypeKey, CellDataTypeEnum excelTypeKey) {
+ if (javaTypeKey == null || excelTypeKey == null) {
+ throw new IllegalArgumentException("All parameters can not be null");
+ }
+ this.javaTypeKey = javaTypeKey;
+ this.excelTypeKey = excelTypeKey;
+ }
+
+ public static ConverterKey buildConverterKey(Class javaTypeKey, CellDataTypeEnum excelTypeKey) {
+ return new ConverterKey(javaTypeKey, excelTypeKey);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ ConverterKey that = (ConverterKey)o;
+ if (javaTypeKey != null ? !javaTypeKey.equals(that.javaTypeKey) : that.javaTypeKey != null) {
+ return false;
+ }
+ return excelTypeKey == that.excelTypeKey;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = javaTypeKey != null ? javaTypeKey.hashCode() : 0;
+ result = 31 * result + (excelTypeKey != null ? excelTypeKey.hashCode() : 0);
+ return result;
+ }
+}
diff --git a/src/main/java/com/alibaba/excel/converters/DateConverter.java b/src/main/java/com/alibaba/excel/converters/DateConverter.java
deleted file mode 100644
index 40f9abe..0000000
--- a/src/main/java/com/alibaba/excel/converters/DateConverter.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package com.alibaba.excel.converters;
-
-import java.util.Date;
-
-import org.apache.poi.hssf.usermodel.HSSFDateUtil;
-import org.apache.poi.ss.usermodel.Cell;
-
-import com.alibaba.excel.context.AnalysisContext;
-import com.alibaba.excel.metadata.ExcelColumnProperty;
-import com.alibaba.excel.util.StringUtils;
-import com.alibaba.excel.util.TypeUtil;
-
-public class DateConverter implements Converter {
- private final AnalysisContext context;
-
- public DateConverter(AnalysisContext context) {
- this.context = context;
- }
-
- @Override
- public String getName() {
- return "date-converter";
- }
- @Override
- public boolean support(ExcelColumnProperty columnProperty) {
- return Date.class.equals(columnProperty.getField().getType());
- }
-
- @Override
- public Object convert(String value, ExcelColumnProperty columnProperty) {
- if (value.contains("-") || value.contains("/") || value.contains(":")) {
- return TypeUtil.getSimpleDateFormatDate(value, columnProperty.getFormat());
- } else {
- Double d = Double.parseDouble(value);
- return HSSFDateUtil.getJavaDate(d, context != null ? context.use1904WindowDate() : false);
- }
- }
-
- @Override
- public Cell convert(Cell cell, Object value, ExcelColumnProperty columnProperty) {
- Date d = (Date)value;
- if (columnProperty != null && StringUtils.isEmpty(columnProperty.getFormat()) == false) {
- cell.setCellValue(TypeUtil.formatDate(d, columnProperty.getFormat()));
- } else {
- cell.setCellValue(d);
- }
-
- return cell;
- }
-
- @Override
- public boolean support(Object cellValue) {
- return cellValue instanceof Date;
- }
-}
diff --git a/src/main/java/com/alibaba/excel/converters/DoubleConverter.java b/src/main/java/com/alibaba/excel/converters/DoubleConverter.java
deleted file mode 100644
index 27efbb6..0000000
--- a/src/main/java/com/alibaba/excel/converters/DoubleConverter.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.alibaba.excel.converters;
-
-import java.lang.reflect.Field;
-
-import org.apache.poi.ss.usermodel.Cell;
-
-import com.alibaba.excel.metadata.ExcelColumnProperty;
-import com.alibaba.excel.util.TypeUtil;
-
-public class DoubleConverter implements Converter {
- @Override
- public String getName() {
- return "double-converter";
- }
- @Override
- public boolean support(ExcelColumnProperty columnProperty) {
- Field field = columnProperty.getField();
- return Double.class.equals(field.getType()) || double.class.equals(field.getType());
- }
- @Override
- public Object convert(String value, ExcelColumnProperty columnProperty) {
- return TypeUtil.formatFloat(value);
- }
- @Override
- public Cell convert(Cell cell, Object value, ExcelColumnProperty columnProperty) {
- cell.setCellValue(Double.parseDouble(value.toString()));
- return cell;
- }
- @Override
- public boolean support(Object cellValue) {
- return cellValue instanceof Double || double.class.equals(cellValue.getClass());
- }
-}
diff --git a/src/main/java/com/alibaba/excel/converters/FloatConverter.java b/src/main/java/com/alibaba/excel/converters/FloatConverter.java
deleted file mode 100644
index 5c17c62..0000000
--- a/src/main/java/com/alibaba/excel/converters/FloatConverter.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.alibaba.excel.converters;
-
-import org.apache.poi.ss.usermodel.Cell;
-
-import com.alibaba.excel.metadata.ExcelColumnProperty;
-import com.alibaba.excel.util.TypeUtil;
-
-public class FloatConverter implements Converter {
- @Override
- public String getName() {
- return "float-converter";
- }
- @Override
- public boolean support(ExcelColumnProperty columnProperty) {
- return Float.class.equals(columnProperty.getField().getType());
- }
- @Override
- public Object convert(String value, ExcelColumnProperty columnProperty) {
- return TypeUtil.formatFloat(value);
- }
- @Override
- public Cell convert(Cell cell, Object value, ExcelColumnProperty columnProperty) {
- cell.setCellValue(Double.parseDouble(value.toString()));
- return cell;
- }
-
- @Override
- public boolean support(Object cellValue) {
- return cellValue instanceof Float || float.class.equals(cellValue.getClass());
- }
-}
diff --git a/src/main/java/com/alibaba/excel/converters/IntegerConverter.java b/src/main/java/com/alibaba/excel/converters/IntegerConverter.java
deleted file mode 100644
index 6433992..0000000
--- a/src/main/java/com/alibaba/excel/converters/IntegerConverter.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.alibaba.excel.converters;
-
-import java.lang.reflect.Field;
-
-import org.apache.poi.ss.usermodel.Cell;
-
-import com.alibaba.excel.metadata.ExcelColumnProperty;
-
-public class IntegerConverter implements Converter {
- @Override
- public String getName() {
- return "integer-converter";
- }
- @Override
- public boolean support(ExcelColumnProperty columnProperty) {
- Field field = columnProperty.getField();
- return Integer.class.equals(field.getType()) || int.class.equals(field.getType());
- }
- @Override
- public Object convert(String value, ExcelColumnProperty columnProperty) {
- return Integer.parseInt(value);
- }
- @Override
- public Cell convert(Cell cell, Object value, ExcelColumnProperty columnProperty) {
- cell.setCellValue(Double.parseDouble(value.toString()));
- return cell;
- }
-
- @Override
- public boolean support(Object cellValue) {
- return cellValue instanceof Integer || int.class.equals(cellValue.getClass());
- }
-}
diff --git a/src/main/java/com/alibaba/excel/converters/LongConverter.java b/src/main/java/com/alibaba/excel/converters/LongConverter.java
deleted file mode 100644
index 36245a1..0000000
--- a/src/main/java/com/alibaba/excel/converters/LongConverter.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.alibaba.excel.converters;
-
-import java.lang.reflect.Field;
-
-import org.apache.poi.ss.usermodel.Cell;
-
-import com.alibaba.excel.metadata.ExcelColumnProperty;
-
-public class LongConverter implements Converter {
- @Override
- public String getName() {
- return "long-converter";
- }
- @Override
- public boolean support(ExcelColumnProperty columnProperty) {
- Field field = columnProperty.getField();
- return Long.class.equals(field.getType()) || long.class.equals(field.getType());
- }
- @Override
- public Object convert(String value, ExcelColumnProperty columnProperty) {
- return Long.parseLong(value);
- }
- @Override
- public Cell convert(Cell cell, Object value, ExcelColumnProperty columnProperty) {
- cell.setCellValue(Double.parseDouble(value.toString()));
- return cell;
- }
-
- @Override
- public boolean support(Object cellValue) {
- return cellValue instanceof Long || long.class.equals(cellValue.getClass());
- }
-}
diff --git a/src/main/java/com/alibaba/excel/converters/StringConverter.java b/src/main/java/com/alibaba/excel/converters/StringConverter.java
deleted file mode 100644
index 281ffaf..0000000
--- a/src/main/java/com/alibaba/excel/converters/StringConverter.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.alibaba.excel.converters;
-
-import org.apache.poi.ss.usermodel.Cell;
-
-import com.alibaba.excel.metadata.ExcelColumnProperty;
-import com.alibaba.excel.util.TypeUtil;
-
-public class StringConverter implements Converter {
- @Override
- public String getName() {
- return "string-converter";
- }
- @Override
- public boolean support(ExcelColumnProperty columnProperty) {
- return String.class.equals(columnProperty.getField().getType());
- }
- @Override
- public Object convert(String value, ExcelColumnProperty columnProperty) {
- return TypeUtil.formatFloat(value);
- }
- @Override
- public Cell convert(Cell cell, Object value, ExcelColumnProperty columnProperty) {
- cell.setCellValue(String.valueOf(value));
- return cell;
- }
-
- @Override
- public boolean support(Object cellValue) {
- return cellValue instanceof String;
- }
-}
diff --git a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java
new file mode 100644
index 0000000..ac3453b
--- /dev/null
+++ b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java
@@ -0,0 +1,42 @@
+package com.alibaba.excel.converters.bigdecimal;
+
+import java.math.BigDecimal;
+
+import com.alibaba.excel.converters.Converter;
+import com.alibaba.excel.enums.CellDataTypeEnum;
+import com.alibaba.excel.metadata.CellData;
+import com.alibaba.excel.metadata.ExcelColumnProperty;
+
+/**
+ * BigDecimal and boolean converter
+ *
+ * @author zhuangjiaju
+ */
+public class BigDecimalBooleanConverter implements Converter {
+
+ @Override
+ public Class supportJavaTypeKey() {
+ return BigDecimal.class;
+ }
+
+ @Override
+ public CellDataTypeEnum supportExcelTypeKey() {
+ return CellDataTypeEnum.BOOLEAN;
+ }
+
+ @Override
+ public BigDecimal convertToJavaData(CellData cellData, ExcelColumnProperty columnProperty) {
+ if (cellData.getBooleanValue()) {
+ return BigDecimal.ONE;
+ }
+ return BigDecimal.ZERO;
+ }
+
+ @Override
+ public CellData convertToExcelData(BigDecimal value, ExcelColumnProperty columnProperty) {
+ if (BigDecimal.ONE.equals(value)) {
+ return new CellData(Boolean.TRUE);
+ }
+ return new CellData(Boolean.FALSE);
+ }
+}
diff --git a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java
new file mode 100644
index 0000000..09ef24c
--- /dev/null
+++ b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java
@@ -0,0 +1,36 @@
+package com.alibaba.excel.converters.bigdecimal;
+
+import java.math.BigDecimal;
+
+import com.alibaba.excel.converters.Converter;
+import com.alibaba.excel.enums.CellDataTypeEnum;
+import com.alibaba.excel.metadata.CellData;
+import com.alibaba.excel.metadata.ExcelColumnProperty;
+
+/**
+ * BigDecimal and number converter
+ *
+ * @author zhuangjiaju
+ */
+public class BigDecimalNumberConverter implements Converter {
+
+ @Override
+ public Class supportJavaTypeKey() {
+ return BigDecimal.class;
+ }
+
+ @Override
+ public CellDataTypeEnum supportExcelTypeKey() {
+ return CellDataTypeEnum.NUMBER;
+ }
+
+ @Override
+ public BigDecimal convertToJavaData(CellData cellData, ExcelColumnProperty columnProperty) {
+ return new BigDecimal(cellData.getDoubleValue());
+ }
+
+ @Override
+ public CellData convertToExcelData(BigDecimal value, ExcelColumnProperty columnProperty) {
+ return new CellData(value.doubleValue());
+ }
+}
diff --git a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java
new file mode 100644
index 0000000..2e327c4
--- /dev/null
+++ b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java
@@ -0,0 +1,41 @@
+package com.alibaba.excel.converters.bigdecimal;
+
+import java.math.BigDecimal;
+import java.text.DecimalFormat;
+
+import com.alibaba.excel.converters.Converter;
+import com.alibaba.excel.enums.CellDataTypeEnum;
+import com.alibaba.excel.metadata.CellData;
+import com.alibaba.excel.metadata.ExcelColumnProperty;
+import com.alibaba.excel.util.StringUtils;
+
+/**
+ * BigDecimal and string converter
+ *
+ * @author zhuangjiaju
+ */
+public class BigDecimalStringConverter implements Converter {
+
+ @Override
+ public Class supportJavaTypeKey() {
+ return BigDecimal.class;
+ }
+
+ @Override
+ public CellDataTypeEnum supportExcelTypeKey() {
+ return CellDataTypeEnum.STRING;
+ }
+
+ @Override
+ public BigDecimal convertToJavaData(CellData cellData, ExcelColumnProperty columnProperty) {
+ return new BigDecimal(cellData.getStringValue());
+ }
+
+ @Override
+ public CellData convertToExcelData(BigDecimal value, ExcelColumnProperty columnProperty) {
+ if (StringUtils.isEmpty(columnProperty.getFormat())) {
+ return new CellData(value.toString());
+ }
+ return new CellData(new DecimalFormat(columnProperty.getFormat()).format(value));
+ }
+}
diff --git a/src/main/java/com/alibaba/excel/converters/date/DateNumberConverter.java b/src/main/java/com/alibaba/excel/converters/date/DateNumberConverter.java
new file mode 100644
index 0000000..e784e60
--- /dev/null
+++ b/src/main/java/com/alibaba/excel/converters/date/DateNumberConverter.java
@@ -0,0 +1,39 @@
+package com.alibaba.excel.converters.date;
+
+import java.util.Date;
+
+import org.apache.poi.hssf.usermodel.HSSFDateUtil;
+
+import com.alibaba.excel.converters.Converter;
+import com.alibaba.excel.enums.CellDataTypeEnum;
+import com.alibaba.excel.metadata.CellData;
+import com.alibaba.excel.metadata.ExcelColumnProperty;
+
+/**
+ * Date and number converter
+ *
+ * @author zhuangjiaju
+ */
+public class DateNumberConverter implements Converter {
+
+ @Override
+ public Class supportJavaTypeKey() {
+ return Date.class;
+ }
+
+ @Override
+ public CellDataTypeEnum supportExcelTypeKey() {
+ return CellDataTypeEnum.NUMBER;
+ }
+
+ @Override
+ public Date convertToJavaData(CellData cellData, ExcelColumnProperty columnProperty) {
+ return HSSFDateUtil.getJavaDate(cellData.getDoubleValue(), columnProperty.getUse1904windowing(),
+ columnProperty.getTimeZone());
+ }
+
+ @Override
+ public CellData convertToExcelData(Date value, ExcelColumnProperty columnProperty) {
+ return new CellData((double)(value.getTime()));
+ }
+}
diff --git a/src/main/java/com/alibaba/excel/converters/date/DateStringConverter.java b/src/main/java/com/alibaba/excel/converters/date/DateStringConverter.java
new file mode 100644
index 0000000..f346c4c
--- /dev/null
+++ b/src/main/java/com/alibaba/excel/converters/date/DateStringConverter.java
@@ -0,0 +1,37 @@
+package com.alibaba.excel.converters.date;
+
+import java.text.ParseException;
+import java.util.Date;
+
+import com.alibaba.excel.converters.Converter;
+import com.alibaba.excel.enums.CellDataTypeEnum;
+import com.alibaba.excel.metadata.CellData;
+import com.alibaba.excel.metadata.ExcelColumnProperty;
+import com.alibaba.excel.util.DateUtils;
+
+/**
+ * Date and string converter
+ *
+ * @author zhuangjiaju
+ */
+public class DateStringConverter implements Converter {
+ @Override
+ public Class supportJavaTypeKey() {
+ return Date.class;
+ }
+
+ @Override
+ public CellDataTypeEnum supportExcelTypeKey() {
+ return CellDataTypeEnum.STRING;
+ }
+
+ @Override
+ public Date convertToJavaData(CellData cellData, ExcelColumnProperty columnProperty) throws ParseException {
+ return DateUtils.parseDate(cellData.getStringValue(), columnProperty.getFormat());
+ }
+
+ @Override
+ public CellData convertToExcelData(Date value, ExcelColumnProperty columnProperty) {
+ return new CellData(DateUtils.format(value, columnProperty.getFormat()));
+ }
+}
diff --git a/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java b/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java
new file mode 100644
index 0000000..0081c2f
--- /dev/null
+++ b/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java
@@ -0,0 +1,54 @@
+package com.alibaba.excel.enums;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.alibaba.excel.util.StringUtils;
+
+/**
+ * excel internal data type
+ *
+ * @author zhuangjiaju
+ */
+public enum CellDataTypeEnum {
+ /**
+ * string
+ */
+ STRING,
+ /**
+ * number
+ */
+ NUMBER,
+ /**
+ * boolean
+ */
+ BOOLEAN,
+ /**
+ * empty
+ */
+ EMPTY,
+ /**
+ * error
+ */
+ ERROR;
+
+ private static final Map TYPE_ROUTING_MAP = new HashMap(8);
+ static {
+ TYPE_ROUTING_MAP.put("s", STRING);
+ TYPE_ROUTING_MAP.put("e", ERROR);
+ TYPE_ROUTING_MAP.put("b", BOOLEAN);
+ }
+
+ /**
+ * Build data types
+ *
+ * @param cellType
+ * @return
+ */
+ public static CellDataTypeEnum buildFromCellType(String cellType) {
+ if (StringUtils.isEmpty(cellType)) {
+ return EMPTY;
+ }
+ return TYPE_ROUTING_MAP.get(cellType);
+ }
+}
diff --git a/src/main/java/com/alibaba/excel/enums/HeadKindEnum.java b/src/main/java/com/alibaba/excel/enums/HeadKindEnum.java
index e7f19d9..e9e5b65 100644
--- a/src/main/java/com/alibaba/excel/enums/HeadKindEnum.java
+++ b/src/main/java/com/alibaba/excel/enums/HeadKindEnum.java
@@ -1,7 +1,7 @@
package com.alibaba.excel.enums;
/**
- * The types of head
+ * The types of header
*
* @author zhuangjiaju
**/
diff --git a/src/main/java/com/alibaba/excel/event/EachRowAnalysisFinishEvent.java b/src/main/java/com/alibaba/excel/event/EachRowAnalysisFinishEvent.java
index 9a31ef4..9173caa 100644
--- a/src/main/java/com/alibaba/excel/event/EachRowAnalysisFinishEvent.java
+++ b/src/main/java/com/alibaba/excel/event/EachRowAnalysisFinishEvent.java
@@ -3,6 +3,8 @@ package com.alibaba.excel.event;
import java.util.ArrayList;
import java.util.List;
+import com.alibaba.excel.metadata.CellData;
+
/**
* @author jipengfei
*/
@@ -12,9 +14,9 @@ public class EachRowAnalysisFinishEvent implements AnalysisFinishEvent {
this.result = content;
}
- public EachRowAnalysisFinishEvent(String[] content, int length) {
+ public EachRowAnalysisFinishEvent(CellData[] content, int length) {
if (content != null) {
- List ls = new ArrayList(length);
+ List ls = new ArrayList(length);
for (int i = 0; i <= length; i++) {
ls.add(content[i]);
}
diff --git a/src/main/java/com/alibaba/excel/event/ModelBuildEventListener.java b/src/main/java/com/alibaba/excel/event/ModelBuildEventListener.java
index 82f7708..193af9d 100644
--- a/src/main/java/com/alibaba/excel/event/ModelBuildEventListener.java
+++ b/src/main/java/com/alibaba/excel/event/ModelBuildEventListener.java
@@ -9,6 +9,7 @@ import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelGenerateException;
+import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.ExcelColumnProperty;
import com.alibaba.excel.metadata.ExcelHeadProperty;
import com.alibaba.excel.util.TypeUtil;
@@ -29,7 +30,7 @@ public class ModelBuildEventListener extends AnalysisEventListener