Browse Source

优化读写的写法,方便读写

pull/507/head
zhuangjiaju 6 years ago
parent
commit
5ac5c0e85d
  1. 43
      src/main/java/com/alibaba/excel/EasyExcelFactory.java
  2. 125
      src/main/java/com/alibaba/excel/ExcelReader.java
  3. 148
      src/main/java/com/alibaba/excel/ExcelWriter.java
  4. 6
      src/main/java/com/alibaba/excel/analysis/ExcelAnalyser.java
  5. 19
      src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java
  6. 4
      src/main/java/com/alibaba/excel/analysis/ExcelExecutor.java
  7. 34
      src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java
  8. 28
      src/main/java/com/alibaba/excel/analysis/v03/handlers/BOFRecordHandler.java
  9. 65
      src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java
  10. 2
      src/main/java/com/alibaba/excel/analysis/v07/handlers/ProcessResultCellHandler.java
  11. 30
      src/main/java/com/alibaba/excel/context/AnalysisContext.java
  12. 105
      src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java
  13. 36
      src/main/java/com/alibaba/excel/context/WriteContext.java
  14. 221
      src/main/java/com/alibaba/excel/context/WriteContextImpl.java
  15. 27
      src/main/java/com/alibaba/excel/event/AbstractIgnoreExceptionReadListener.java
  16. 31
      src/main/java/com/alibaba/excel/event/SyncReadListener.java
  17. 22
      src/main/java/com/alibaba/excel/exception/ExcelCommonException.java
  18. 35
      src/main/java/com/alibaba/excel/metadata/CellData.java
  19. 22
      src/main/java/com/alibaba/excel/metadata/Sheet.java
  20. 10
      src/main/java/com/alibaba/excel/metadata/Table.java
  21. 494
      src/main/java/com/alibaba/excel/metadata/holder/read/AbstractWriteConfiguration.java
  22. 39
      src/main/java/com/alibaba/excel/metadata/holder/read/ReadConfiguration.java
  23. 235
      src/main/java/com/alibaba/excel/metadata/holder/read/SheetHolder.java
  24. 138
      src/main/java/com/alibaba/excel/metadata/holder/read/TableHolder.java
  25. 325
      src/main/java/com/alibaba/excel/metadata/holder/read/WorkbookHolder.java
  26. 234
      src/main/java/com/alibaba/excel/metadata/holder/write/SheetHolder.java
  27. 235
      src/main/java/com/alibaba/excel/read/builder/ExcelReaderBuilder.java
  28. 189
      src/main/java/com/alibaba/excel/read/builder/ExcelReaderSheetBuilder.java
  29. 38
      src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java
  30. 2
      src/main/java/com/alibaba/excel/read/listener/ReadListener.java
  31. 11
      src/main/java/com/alibaba/excel/read/metadata/ReadSheet.java
  32. 34
      src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java
  33. 31
      src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java
  34. 27
      src/main/java/com/alibaba/excel/read/metadata/holder/ReadRowHolder.java
  35. 85
      src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java
  36. 185
      src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java
  37. 239
      src/main/java/com/alibaba/excel/read/metadata/holder/SheetHolder.java
  38. 138
      src/main/java/com/alibaba/excel/read/metadata/holder/TableHolder.java
  39. 315
      src/main/java/com/alibaba/excel/read/metadata/holder/WorkbookHolder.java
  40. 29
      src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java
  41. 26
      src/main/java/com/alibaba/excel/util/WorkBookUtil.java
  42. 16
      src/main/java/com/alibaba/excel/write/ExcelBuilder.java
  43. 98
      src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java
  44. 102
      src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java
  45. 78
      src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java
  46. 68
      src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java
  47. 20
      src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java
  48. 20
      src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java
  49. 16
      src/main/java/com/alibaba/excel/write/handler/SheetWriteHandler.java
  50. 6
      src/main/java/com/alibaba/excel/write/handler/WorkbookWriteHandler.java
  51. 2
      src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java
  52. 86
      src/main/java/com/alibaba/excel/write/metadata/holder/UTils.java
  53. 22
      src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java
  54. 12
      src/main/java/com/alibaba/excel/write/metadata/holder/WriteTableHolder.java
  55. 12
      src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java
  56. 21
      src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java
  57. 16
      src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java
  58. 12
      src/main/java/com/alibaba/excel/write/style/row/AbstractRowHeightStyleStrategy.java
  59. 39
      src/test/java/com/alibaba/easyexcel/test/read/large/LargeData07Test.java

43
src/main/java/com/alibaba/excel/EasyExcelFactory.java

@ -8,7 +8,9 @@ import java.util.List;
import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.event.WriteHandler; import com.alibaba.excel.event.WriteHandler;
import com.alibaba.excel.write.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder; import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder; import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
@ -29,7 +31,9 @@ public class EasyExcelFactory {
* @param sheet * @param sheet
* read sheet. * read sheet.
* @return analysis result. * @return analysis result.
* @deprecated please use 'EasyExcelFactory.read().file(in).sheet(sheetNo).doReadSync();'
*/ */
@Deprecated
public static List<Object> read(InputStream in, Sheet sheet) { public static List<Object> read(InputStream in, Sheet sheet) {
final List<Object> rows = new ArrayList<Object>(); final List<Object> rows = new ArrayList<Object>();
new ExcelReader(in, null, new AnalysisEventListener<Object>() { new ExcelReader(in, null, new AnalysisEventListener<Object>() {
@ -53,7 +57,9 @@ public class EasyExcelFactory {
* read sheet. * read sheet.
* @param listener * @param listener
* Callback method after each row is parsed. * Callback method after each row is parsed.
* @deprecated please use 'EasyExcelFactory.read().registerReadListener(listener).file(in).sheet(sheetNo).doRead().finish();'
*/ */
@Deprecated
public static void readBySax(InputStream in, Sheet sheet, AnalysisEventListener listener) { public static void readBySax(InputStream in, Sheet sheet, AnalysisEventListener listener) {
new ExcelReader(in, null, listener).read(sheet); new ExcelReader(in, null, listener).read(sheet);
} }
@ -66,7 +72,9 @@ public class EasyExcelFactory {
* @param listener * @param listener
* Callback method after each row is parsed. * Callback method after each row is parsed.
* @return ExcelReader. * @return ExcelReader.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/ */
@Deprecated
public static ExcelReader getReader(InputStream in, AnalysisEventListener listener) { public static ExcelReader getReader(InputStream in, AnalysisEventListener listener) {
return new ExcelReader(in, null, listener); return new ExcelReader(in, null, listener);
} }
@ -77,12 +85,11 @@ public class EasyExcelFactory {
* @param outputStream * @param outputStream
* the java OutputStream you wish to write the value to. * the java OutputStream you wish to write the value to.
* @return new ExcelWriter. * @return new ExcelWriter.
* @deprecated please use {@link EasyExcelFactory#writerBuilder()} * @deprecated please use {@link EasyExcelFactory#write()}
*/ */
@Deprecated @Deprecated
public static ExcelWriter getWriter(OutputStream outputStream) { public static ExcelWriter getWriter(OutputStream outputStream) {
return writerBuilder().outputFile(outputStream).autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE) return write().file(outputStream).autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build();
.build();
} }
/** /**
@ -95,12 +102,12 @@ public class EasyExcelFactory {
* @param needHead * @param needHead
* Do you need to write the header to the file? * Do you need to write the header to the file?
* @return new ExcelWriter * @return new ExcelWriter
* @deprecated please use {@link EasyExcelFactory#writerBuilder()} * @deprecated please use {@link EasyExcelFactory#write()}
*/ */
@Deprecated @Deprecated
public static ExcelWriter getWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { public static ExcelWriter getWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) {
return writerBuilder().outputFile(outputStream).excelType(typeEnum).needHead(needHead) return write().file(outputStream).excelType(typeEnum).needHead(needHead).autoCloseStream(Boolean.FALSE)
.autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build(); .convertAllFiled(Boolean.FALSE).build();
} }
/** /**
@ -114,12 +121,12 @@ public class EasyExcelFactory {
* @param typeEnum * @param typeEnum
* 03 or 07 * 03 or 07
* @return new ExcelWriter * @return new ExcelWriter
* @deprecated please use {@link EasyExcelFactory#writerBuilder()} * @deprecated please use {@link EasyExcelFactory#write()}
*/ */
@Deprecated @Deprecated
public static ExcelWriter getWriterWithTemp(InputStream temp, OutputStream outputStream, ExcelTypeEnum typeEnum, public static ExcelWriter getWriterWithTemp(InputStream temp, OutputStream outputStream, ExcelTypeEnum typeEnum,
boolean needHead) { boolean needHead) {
return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).needHead(needHead) return write().withTemplate(temp).file(outputStream).excelType(typeEnum).needHead(needHead)
.autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build(); .autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build();
} }
@ -137,24 +144,32 @@ public class EasyExcelFactory {
* @param handler * @param handler
* User-defined callback * User-defined callback
* @return new ExcelWriter * @return new ExcelWriter
* @deprecated please use {@link EasyExcelFactory#writerBuilder()} * @deprecated please use {@link EasyExcelFactory#write()}
*/ */
@Deprecated @Deprecated
public static ExcelWriter getWriterWithTempAndHandler(InputStream temp, OutputStream outputStream, public static ExcelWriter getWriterWithTempAndHandler(InputStream temp, OutputStream outputStream,
ExcelTypeEnum typeEnum, boolean needHead, WriteHandler handler) { ExcelTypeEnum typeEnum, boolean needHead, WriteHandler handler) {
return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).needHead(needHead) return write().withTemplate(temp).file(outputStream).excelType(typeEnum).needHead(needHead)
.registerWriteHandler(handler).autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build(); .registerWriteHandler(handler).autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build();
} }
public static ExcelWriterBuilder writerBuilder() { public static ExcelWriterBuilder write() {
return new ExcelWriterBuilder(); return new ExcelWriterBuilder();
} }
public static ExcelWriterSheetBuilder writerSheetBuilder() { public static ExcelWriterSheetBuilder writerSheet() {
return new ExcelWriterSheetBuilder(); return new ExcelWriterSheetBuilder();
} }
public static ExcelWriterTableBuilder writerTableBuilder() { public static ExcelWriterTableBuilder writerTable() {
return new ExcelWriterTableBuilder(); return new ExcelWriterTableBuilder();
} }
public static ExcelReaderBuilder read() {
return new ExcelReaderBuilder();
}
public static ExcelReaderSheetBuilder readSheet() {
return new ExcelReaderSheetBuilder();
}
} }

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

@ -1,6 +1,7 @@
package com.alibaba.excel; package com.alibaba.excel;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -9,12 +10,15 @@ import org.slf4j.LoggerFactory;
import com.alibaba.excel.analysis.ExcelAnalyser; import com.alibaba.excel.analysis.ExcelAnalyser;
import com.alibaba.excel.analysis.ExcelAnalyserImpl; import com.alibaba.excel.analysis.ExcelAnalyserImpl;
import com.alibaba.excel.analysis.ExcelExecutor; import com.alibaba.excel.analysis.ExcelExecutor;
import com.alibaba.excel.cache.MapCache;
import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException; import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.write.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.parameter.AnalysisParam; import com.alibaba.excel.parameter.AnalysisParam;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
/** /**
@ -43,6 +47,7 @@ public class ExcelReader {
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext * {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener * @param eventListener
* Callback method after each row is parsed. * Callback method after each row is parsed.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/ */
@Deprecated @Deprecated
public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent, public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent,
@ -59,24 +64,11 @@ public class ExcelReader {
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext * {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener * @param eventListener
* Callback method after each row is parsed * Callback method after each row is parsed
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/ */
@Deprecated
public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener) { public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener) {
this(in, customContent, eventListener, null, true); this(in, customContent, eventListener, true);
}
/**
* Create new reader
*
* @param in
* the POI filesystem that contains the Workbook stream
* @param customContent
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener
* Callback method after each row is parsed
*/
public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener,
List<Converter> converters) {
this(in, customContent, eventListener, converters, true);
} }
/** /**
@ -86,6 +78,7 @@ public class ExcelReader {
* old param Deprecated * old param Deprecated
* @param eventListener * @param eventListener
* Callback method after each row is parsed. * Callback method after each row is parsed.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/ */
@Deprecated @Deprecated
public ExcelReader(AnalysisParam param, AnalysisEventListener eventListener) { public ExcelReader(AnalysisParam param, AnalysisEventListener eventListener) {
@ -96,59 +89,59 @@ public class ExcelReader {
* Create new reader * Create new reader
* *
* @param in * @param in
* the POI filesystem that contains the Workbook stream
* @param excelTypeEnum
* 03 or 07
* @param customContent * @param customContent
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext * {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener * @param eventListener
* Callback method after each row is parsed.
* @param trim * @param trim
* The content of the form is empty and needs to be empty. The purpose is to be fault-tolerant, because * The content of the form is empty and needs to be empty. The purpose is to be fault-tolerant, because
* there are often table contents with spaces that can not be converted into custom types. For example: * there are often table contents with spaces that can not be converted into custom types. For example:
* '1234 ' contain a space cannot be converted to int. * '1234 ' contain a space cannot be converted to int.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/ */
@Deprecated @Deprecated
public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent, public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener, boolean trim) {
AnalysisEventListener eventListener, boolean trim) { this(in, null, customContent, eventListener, trim);
this(in, excelTypeEnum, customContent, eventListener, null, trim);
} }
/** /**
* Create new reader * Create new reader
* *
* @param in * @param in
* the POI filesystem that contains the Workbook stream
* @param excelTypeEnum
* 03 or 07
* @param customContent * @param customContent
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext * {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener * @param eventListener
* Callback method after each row is parsed.
* @param trim * @param trim
* The content of the form is empty and needs to be empty. The purpose is to be fault-tolerant, because * The content of the form is empty and needs to be empty. The purpose is to be fault-tolerant, because
* there are often table contents with spaces that can not be converted into custom types. For example: * there are often table contents with spaces that can not be converted into custom types. For example:
* '1234 ' contain a space cannot be converted to int. * '1234 ' contain a space cannot be converted to int.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/ */
public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener, @Deprecated
List<Converter> converters, boolean trim) {
this(in, ExcelTypeEnum.valueOf(in), customContent, eventListener, converters, trim);
}
public ExcelReader(InputStream in, Object excelTypeEnum, AnalysisEventListener<Object> eventListener,
boolean trim) {
this(in, ExcelTypeEnum.valueOf(in), null, eventListener, null, trim);
}
public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent, public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent,
AnalysisEventListener eventListener, List<Converter> converters, boolean trim) { AnalysisEventListener eventListener, boolean trim) {
validateParam(in, eventListener); ReadWorkbook readWorkbook = new ReadWorkbook();
analyser = new ExcelAnalyserImpl(in, excelTypeEnum, customContent, eventListener, trim); readWorkbook.setInputStream(in);
initConverters(analyser, converters); readWorkbook.setExcelType(excelTypeEnum);
readWorkbook.setCustomObject(customContent);
if (eventListener != null) {
List<ReadListener> customReadListenerList = new ArrayList<ReadListener>();
customReadListenerList.add(eventListener);
readWorkbook.setCustomReadListenerList(customReadListenerList);
}
readWorkbook.setAutoTrim(trim);
readWorkbook.setAutoCloseStream(Boolean.FALSE);
readWorkbook.setMandatoryUseInputStream(Boolean.TRUE);
readWorkbook.setReadCache(new MapCache());
readWorkbook.setConvertAllFiled(Boolean.FALSE);
excelAnalyser = new ExcelAnalyserImpl(readWorkbook);
} }
private void initConverters(ExcelAnalyser analyser, List<Converter> converters) { public ExcelReader(ReadWorkbook readWorkbook) {
if (converters != null && converters.size() > 0) { excelAnalyser = new ExcelAnalyserImpl(readWorkbook);
for (Converter c : converters) {
analyser.getAnalysisContext().getConverterRegistryCenter().register(c);
}
}
} }
/** /**
@ -160,20 +153,42 @@ public class ExcelReader {
LOGGER.warn("Excel doesn't have any sheets."); LOGGER.warn("Excel doesn't have any sheets.");
return; return;
} }
for (Sheet sheet : excelExecutor.sheetList()) { for (ReadSheet readSheet : excelExecutor.sheetList()) {
read(sheet); read(readSheet);
} }
} }
/**
* Parse the specified sheetSheetNo start from 1
*
* @param readSheet
* Read sheet
*/
public ExcelReader read(ReadSheet readSheet) {
checkFinished();
excelAnalyser.analysis(readSheet);
return this;
}
/** /**
* Parse the specified sheetSheetNo start from 1 * Parse the specified sheetSheetNo start from 1
* *
* @param sheet * @param sheet
* Read sheet * Read sheet
* @deprecated please us {@link #read(ReadSheet)}
*/ */
@Deprecated
public void read(Sheet sheet) { public void read(Sheet sheet) {
checkFinished(); ReadSheet readSheet = null;
excelAnalyser.analysis(sheet); if (sheet != null) {
readSheet = new ReadSheet();
readSheet.setSheetNo(sheet.getSheetNo() - 1);
readSheet.setSheetName(sheet.getSheetName());
readSheet.setClazz(sheet.getClazz());
readSheet.setHead(sheet.getHead());
readSheet.setHeadRowNumber(sheet.getHeadLineMun());
}
read(readSheet);
} }
/** /**
@ -223,7 +238,17 @@ public class ExcelReader {
*/ */
@Deprecated @Deprecated
public List<Sheet> getSheets() { public List<Sheet> getSheets() {
return excelExecutor().sheetList(); List<ReadSheet> sheetList = excelExecutor().sheetList();
List<Sheet> sheets = new ArrayList<Sheet>();
if (sheetList == null || sheetList.isEmpty()) {
return sheets;
}
for (ReadSheet readSheet : sheetList) {
Sheet sheet = new Sheet(readSheet.getSheetNo() + 1);
sheet.setSheetName(readSheet.getSheetName());
sheets.add(sheet);
}
return sheets;
} }
/** /**

148
src/main/java/com/alibaba/excel/ExcelWriter.java

@ -4,18 +4,19 @@ import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.write.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.write.metadata.Table; import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.write.metadata.Workbook;
import com.alibaba.excel.parameter.GenerateParam; import com.alibaba.excel.parameter.GenerateParam;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.ExcelBuilder; import com.alibaba.excel.write.ExcelBuilder;
import com.alibaba.excel.write.ExcelBuilderImpl; import com.alibaba.excel.write.ExcelBuilderImpl;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy; import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.WriteWorkbook;
/** /**
* Excel Writer This tool is used to write value out to Excel via POI. This object can perform the following two * Excel Writer This tool is used to write value out to Excel via POI. This object can perform the following two
@ -34,36 +35,10 @@ public class ExcelWriter {
/** /**
* Create new writer * Create new writer
* *
* @param templateInputStream * @param writeWorkbook
* Append value after a POI file ,Can be nullthe 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(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum excelType, public ExcelWriter(WriteWorkbook writeWorkbook) {
boolean needHead, Map<Class, Converter> customConverterMap, List<WriteHandler> customWriteHandlerList) { excelBuilder = new ExcelBuilderImpl(writeWorkbook);
Workbook workbook = new Workbook();
workbook.setInputStream(templateInputStream);
workbook.setOutputStream(outputStream);
workbook.setExcelType(excelType);
workbook.setNeedHead(needHead);
workbook.setCustomConverterMap(customConverterMap);
workbook.setCustomWriteHandlerList(customWriteHandlerList);
excelBuilder = new ExcelBuilderImpl(workbook);
}
/**
* Create new writer
*
* @param workbook
*/
public ExcelWriter(Workbook workbook) {
excelBuilder = new ExcelBuilderImpl(workbook);
} }
/** /**
@ -94,7 +69,7 @@ public class ExcelWriter {
*/ */
@Deprecated @Deprecated
public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) {
this(null, outputStream, typeEnum, needHead, null, null); this(null, outputStream, typeEnum, needHead, null);
} }
/** /**
@ -112,7 +87,7 @@ public class ExcelWriter {
@Deprecated @Deprecated
public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum, public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum,
Boolean needHead) { Boolean needHead) {
this(templateInputStream, outputStream, typeEnum, needHead, null, null); this(templateInputStream, outputStream, typeEnum, needHead, null);
} }
/** /**
@ -134,13 +109,13 @@ public class ExcelWriter {
Boolean needHead, WriteHandler writeHandler) { Boolean needHead, WriteHandler writeHandler) {
List<WriteHandler> customWriteHandlerList = new ArrayList<WriteHandler>(); List<WriteHandler> customWriteHandlerList = new ArrayList<WriteHandler>();
customWriteHandlerList.add(writeHandler); customWriteHandlerList.add(writeHandler);
Workbook workbook = new Workbook(); WriteWorkbook writeWorkbook = new WriteWorkbook();
workbook.setInputStream(templateInputStream); writeWorkbook.setTemplateInputStream(templateInputStream);
workbook.setOutputStream(outputStream); writeWorkbook.setOutputStream(outputStream);
workbook.setExcelType(typeEnum); writeWorkbook.setExcelType(typeEnum);
workbook.setNeedHead(needHead); writeWorkbook.setNeedHead(needHead);
workbook.setCustomWriteHandlerList(customWriteHandlerList); writeWorkbook.setCustomWriteHandlerList(customWriteHandlerList);
excelBuilder = new ExcelBuilderImpl(workbook); excelBuilder = new ExcelBuilderImpl(writeWorkbook);
} }
/** /**
@ -157,12 +132,12 @@ public class ExcelWriter {
* *
* @param data * @param data
* Data to be written * Data to be written
* @param sheet * @param writeSheet
* Write to this sheet * Write to this sheet
* @return this current writer * @return this current writer
*/ */
public ExcelWriter write(List data, Sheet sheet) { public ExcelWriter write(List data, WriteSheet writeSheet) {
return write(data, sheet, null); return write(data, writeSheet, null);
} }
/** /**
@ -170,45 +145,85 @@ public class ExcelWriter {
* *
* @param data * @param data
* Data to be written * Data to be written
* @param sheet * @param writeSheet
* Write to this sheet * Write to this sheet
* @param table * @param writeTable
* Write to this table * Write to this table
* @return this * @return this
*/ */
public ExcelWriter write(List data, Sheet sheet, Table table) { public ExcelWriter write(List data, WriteSheet writeSheet, WriteTable writeTable) {
excelBuilder.addContent(data, sheet, table); excelBuilder.addContent(data, writeSheet, writeTable);
return this; return this;
} }
/** /**
* Write data to a sheet
* *
* @param data
* Data to be written
* @param sheet
* Write to this sheet
* @return this current writer
* @deprecated please use {@link ExcelWriter#write(List, WriteSheet)}
*/
@Deprecated
public ExcelWriter write(List data, Sheet sheet) {
return write(data, sheet, null);
}
/**
* Write value to a sheet * Write value to a sheet
* *
* @param data * @param data
* Data to be written * Data to be written
* @param sheet * @param sheet
* Write to this sheet * Write to this sheet
* @param table
* Write to this table
* @return this * @return this
* @deprecated please use {@link ExcelWriter#write(List, Sheet)} * @deprecated * @deprecated please use {@link ExcelWriter#write(List, WriteSheet,WriteTable)}
*/ */
@Deprecated @Deprecated
public ExcelWriter write1(List data, Sheet sheet) { public ExcelWriter write(List data, Sheet sheet, Table table) {
return write(data, sheet); WriteSheet writeSheet = null;
if (sheet != null) {
if (sheet.getStartRow() != 0) {
throw new ExcelGenerateException(
"Specifying a line to start is no longer supported.Please 'WriteSheet.relativeHeadRowIndex' him instead.");
}
writeSheet = new WriteSheet();
writeSheet.setSheetNo(sheet.getSheetNo() - 1);
writeSheet.setSheetName(sheet.getSheetName());
writeSheet.setClazz(sheet.getClazz());
writeSheet.setHead(sheet.getHead());
writeSheet.setTableStyle(sheet.getTableStyle());
writeSheet.setColumnWidthMap(sheet.getColumnWidthMap());
}
WriteTable writeTable = null;
if (table != null) {
writeTable = new WriteTable();
writeTable.setTableNo(table.getTableNo());
writeTable.setClazz(table.getClazz());
writeTable.setHead(table.getHead());
writeTable.setTableStyle(table.getTableStyle());
}
return write(data, writeSheet, writeTable);
} }
/** /**
* Write value to a sheet * Write data to a sheet
* *
* @param data * @param data
* Data to be written * Data to be written
* @param sheet * @param sheet
* Write to this sheet * Write to this sheet
* @deprecated please use {@link ExcelWriter#write(List, Sheet)} * @return this current writer
* @deprecated please use {@link ExcelWriter#write(List, WriteSheet)}
*/ */
@Deprecated @Deprecated
public ExcelWriter write0(List data, Sheet sheet) { public ExcelWriter write0(List data, Sheet sheet) {
return write(data, sheet); return write(data, sheet, null);
} }
/** /**
@ -220,12 +235,27 @@ public class ExcelWriter {
* Write to this sheet * Write to this sheet
* @param table * @param table
* Write to this table * Write to this table
* @deprecated please use {@link ExcelWriter#write(List, Sheet,Table)} * @return this
* @deprecated * @deprecated please use {@link ExcelWriter#write(List, WriteSheet,WriteTable)}
*/ */
@Deprecated @Deprecated
public ExcelWriter write0(List data, Sheet sheet, Table table) { public ExcelWriter write0(List data, Sheet sheet, Table table) {
return write(data, sheet, table); return write(data, sheet, table);
}
/**
* Write data to a sheet
*
* @param data
* Data to be written
* @param sheet
* Write to this sheet
* @return this current writer
* @deprecated please use {@link ExcelWriter#write(List, WriteSheet)}
*/
@Deprecated
public ExcelWriter write1(List data, Sheet sheet) {
return write(data, sheet, null);
} }
/** /**
@ -237,12 +267,12 @@ public class ExcelWriter {
* Write to this sheet * Write to this sheet
* @param table * @param table
* Write to this table * Write to this table
* @deprecated please use {@link ExcelWriter#write(List, Sheet,Table)} * @return this
* @deprecated * @deprecated please use {@link ExcelWriter#write(List, WriteSheet,WriteTable)}
*/ */
@Deprecated @Deprecated
public ExcelWriter write1(List data, Sheet sheet, Table table) { public ExcelWriter write1(List data, Sheet sheet, Table table) {
return write(data, sheet, table); return write(data, sheet, table);
} }
/** /**

6
src/main/java/com/alibaba/excel/analysis/ExcelAnalyser.java

@ -1,7 +1,7 @@
package com.alibaba.excel.analysis; package com.alibaba.excel.analysis;
import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.write.metadata.Sheet; import com.alibaba.excel.read.metadata.ReadSheet;
/** /**
* Excel file analyser * Excel file analyser
@ -12,9 +12,9 @@ public interface ExcelAnalyser {
/** /**
* parse one sheet * parse one sheet
* *
* @param sheetParam * @param readSheet
*/ */
void analysis(Sheet sheetParam); void analysis(ReadSheet readSheet);
/** /**
* Complete the entire read file.Release the cache and close stream * Complete the entire read file.Release the cache and close stream

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

@ -5,8 +5,8 @@ import com.alibaba.excel.analysis.v07.XlsxSaxAnalyser;
import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.context.AnalysisContextImpl; import com.alibaba.excel.context.AnalysisContextImpl;
import com.alibaba.excel.exception.ExcelAnalysisException; import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.write.metadata.Sheet; import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.Workbook; import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
/** /**
@ -18,14 +18,14 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
private ExcelExecutor excelExecutor; private ExcelExecutor excelExecutor;
public ExcelAnalyserImpl(Workbook workbook) { public ExcelAnalyserImpl(ReadWorkbook readWorkbook) {
analysisContext = new AnalysisContextImpl(workbook); analysisContext = new AnalysisContextImpl(readWorkbook);
choiceExcelExecutor(); choiceExcelExecutor();
} }
private void choiceExcelExecutor() { private void choiceExcelExecutor() {
try { try {
ExcelTypeEnum excelType = analysisContext.currentWorkbookHolder().getExcelType(); ExcelTypeEnum excelType = analysisContext.readWorkbookHolder().getExcelType();
if (excelType == null) { if (excelType == null) {
excelExecutor = new XlsxSaxAnalyser(analysisContext); excelExecutor = new XlsxSaxAnalyser(analysisContext);
return; return;
@ -46,12 +46,15 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
} }
@Override @Override
public void analysis(Sheet sheet) { public void analysis(ReadSheet readSheet) {
analysisContext.currentSheet(sheet); analysisContext.currentSheet(excelExecutor, readSheet);
excelExecutor.execute(); excelExecutor.execute();
analysisContext.getEventListener().doAfterAllAnalysed(analysisContext); analysisContext.readSheetHolder().notifyAfterAllAnalysed(analysisContext);
} }
@Override
public void finish() {}
@Override @Override
public com.alibaba.excel.analysis.ExcelExecutor excelExecutor() { public com.alibaba.excel.analysis.ExcelExecutor excelExecutor() {
return excelExecutor; return excelExecutor;

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

@ -2,7 +2,7 @@ package com.alibaba.excel.analysis;
import java.util.List; import java.util.List;
import com.alibaba.excel.write.metadata.Sheet; import com.alibaba.excel.read.metadata.ReadSheet;
/** /**
* Excel file Executor * Excel file Executor
@ -11,7 +11,7 @@ import com.alibaba.excel.write.metadata.Sheet;
*/ */
public interface ExcelExecutor { public interface ExcelExecutor {
List<Sheet> sheetList(); List<ReadSheet> sheetList();
void execute(); void execute();

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

@ -27,9 +27,10 @@ import com.alibaba.excel.analysis.v03.handlers.NumberRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.RKRecordHandler; import com.alibaba.excel.analysis.v03.handlers.RKRecordHandler;
import com.alibaba.excel.analysis.v03.handlers.SSTRecordHandler; import com.alibaba.excel.analysis.v03.handlers.SSTRecordHandler;
import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.event.EachRowAnalysisFinishEvent;
import com.alibaba.excel.exception.ExcelAnalysisException; import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.write.metadata.Sheet; import com.alibaba.excel.read.listener.event.EachRowAnalysisFinishEvent;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder;
import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.CollectionUtils;
/** /**
@ -59,28 +60,27 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
private FormatTrackingHSSFListener formatListener; private FormatTrackingHSSFListener formatListener;
private List<String> records; private List<String> records;
private boolean notAllEmpty = false; private boolean notAllEmpty = false;
private List<Sheet> sheets = new ArrayList<Sheet>(); private List<ReadSheet> sheets = new ArrayList<ReadSheet>();
private HSSFWorkbook stubWorkbook; private HSSFWorkbook stubWorkbook;
private List<XlsRecordHandler> recordHandlers = new ArrayList<XlsRecordHandler>(); private List<XlsRecordHandler> recordHandlers = new ArrayList<XlsRecordHandler>();
private AnalysisContext analysisContext;
public XlsSaxAnalyser(AnalysisContext context) throws IOException { public XlsSaxAnalyser(AnalysisContext context) throws IOException {
this.analysisContext = context; this.analysisContext = context;
this.records = new ArrayList<String>(); this.records = new ArrayList<String>();
context.setCurrentRowNum(0); ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder();
this.fs = new POIFSFileSystem(analysisContext.getInputStream()); if (readWorkbookHolder.getFile() != null) {
this.fs = new POIFSFileSystem(readWorkbookHolder.getFile());
} else {
this.fs = new POIFSFileSystem(readWorkbookHolder.getInputStream());
}
} }
@Override @Override
public List<Sheet> getSheets() { public List<ReadSheet> sheetList() {
return sheets; return sheets;
} }
@Override
public List<Sheet> sheetList() {
return null;
}
@Override @Override
public void execute() { public void execute() {
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this); MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
@ -112,10 +112,11 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
lastColumnNumber = 0; lastColumnNumber = 0;
records = new ArrayList<String>(); records = new ArrayList<String>();
notAllEmpty = false; notAllEmpty = false;
sheets = new ArrayList<Sheet>(); sheets = new ArrayList<ReadSheet>();
buildXlsRecordHandlers(); buildXlsRecordHandlers();
} }
@Override
public void processRecord(Record record) { public void processRecord(Record record) {
int thisRow = -1; int thisRow = -1;
int thisColumn = -1; int thisColumn = -1;
@ -129,10 +130,9 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
break; break;
} }
} }
// If we got something to print out, do so // If we got something to print out, do so
if (thisStr != null) { if (thisStr != null) {
if (analysisContext.trim()) { if (analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
thisStr = thisStr.trim(); thisStr = thisStr.trim();
} }
if (!"".equals(thisStr)) { if (!"".equals(thisStr)) {
@ -165,9 +165,9 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
if (lastColumnNumber == -1) { if (lastColumnNumber == -1) {
lastColumnNumber = 0; lastColumnNumber = 0;
} }
analysisContext.setCurrentRowNum(row);
if (notAllEmpty) { if (notAllEmpty) {
notify(new EachRowAnalysisFinishEvent(new ArrayList<String>(records))); analysisContext.readSheetHolder()
.notifyEndOneRow(new EachRowAnalysisFinishEvent(new ArrayList<String>(records)), analysisContext);
} }
records.clear(); records.clear();
lastColumnNumber = -1; lastColumnNumber = -1;

28
src/main/java/com/alibaba/excel/analysis/v03/handlers/BOFRecordHandler.java

@ -1,29 +1,33 @@
package com.alibaba.excel.analysis.v03.handlers; package com.alibaba.excel.analysis.v03.handlers;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; import java.util.ArrayList;
import com.alibaba.excel.context.AnalysisContext; import java.util.List;
import com.alibaba.excel.write.metadata.Sheet;
import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder; import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder;
import org.apache.poi.hssf.record.BOFRecord; import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BoundSheetRecord; import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.Record; import org.apache.poi.hssf.record.Record;
import java.util.ArrayList; import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import java.util.List; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.metadata.ReadSheet;
public class BOFRecordHandler extends AbstractXlsRecordHandler { public class BOFRecordHandler extends AbstractXlsRecordHandler {
private List<BoundSheetRecord> boundSheetRecords = new ArrayList<BoundSheetRecord>(); private List<BoundSheetRecord> boundSheetRecords = new ArrayList<BoundSheetRecord>();
private BoundSheetRecord[] orderedBSRs; private BoundSheetRecord[] orderedBSRs;
private int sheetIndex; private int sheetIndex;
private List<Sheet> sheets; private List<ReadSheet> sheets;
private AnalysisContext context; private AnalysisContext context;
private boolean analyAllSheet; private boolean analyAllSheet;
private EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener; private EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener;
public BOFRecordHandler(EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener, AnalysisContext context, List<Sheet> sheets) {
public BOFRecordHandler(EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener,
AnalysisContext context, List<ReadSheet> sheets) {
this.context = context; this.context = context;
this.workbookBuildingListener = workbookBuildingListener; this.workbookBuildingListener = workbookBuildingListener;
this.sheets = sheets; this.sheets = sheets;
} }
@Override @Override
public boolean support(Record record) { public boolean support(Record record) {
return BoundSheetRecord.sid == record.getSid() || BOFRecord.sid == record.getSid(); return BoundSheetRecord.sid == record.getSid() || BOFRecord.sid == record.getSid();
@ -40,12 +44,10 @@ public class BOFRecordHandler extends AbstractXlsRecordHandler {
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords); orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
} }
sheetIndex++; sheetIndex++;
ReadSheet readSheet = new ReadSheet(sheetIndex, orderedBSRs[sheetIndex - 1].getSheetname());
Sheet sheet = new Sheet(sheetIndex, 0); sheets.add(readSheet);
sheet.setSheetName(orderedBSRs[sheetIndex - 1].getSheetname());
sheets.add(sheet);
if (this.analyAllSheet) { if (this.analyAllSheet) {
context.setCurrentSheet(sheet); context.currentSheet(null, readSheet);
} }
} }
} }
@ -53,7 +55,7 @@ public class BOFRecordHandler extends AbstractXlsRecordHandler {
@Override @Override
public void init() { public void init() {
if (context.getCurrentSheet() == null) { if (context.readSheetHolder() == null) {
this.analyAllSheet = true; this.analyAllSheet = true;
} }
sheetIndex = 0; sheetIndex = 0;

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

@ -26,8 +26,8 @@ import com.alibaba.excel.analysis.ExcelExecutor;
import com.alibaba.excel.cache.Ehcache; import com.alibaba.excel.cache.Ehcache;
import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelAnalysisException; import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.write.metadata.Sheet; import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder; import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder;
import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.util.FileUtils;
/** /**
@ -36,82 +36,85 @@ import com.alibaba.excel.util.FileUtils;
*/ */
public class XlsxSaxAnalyser implements ExcelExecutor { public class XlsxSaxAnalyser implements ExcelExecutor {
private AnalysisContext analysisContext; private AnalysisContext analysisContext;
private List<Sheet> sheetList; private List<ReadSheet> sheetList;
private Map<Integer, InputStream> sheetMap; private Map<Integer, InputStream> sheetMap;
public XlsxSaxAnalyser(AnalysisContext analysisContext) throws Exception { public XlsxSaxAnalyser(AnalysisContext analysisContext) throws Exception {
this.analysisContext = analysisContext; this.analysisContext = analysisContext;
analysisContext.setCurrentRowNum(0); // Initialize cache
WorkbookHolder workbookHolder = analysisContext.currentWorkbookHolder(); ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder();
if (workbookHolder.getReadCache() == null) { if (readWorkbookHolder.getReadCache() == null) {
workbookHolder.setReadCache(new Ehcache()); readWorkbookHolder.setReadCache(new Ehcache());
} }
workbookHolder.getReadCache().init(analysisContext); readWorkbookHolder.getReadCache().init(analysisContext);
OPCPackage pkg = readOpcPackage(workbookHolder); OPCPackage pkg = readOpcPackage(readWorkbookHolder);
// Analysis sharedStringsTable.xml // Analysis sharedStringsTable.xml
analysisSharedStringsTable(pkg, workbookHolder); analysisSharedStringsTable(pkg, readWorkbookHolder);
XSSFReader xssfReader = new XSSFReader(pkg); XSSFReader xssfReader = new XSSFReader(pkg);
analysisUse1904WindowDate(xssfReader, workbookHolder); analysisUse1904WindowDate(xssfReader, readWorkbookHolder);
sheetList = new ArrayList<Sheet>(); sheetList = new ArrayList<ReadSheet>();
sheetMap = new HashMap<Integer, InputStream>(); sheetMap = new HashMap<Integer, InputStream>();
XSSFReader.SheetIterator ite = (XSSFReader.SheetIterator)xssfReader.getSheetsData(); XSSFReader.SheetIterator ite = (XSSFReader.SheetIterator)xssfReader.getSheetsData();
int index = 0; int index = 0;
if (!ite.hasNext()) {
throw new ExcelAnalysisException("Can not find any sheet!");
}
while (ite.hasNext()) { while (ite.hasNext()) {
InputStream inputStream = ite.next(); InputStream inputStream = ite.next();
Sheet sheet = new Sheet(); sheetList.add(new ReadSheet(index, ite.getSheetName()));
sheet.setSheetNo(index);
sheet.setSheetName(ite.getSheetName());
sheetList.add(sheet);
sheetMap.put(index, inputStream); sheetMap.put(index, inputStream);
index++; index++;
} }
} }
private void analysisUse1904WindowDate(XSSFReader xssfReader, WorkbookHolder workbookHolder) throws Exception { private void analysisUse1904WindowDate(XSSFReader xssfReader, ReadWorkbookHolder readWorkbookHolder)
throws Exception {
if (readWorkbookHolder.globalConfiguration().getUse1904windowing() != null) {
return;
}
InputStream workbookXml = xssfReader.getWorkbookData(); InputStream workbookXml = xssfReader.getWorkbookData();
WorkbookDocument ctWorkbook = WorkbookDocument.Factory.parse(workbookXml); WorkbookDocument ctWorkbook = WorkbookDocument.Factory.parse(workbookXml);
CTWorkbook wb = ctWorkbook.getWorkbook(); CTWorkbook wb = ctWorkbook.getWorkbook();
CTWorkbookPr prefix = wb.getWorkbookPr(); CTWorkbookPr prefix = wb.getWorkbookPr();
if (prefix != null && prefix.getDate1904()) { if (prefix != null && prefix.getDate1904()) {
workbookHolder.setUse1904windowing(Boolean.TRUE); readWorkbookHolder.getGlobalConfiguration().setUse1904windowing(Boolean.TRUE);
} }
} }
private void analysisSharedStringsTable(OPCPackage pkg, WorkbookHolder workbookHolder) throws Exception { private void analysisSharedStringsTable(OPCPackage pkg, ReadWorkbookHolder readWorkbookHolder) throws Exception {
ContentHandler handler = new SharedStringsTableHandler(workbookHolder.getReadCache()); ContentHandler handler = new SharedStringsTableHandler(readWorkbookHolder.getReadCache());
parseXmlSource(pkg.getPartsByContentType(XSSFRelation.SHARED_STRINGS.getContentType()).get(0).getInputStream(), parseXmlSource(pkg.getPartsByContentType(XSSFRelation.SHARED_STRINGS.getContentType()).get(0).getInputStream(),
handler); handler);
workbookHolder.getReadCache().putFinished(); readWorkbookHolder.getReadCache().putFinished();
} }
private OPCPackage readOpcPackage(WorkbookHolder workbookHolder) throws Exception { private OPCPackage readOpcPackage(ReadWorkbookHolder readWorkbookHolder) throws Exception {
if (workbookHolder.getFile() != null) { if (readWorkbookHolder.getFile() != null) {
return OPCPackage.open(workbookHolder.getFile()); return OPCPackage.open(readWorkbookHolder.getFile());
} }
if (workbookHolder.getMandatoryUseInputStream()) { if (readWorkbookHolder.getMandatoryUseInputStream()) {
return OPCPackage.open(workbookHolder.getInputStream()); return OPCPackage.open(readWorkbookHolder.getInputStream());
} }
File readTempFile = FileUtils.createCacheTmpFile(); File readTempFile = FileUtils.createCacheTmpFile();
workbookHolder.setReadTempFile(readTempFile); readWorkbookHolder.setTempFile(readTempFile);
File tempFile = new File(readTempFile.getPath(), UUID.randomUUID().toString() + ".xlsx"); File tempFile = new File(readTempFile.getPath(), UUID.randomUUID().toString() + ".xlsx");
FileUtils.writeToFile(readTempFile, workbookHolder.getInputStream()); FileUtils.writeToFile(readTempFile, readWorkbookHolder.getInputStream());
return OPCPackage.open(tempFile); return OPCPackage.open(tempFile);
} }
@Override @Override
public List<Sheet> sheetList() { public List<ReadSheet> sheetList() {
return sheetList; return sheetList;
} }
@Override @Override
public void execute() { public void execute() {
parseXmlSource(sheetMap.get(analysisContext.currentSheetHolder().getSheetNo()), parseXmlSource(sheetMap.get(analysisContext.readSheetHolder().getSheetNo()),
new XlsxRowHandler(analysisContext)); new XlsxRowHandler(analysisContext));
} }

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

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

30
src/main/java/com/alibaba/excel/context/AnalysisContext.java

@ -1,6 +1,8 @@
package com.alibaba.excel.context; package com.alibaba.excel.context;
import com.alibaba.excel.analysis.ExcelExecutor;
import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.ReadHolder;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder; import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; import com.alibaba.excel.read.metadata.holder.ReadSheetHolder;
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder; import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder;
@ -15,28 +17,48 @@ public interface AnalysisContext {
/** /**
* Select the current table * Select the current table
* *
* @param excelExecutor
* @param readSheet * @param readSheet
*/ */
void currentSheet(ReadSheet readSheet); void currentSheet(ExcelExecutor excelExecutor, ReadSheet readSheet);
/** /**
* All information about the workbook you are currently working on * All information about the workbook you are currently working on
* *
* @return * @return
*/ */
ReadWorkbookHolder currentWorkbookHolder(); ReadWorkbookHolder readWorkbookHolder();
/** /**
* All information about the sheet you are currently working on * All information about the sheet you are currently working on
* *
* @return * @return
*/ */
ReadSheetHolder currentSheetHolder(); ReadSheetHolder readSheetHolder();
/**
* Set row of currently operated cell
*
* @param readRowHolder
*/
void readRowHolder(ReadRowHolder readRowHolder);
/** /**
* Row of currently operated cell * Row of currently operated cell
* *
* @return * @return
*/ */
ReadRowHolder currentRowHolder(); ReadRowHolder readRowHolder();
/**
* The current read operation corresponds to the 'readSheetHolder' or 'readWorkbookHolder'
*
* @return
*/
ReadHolder currentReadHolder();
/**
* Custom attribute
*/
Object getCustom();
} }

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

@ -3,10 +3,15 @@ package com.alibaba.excel.context;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.alibaba.excel.write.metadata.holder.SheetHolder; import com.alibaba.excel.analysis.ExcelExecutor;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder; import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.write.metadata.Sheet; import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.Workbook; import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.read.metadata.holder.ReadHolder;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.ReadSheetHolder;
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder;
import com.alibaba.excel.util.StringUtils;
/** /**
* *
@ -17,33 +22,101 @@ public class AnalysisContextImpl implements AnalysisContext {
/** /**
* The Workbook currently written * The Workbook currently written
*/ */
private WorkbookHolder currentWorkbookHolder; private ReadWorkbookHolder readWorkbookHolder;
/** /**
* Current sheet holder * Current sheet holder
*/ */
private SheetHolder currentSheetHolder; private ReadSheetHolder readSheetHolder;
/**
* Current row holder
*/
private ReadRowHolder readRowHolder;
/**
* Configuration of currently operated cell
*/
private ReadHolder currentReadHolder;
public AnalysisContextImpl(Workbook workbook) { public AnalysisContextImpl(ReadWorkbook readWorkbook) {
if (workbook == null) { if (readWorkbook == null) {
throw new IllegalArgumentException("Workbook argument cannot be null"); throw new IllegalArgumentException("Workbook argument cannot be null");
} }
currentWorkbookHolder = WorkbookHolder.buildReadWorkbookHolder(workbook); readWorkbookHolder = new ReadWorkbookHolder(readWorkbook);
currentReadHolder = readWorkbookHolder;
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Initialization 'AnalysisContextImpl' complete"); LOGGER.debug("Initialization 'AnalysisContextImpl' complete");
} }
} }
@Override @Override
public void currentSheet(Sheet sheet) { public void currentSheet(ExcelExecutor excelExecutor, ReadSheet readSheet) {
if (sheet == null) { if (readSheet == null) {
throw new IllegalArgumentException("Sheet argument cannot be null"); throw new IllegalArgumentException("Sheet argument cannot be null");
} }
if (sheet.getSheetNo() == null || sheet.getSheetNo() <= 0) { readSheetHolder = new ReadSheetHolder(readSheet, readWorkbookHolder);
sheet.setSheetNo(0); currentReadHolder = readSheetHolder;
} selectSheet(excelExecutor);
currentSheetHolder = SheetHolder.buildReadWorkSheetHolder(sheet, currentWorkbookHolder);
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Began to read:{}", sheet); LOGGER.debug("Began to read:{}", readSheet);
}
}
private void selectSheet(ExcelExecutor excelExecutor) {
if (readSheetHolder.getSheetNo() != null && readSheetHolder.getSheetNo() >= 0) {
for (ReadSheet readSheetExcel : excelExecutor.sheetList()) {
if (readSheetExcel.getSheetNo().equals(readSheetHolder.getSheetNo())) {
readSheetHolder.setSheetName(readSheetExcel.getSheetName());
return;
}
}
throw new ExcelAnalysisException("Can not find sheet:" + readSheetHolder.getSheetNo());
}
if (!StringUtils.isEmpty(readSheetHolder.getSheetName())) {
for (ReadSheet readSheetExcel : excelExecutor.sheetList()) {
String sheetName = readSheetExcel.getSheetName();
if (sheetName == null) {
continue;
}
if (readSheetHolder.globalConfiguration().getAutoTrim()) {
sheetName = sheetName.trim();
}
if (sheetName.equals(readSheetHolder.getSheetName())) {
readSheetHolder.setSheetNo(readSheetHolder.getSheetNo());
return;
}
}
} }
ReadSheet readSheetExcel = excelExecutor.sheetList().get(0);
readSheetHolder.setSheetNo(readSheetExcel.getSheetNo());
readSheetHolder.setSheetName(readSheetExcel.getSheetName());
}
@Override
public ReadWorkbookHolder readWorkbookHolder() {
return readWorkbookHolder;
}
@Override
public ReadSheetHolder readSheetHolder() {
return readSheetHolder;
}
@Override
public ReadRowHolder readRowHolder() {
return readRowHolder;
}
@Override
public void readRowHolder(ReadRowHolder readRowHolder) {
this.readRowHolder = readRowHolder;
}
@Override
public ReadHolder currentReadHolder() {
return readSheetHolder;
}
@Override
public Object getCustom() {
return readWorkbookHolder.getCustomObject();
} }
} }

36
src/main/java/com/alibaba/excel/context/WriteContext.java

@ -1,11 +1,11 @@
package com.alibaba.excel.context; package com.alibaba.excel.context;
import com.alibaba.excel.write.metadata.Table; import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.holder.WriteConfiguration; import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.holder.SheetHolder; import com.alibaba.excel.write.metadata.holder.WriteHolder;
import com.alibaba.excel.write.metadata.holder.TableHolder; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.Sheet; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/** /**
* Write context * Write context
@ -16,44 +16,44 @@ public interface WriteContext {
/** /**
* If the current sheet already exists, select it; if not, create it * If the current sheet already exists, select it; if not, create it
* *
* @param sheet * @param writeSheet
*/ */
void currentSheet(Sheet sheet); void currentSheet(WriteSheet writeSheet);
/** /**
* If the current table already exists, select it; if not, create it * If the current table already exists, select it; if not, create it
* *
* @param table * @param writeTable
*/ */
void currentTable(Table table); void currentTable(WriteTable writeTable);
/** /**
* Configuration of currently operated cell * All information about the workbook you are currently working on
* *
* @return * @return
*/ */
WriteConfiguration currentConfiguration(); WriteWorkbookHolder writeWorkbookHolder();
/** /**
* All information about the workbook you are currently working on * All information about the sheet you are currently working on
* *
* @return * @return
*/ */
WorkbookHolder currentWorkbookHolder(); WriteSheetHolder writeSheetHolder();
/** /**
* All information about the sheet you are currently working on * All information about the table you are currently working on
* *
* @return * @return
*/ */
SheetHolder currentSheetHolder(); WriteTableHolder writeTableHolder();
/** /**
* All information about the table you are currently working on * Configuration of currently operated cell. May be 'writeSheetHolder' or 'writeTableHolder' or 'writeWorkbookHolder'
* *
* @return * @return
*/ */
TableHolder currentTableHolder(); WriteHolder currentWriteHolder();
/** /**
* close * close

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

@ -13,19 +13,20 @@ import org.slf4j.LoggerFactory;
import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.property.ExcelHeadProperty;
import com.alibaba.excel.util.WorkBookUtil; import com.alibaba.excel.util.WorkBookUtil;
import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.RowWriteHandler; import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler; import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.WorkbookWriteHandler; import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.Table; import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.Workbook; import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.holder.SheetHolder; import com.alibaba.excel.write.metadata.WriteWorkbook;
import com.alibaba.excel.write.metadata.holder.TableHolder; import com.alibaba.excel.write.metadata.holder.WriteHolder;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteConfiguration; import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.property.ExcelWriteHeadProperty;
/** /**
* A context is the main anchorage point of a excel writer. * A context is the main anchorage point of a excel writer.
@ -39,31 +40,31 @@ public class WriteContextImpl implements WriteContext {
/** /**
* The Workbook currently written * The Workbook currently written
*/ */
private WorkbookHolder currentWorkbookHolder; private WriteWorkbookHolder writeWorkbookHolder;
/** /**
* Current sheet holder * Current sheet holder
*/ */
private SheetHolder currentSheetHolder; private WriteSheetHolder writeSheetHolder;
/** /**
* The table currently written * The table currently written
*/ */
private TableHolder currentTableHolder; private WriteTableHolder writeTableHolder;
/** /**
* Configuration of currently operated cell * Configuration of currently operated cell
*/ */
private WriteConfiguration currentWriteConfiguration; private WriteHolder currentWriteHolder;
public WriteContextImpl(Workbook workbook) { public WriteContextImpl(WriteWorkbook writeWorkbook) {
if (workbook == null) { if (writeWorkbook == null) {
throw new IllegalArgumentException("Workbook argument cannot be null"); throw new IllegalArgumentException("Workbook argument cannot be null");
} }
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Begin to Initialization 'WriteContextImpl'"); LOGGER.debug("Begin to Initialization 'WriteContextImpl'");
} }
initCurrentWorkbookHolder(workbook); initCurrentWorkbookHolder(writeWorkbook);
beforeWorkbookCreate(); beforeWorkbookCreate();
try { try {
currentWorkbookHolder.setWorkbook(WorkBookUtil.createWorkBook(currentWorkbookHolder)); writeWorkbookHolder.setWorkbook(WorkBookUtil.createWorkBook(writeWorkbookHolder));
} catch (Exception e) { } catch (Exception e) {
throw new ExcelGenerateException("Create workbook failure", e); throw new ExcelGenerateException("Create workbook failure", e);
} }
@ -74,7 +75,7 @@ public class WriteContextImpl implements WriteContext {
} }
private void beforeWorkbookCreate() { private void beforeWorkbookCreate() {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(WorkbookWriteHandler.class); List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(WorkbookWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) { if (handlerList == null || handlerList.isEmpty()) {
return; return;
} }
@ -86,159 +87,159 @@ public class WriteContextImpl implements WriteContext {
} }
private void afterWorkbookCreate() { private void afterWorkbookCreate() {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(WorkbookWriteHandler.class); List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(WorkbookWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) { if (handlerList == null || handlerList.isEmpty()) {
return; return;
} }
for (WriteHandler writeHandler : handlerList) { for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof WorkbookWriteHandler) { if (writeHandler instanceof WorkbookWriteHandler) {
((WorkbookWriteHandler)writeHandler).afterWorkbookCreate(currentWorkbookHolder); ((WorkbookWriteHandler)writeHandler).afterWorkbookCreate(writeWorkbookHolder);
} }
} }
} }
private void initCurrentWorkbookHolder(Workbook workbook) { private void initCurrentWorkbookHolder(WriteWorkbook writeWorkbook) {
currentWorkbookHolder = new WorkbookHolder(workbook); writeWorkbookHolder = new WriteWorkbookHolder(writeWorkbook);
currentWriteConfiguration = currentWorkbookHolder; currentWriteHolder = writeWorkbookHolder;
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CurrentConfiguration is currentWorkbookHolder"); LOGGER.debug("CurrentConfiguration is writeWorkbookHolder");
} }
} }
/** /**
* @param sheet * @param writeSheet
*/ */
@Override @Override
public void currentSheet(com.alibaba.excel.write.metadata.Sheet sheet) { public void currentSheet(WriteSheet writeSheet) {
if (sheet == null) { if (writeSheet == null) {
throw new IllegalArgumentException("Sheet argument cannot be null"); throw new IllegalArgumentException("Sheet argument cannot be null");
} }
if (sheet.getSheetNo() == null || sheet.getSheetNo() <= 0) { if (writeSheet.getSheetNo() == null || writeSheet.getSheetNo() <= 0) {
LOGGER.info("Sheet number is null"); LOGGER.info("Sheet number is null");
sheet.setSheetNo(0); writeSheet.setSheetNo(0);
} }
if (currentWorkbookHolder.getHasBeenInitializedSheet().containsKey(sheet.getSheetNo())) { if (writeWorkbookHolder.getHasBeenInitializedSheet().containsKey(writeSheet.getSheetNo())) {
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sheet:{} is already existed", sheet.getSheetNo()); LOGGER.debug("Sheet:{} is already existed", writeSheet.getSheetNo());
} }
currentSheetHolder = currentWorkbookHolder.getHasBeenInitializedSheet().get(sheet.getSheetNo()); writeSheetHolder = writeWorkbookHolder.getHasBeenInitializedSheet().get(writeSheet.getSheetNo());
currentSheetHolder.setNewInitialization(Boolean.FALSE); writeSheetHolder.setNewInitialization(Boolean.FALSE);
currentTableHolder = null; writeTableHolder = null;
currentWriteConfiguration = currentSheetHolder; currentWriteHolder = writeSheetHolder;
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CurrentConfiguration is currentSheetHolder"); LOGGER.debug("CurrentConfiguration is writeSheetHolder");
} }
return; return;
} }
initCurrentSheetHolder(sheet); initCurrentSheetHolder(writeSheet);
beforeSheetCreate(); beforeSheetCreate();
// Initialization current sheet // Initialization current sheet
initSheet(sheet); initSheet();
afterSheetCreate(); afterSheetCreate();
} }
private void beforeSheetCreate() { private void beforeSheetCreate() {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(SheetWriteHandler.class); List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(SheetWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) { if (handlerList == null || handlerList.isEmpty()) {
return; return;
} }
for (WriteHandler writeHandler : handlerList) { for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof SheetWriteHandler) { if (writeHandler instanceof SheetWriteHandler) {
((SheetWriteHandler)writeHandler).beforeSheetCreate(currentWorkbookHolder, currentSheetHolder); ((SheetWriteHandler)writeHandler).beforeSheetCreate(writeWorkbookHolder, writeSheetHolder);
} }
} }
} }
private void afterSheetCreate() { private void afterSheetCreate() {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(SheetWriteHandler.class); List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(SheetWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) { if (handlerList == null || handlerList.isEmpty()) {
return; return;
} }
for (WriteHandler writeHandler : handlerList) { for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof SheetWriteHandler) { if (writeHandler instanceof SheetWriteHandler) {
((SheetWriteHandler)writeHandler).afterSheetCreate(currentWorkbookHolder, currentSheetHolder); ((SheetWriteHandler)writeHandler).afterSheetCreate(writeWorkbookHolder, writeSheetHolder);
} }
} }
if (null != currentWorkbookHolder.getWriteHandler()) { if (null != writeWorkbookHolder.getWriteWorkbook().getWriteHandler()) {
currentWorkbookHolder.getWriteHandler().sheet(currentSheetHolder.getSheetNo(), writeWorkbookHolder.getWriteWorkbook().getWriteHandler().sheet(writeSheetHolder.getSheetNo(),
currentSheetHolder.getSheet()); writeSheetHolder.getSheet());
} }
} }
private void initCurrentSheetHolder(com.alibaba.excel.write.metadata.Sheet sheet) { private void initCurrentSheetHolder(WriteSheet writeSheet) {
currentSheetHolder = new SheetHolder(sheet, currentWorkbookHolder); writeSheetHolder = new WriteSheetHolder(writeSheet, writeWorkbookHolder);
currentWorkbookHolder.getHasBeenInitializedSheet().put(sheet.getSheetNo(), currentSheetHolder); writeWorkbookHolder.getHasBeenInitializedSheet().put(writeSheet.getSheetNo(), writeSheetHolder);
currentTableHolder = null; writeTableHolder = null;
currentWriteConfiguration = currentSheetHolder; currentWriteHolder = writeSheetHolder;
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CurrentConfiguration is currentSheetHolder"); LOGGER.debug("CurrentConfiguration is writeSheetHolder");
} }
} }
private void initSheet(com.alibaba.excel.write.metadata.Sheet sheet) { private void initSheet() {
Sheet currentSheet; Sheet currentSheet;
try { try {
currentSheet = currentWorkbookHolder.getWorkbook().getSheetAt(sheet.getSheetNo()); currentSheet = writeWorkbookHolder.getWorkbook().getSheetAt(writeSheetHolder.getSheetNo());
} catch (Exception e) { } catch (Exception e) {
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Can not find sheet:{} ,now create it", sheet.getSheetNo()); LOGGER.debug("Can not find sheet:{} ,now create it", writeSheetHolder.getSheetNo());
} }
currentSheet = WorkBookUtil.createSheet(currentWorkbookHolder.getWorkbook(), sheet); currentSheet = WorkBookUtil.createSheet(writeWorkbookHolder.getWorkbook(), writeSheetHolder.getSheetName());
} }
currentSheetHolder.setSheet(currentSheet); writeSheetHolder.setSheet(currentSheet);
// Initialization head // Initialization head
initHead(currentSheetHolder.getExcelHeadProperty()); initHead(writeSheetHolder.excelWriteHeadProperty());
} }
public void initHead(ExcelHeadProperty excelHeadProperty) { public void initHead(ExcelWriteHeadProperty excelWriteHeadProperty) {
if (!currentWriteConfiguration.needHead() || !currentSheetHolder.getExcelHeadProperty().hasHead()) { if (!currentWriteHolder.needHead() || !currentWriteHolder.excelWriteHeadProperty().hasHead()) {
return; return;
} }
int lastRowNum = currentSheetHolder.getSheet().getLastRowNum(); int lastRowNum = writeSheetHolder.getSheet().getLastRowNum();
int rowIndex = lastRowNum + currentWriteConfiguration.writeRelativeHeadRowIndex(); int rowIndex = lastRowNum + currentWriteHolder.relativeHeadRowIndex();
// Combined head // Combined head
addMergedRegionToCurrentSheet(excelHeadProperty, rowIndex); addMergedRegionToCurrentSheet(excelWriteHeadProperty, rowIndex);
for (int relativeRowIndex = 0, i = rowIndex; i < excelHeadProperty.getHeadRowNumber() + rowIndex; for (int relativeRowIndex = 0, i = rowIndex; i < excelWriteHeadProperty.getHeadRowNumber() + rowIndex;
i++, relativeRowIndex++) { i++, relativeRowIndex++) {
beforeRowCreate(rowIndex, relativeRowIndex); beforeRowCreate(rowIndex, relativeRowIndex);
Row row = WorkBookUtil.createRow(currentSheetHolder.getSheet(), i); Row row = WorkBookUtil.createRow(writeSheetHolder.getSheet(), i);
afterRowCreate(row, relativeRowIndex); afterRowCreate(row, relativeRowIndex);
addOneRowOfHeadDataToExcel(row, excelHeadProperty.getHeadMap(), relativeRowIndex); addOneRowOfHeadDataToExcel(row, excelWriteHeadProperty.getHeadMap(), relativeRowIndex);
} }
} }
private void beforeRowCreate(int rowIndex, int relativeRowIndex) { private void beforeRowCreate(int rowIndex, int relativeRowIndex) {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(RowWriteHandler.class); List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(RowWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) { if (handlerList == null || handlerList.isEmpty()) {
return; return;
} }
for (WriteHandler writeHandler : handlerList) { for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) { if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).beforeRowCreate(currentSheetHolder, currentTableHolder, rowIndex, ((RowWriteHandler)writeHandler).beforeRowCreate(writeSheetHolder, writeTableHolder, rowIndex,
relativeRowIndex, true); relativeRowIndex, true);
} }
} }
} }
private void afterRowCreate(Row row, int relativeRowIndex) { private void afterRowCreate(Row row, int relativeRowIndex) {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(RowWriteHandler.class); List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(RowWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) { if (handlerList == null || handlerList.isEmpty()) {
return; return;
} }
for (WriteHandler writeHandler : handlerList) { for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) { if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).afterRowCreate(currentSheetHolder, currentTableHolder, row, ((RowWriteHandler)writeHandler).afterRowCreate(writeSheetHolder, writeTableHolder, row,
relativeRowIndex, true); relativeRowIndex, true);
} }
} }
if (null != currentWorkbookHolder.getWriteHandler()) { if (null != writeWorkbookHolder.getWriteWorkbook().getWriteHandler()) {
currentWorkbookHolder.getWriteHandler().row(row.getRowNum(), row); writeWorkbookHolder.getWriteWorkbook().getWriteHandler().row(row.getRowNum(), row);
} }
} }
private void addMergedRegionToCurrentSheet(ExcelHeadProperty excelHeadProperty, int rowIndex) { private void addMergedRegionToCurrentSheet(ExcelWriteHeadProperty excelWriteHeadProperty, int rowIndex) {
for (com.alibaba.excel.metadata.CellRange cellRangeModel : excelHeadProperty.headCellRangeList()) { for (com.alibaba.excel.metadata.CellRange cellRangeModel : excelWriteHeadProperty.headCellRangeList()) {
currentSheetHolder.getSheet().addMergedRegion(new CellRangeAddress(cellRangeModel.getFirstRow() + rowIndex, writeSheetHolder.getSheet().addMergedRegion(new CellRangeAddress(cellRangeModel.getFirstRow() + rowIndex,
cellRangeModel.getLastRow() + rowIndex, cellRangeModel.getFirstCol(), cellRangeModel.getLastCol())); cellRangeModel.getLastRow() + rowIndex, cellRangeModel.getFirstCol(), cellRangeModel.getLastCol()));
} }
} }
@ -253,98 +254,98 @@ public class WriteContextImpl implements WriteContext {
} }
private void beforeCellCreate(Row row, Head head, int relativeRowIndex) { private void beforeCellCreate(Row row, Head head, int relativeRowIndex) {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(CellWriteHandler.class); List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(CellWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) { if (handlerList == null || handlerList.isEmpty()) {
return; return;
} }
for (WriteHandler writeHandler : handlerList) { for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof CellWriteHandler) { if (writeHandler instanceof CellWriteHandler) {
((CellWriteHandler)writeHandler).beforeCellCreate(currentSheetHolder, currentTableHolder, row, head, ((CellWriteHandler)writeHandler).beforeCellCreate(writeSheetHolder, writeTableHolder, row, head,
relativeRowIndex, true); relativeRowIndex, true);
} }
} }
} }
private void afterCellCreate(Head head, Cell cell, int relativeRowIndex) { private void afterCellCreate(Head head, Cell cell, int relativeRowIndex) {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(CellWriteHandler.class); List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(CellWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) { if (handlerList == null || handlerList.isEmpty()) {
return; return;
} }
for (WriteHandler writeHandler : handlerList) { for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof CellWriteHandler) { if (writeHandler instanceof CellWriteHandler) {
((CellWriteHandler)writeHandler).afterCellCreate(currentSheetHolder, currentTableHolder, cell, head, ((CellWriteHandler)writeHandler).afterCellCreate(writeSheetHolder, writeTableHolder, cell, head,
relativeRowIndex, true); relativeRowIndex, true);
} }
} }
if (null != currentWorkbookHolder.getWriteHandler()) { if (null != writeWorkbookHolder.getWriteWorkbook().getWriteHandler()) {
currentWorkbookHolder.getWriteHandler().cell(cell.getRowIndex(), cell); writeWorkbookHolder.getWriteWorkbook().getWriteHandler().cell(cell.getRowIndex(), cell);
} }
} }
@Override @Override
public void currentTable(Table table) { public void currentTable(WriteTable writeTable) {
if (table == null) { if (writeTable == null) {
return; return;
} }
if (table.getTableNo() == null || table.getTableNo() <= 0) { if (writeTable.getTableNo() == null || writeTable.getTableNo() <= 0) {
table.setTableNo(0); writeTable.setTableNo(0);
} }
if (currentSheetHolder.getHasBeenInitializedTable().containsKey(table.getTableNo())) { if (writeSheetHolder.getHasBeenInitializedTable().containsKey(writeTable.getTableNo())) {
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Table:{} is already existed", table.getTableNo()); LOGGER.debug("Table:{} is already existed", writeTable.getTableNo());
} }
currentTableHolder = currentSheetHolder.getHasBeenInitializedTable().get(table.getTableNo()); writeTableHolder = writeSheetHolder.getHasBeenInitializedTable().get(writeTable.getTableNo());
currentTableHolder.setNewInitialization(Boolean.FALSE); writeTableHolder.setNewInitialization(Boolean.FALSE);
currentWriteConfiguration = currentTableHolder; currentWriteHolder = writeTableHolder;
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CurrentConfiguration is currentTableHolder"); LOGGER.debug("CurrentConfiguration is writeTableHolder");
} }
return; return;
} }
initCurrentTableHolder(table); initCurrentTableHolder(writeTable);
initHead(currentTableHolder.getExcelHeadProperty()); initHead(writeTableHolder.excelWriteHeadProperty());
} }
private void initCurrentTableHolder(Table table) { private void initCurrentTableHolder(WriteTable writeTable) {
currentTableHolder = new TableHolder(table, currentSheetHolder, currentWorkbookHolder); writeTableHolder = new WriteTableHolder(writeTable, writeSheetHolder, writeWorkbookHolder);
currentSheetHolder.getHasBeenInitializedTable().put(table.getTableNo(), currentTableHolder); writeSheetHolder.getHasBeenInitializedTable().put(writeTable.getTableNo(), writeTableHolder);
currentWriteConfiguration = currentTableHolder; currentWriteHolder = writeTableHolder;
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CurrentConfiguration is currentTableHolder"); LOGGER.debug("CurrentConfiguration is writeTableHolder");
} }
} }
@Override @Override
public WriteConfiguration currentConfiguration() { public WriteWorkbookHolder writeWorkbookHolder() {
return currentWriteConfiguration; return writeWorkbookHolder;
} }
@Override @Override
public WorkbookHolder currentWorkbookHolder() { public WriteSheetHolder writeSheetHolder() {
return currentWorkbookHolder; return writeSheetHolder;
} }
@Override @Override
public SheetHolder currentSheetHolder() { public WriteTableHolder writeTableHolder() {
return currentSheetHolder; return writeTableHolder;
} }
@Override @Override
public TableHolder currentTableHolder() { public WriteHolder currentWriteHolder() {
return currentTableHolder; return currentWriteHolder;
} }
@Override @Override
public void finish() { public void finish() {
try { try {
currentWorkbookHolder.getWorkbook().write(currentWorkbookHolder.getOutputStream()); writeWorkbookHolder.getWorkbook().write(writeWorkbookHolder.getOutputStream());
currentWorkbookHolder.getWorkbook().close(); writeWorkbookHolder.getWorkbook().close();
if (currentWorkbookHolder.getAutoCloseStream()) { if (writeWorkbookHolder.getAutoCloseStream()) {
if (currentWorkbookHolder.getOutputStream() != null) { if (writeWorkbookHolder.getOutputStream() != null) {
currentWorkbookHolder.getOutputStream().close(); writeWorkbookHolder.getOutputStream().close();
} }
if (currentWorkbookHolder.getTemplateInputStream() != null) { if (writeWorkbookHolder.getTemplateInputStream() != null) {
currentWorkbookHolder.getTemplateInputStream().close(); writeWorkbookHolder.getTemplateInputStream().close();
} }
} }
} catch (IOException e) { } catch (IOException e) {

27
src/main/java/com/alibaba/excel/event/AbstractIgnoreExceptionReadListener.java

@ -0,0 +1,27 @@
package com.alibaba.excel.event;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
/**
* Receives the return of each piece of data parsed
*
* @author jipengfei
*/
public abstract class AbstractIgnoreExceptionReadListener<T> implements ReadListener<T> {
/**
* All listeners receive this method when any one Listener does an error report. If an exception is thrown here, the
* entire read will terminate.
*
* @param exception
* @param context
*/
@Override
public void onException(Exception exception, AnalysisContext context) {}
@Override
public boolean hasNext(AnalysisContext context) {
return true;
}
}

31
src/main/java/com/alibaba/excel/event/SyncReadListener.java

@ -0,0 +1,31 @@
package com.alibaba.excel.event;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
/**
* Synchronous data reading
*
* @author zhuangjiaju
*/
public class SyncReadListener extends AnalysisEventListener<Object> {
private List<Object> list = new ArrayList<Object>();
@Override
public void invoke(Object object, AnalysisContext context) {
list.add(object);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {}
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
}

22
src/main/java/com/alibaba/excel/exception/ExcelCommonException.java

@ -0,0 +1,22 @@
package com.alibaba.excel.exception;
/**
*
* @author zhuangjiaju
*/
public class ExcelCommonException extends RuntimeException {
public ExcelCommonException() {}
public ExcelCommonException(String message) {
super(message);
}
public ExcelCommonException(String message, Throwable cause) {
super(message, cause);
}
public ExcelCommonException(Throwable cause) {
super(cause);
}
}

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

@ -21,15 +21,8 @@ public class CellData {
* {@link CellDataTypeEnum#BOOLEAN} * {@link CellDataTypeEnum#BOOLEAN}
*/ */
private Boolean booleanValue; private Boolean booleanValue;
private Boolean formula;
/** private String formulaValue;
* Support only when reading
*/
private Boolean readIsFormula;
/**
* Support only when reading
*/
private String readFormula;
public CellData(String stringValue) { public CellData(String stringValue) {
this(CellDataTypeEnum.STRING, stringValue); this(CellDataTypeEnum.STRING, stringValue);
@ -44,7 +37,7 @@ public class CellData {
} }
this.type = type; this.type = type;
this.stringValue = stringValue; this.stringValue = stringValue;
this.readIsFormula = Boolean.FALSE; this.formula = Boolean.FALSE;
} }
public CellData(Double doubleValue) { public CellData(Double doubleValue) {
@ -53,7 +46,7 @@ public class CellData {
} }
this.type = CellDataTypeEnum.NUMBER; this.type = CellDataTypeEnum.NUMBER;
this.doubleValue = doubleValue; this.doubleValue = doubleValue;
this.readIsFormula = Boolean.FALSE; this.formula = Boolean.FALSE;
} }
public CellData(Boolean booleanValue) { public CellData(Boolean booleanValue) {
@ -62,7 +55,7 @@ public class CellData {
} }
this.type = CellDataTypeEnum.BOOLEAN; this.type = CellDataTypeEnum.BOOLEAN;
this.booleanValue = booleanValue; this.booleanValue = booleanValue;
this.readIsFormula = Boolean.FALSE; this.formula = Boolean.FALSE;
} }
public CellData(CellDataTypeEnum type) { public CellData(CellDataTypeEnum type) {
@ -70,7 +63,7 @@ public class CellData {
throw new IllegalArgumentException("Type can not be null"); throw new IllegalArgumentException("Type can not be null");
} }
this.type = type; this.type = type;
this.readIsFormula = Boolean.FALSE; this.formula = Boolean.FALSE;
} }
public CellDataTypeEnum getType() { public CellDataTypeEnum getType() {
@ -105,20 +98,20 @@ public class CellData {
this.booleanValue = booleanValue; this.booleanValue = booleanValue;
} }
public Boolean getReadIsFormula() { public Boolean getFormula() {
return readIsFormula; return formula;
} }
public void setReadIsFormula(Boolean readIsFormula) { public void setFormula(Boolean formula) {
this.readIsFormula = readIsFormula; this.formula = formula;
} }
public String getReadFormula() { public String getFormulaValue() {
return readFormula; return formulaValue;
} }
public void setReadFormula(String readFormula) { public void setFormulaValue(String formulaValue) {
this.readFormula = readFormula; this.formulaValue = formulaValue;
} }
@Override @Override

22
src/main/java/com/alibaba/excel/metadata/Sheet.java

@ -7,7 +7,10 @@ import java.util.Map;
/** /**
* *
* @author jipengfei * @author jipengfei
* @deprecated pleas use {@link com.alibaba.excel.write.metadata.WriteSheet} or
* {@link com.alibaba.excel.read.metadata.ReadSheet}
*/ */
@Deprecated
public class Sheet { public class Sheet {
/** /**
@ -39,7 +42,7 @@ public class Sheet {
/** /**
* column with * column with
*/ */
private Map<Integer,Integer> columnWidthMap = new HashMap<Integer, Integer>(); private Map<Integer, Integer> columnWidthMap = new HashMap<Integer, Integer>();
/** /**
* *
@ -51,7 +54,6 @@ public class Sheet {
*/ */
private int startRow = 0; private int startRow = 0;
public Sheet(int sheetNo) { public Sheet(int sheetNo) {
this.sheetNo = sheetNo; this.sheetNo = sheetNo;
} }
@ -68,7 +70,7 @@ public class Sheet {
} }
public Sheet(int sheetNo, int headLineMun, Class<? extends BaseRowModel> clazz, String sheetName, public Sheet(int sheetNo, int headLineMun, Class<? extends BaseRowModel> clazz, String sheetName,
List<List<String>> head) { List<List<String>> head) {
this.sheetNo = sheetNo; this.sheetNo = sheetNo;
this.clazz = clazz; this.clazz = clazz;
this.headLineMun = headLineMun; this.headLineMun = headLineMun;
@ -127,8 +129,6 @@ public class Sheet {
this.tableStyle = tableStyle; this.tableStyle = tableStyle;
} }
public Map<Integer, Integer> getColumnWidthMap() { public Map<Integer, Integer> getColumnWidthMap() {
return columnWidthMap; return columnWidthMap;
} }
@ -139,15 +139,9 @@ public class Sheet {
@Override @Override
public String toString() { public String toString() {
return "Sheet{" + return "Sheet{" + "headLineMun=" + headLineMun + ", sheetNo=" + sheetNo + ", sheetName='" + sheetName + '\''
"headLineMun=" + headLineMun + + ", clazz=" + clazz + ", head=" + head + ", tableStyle=" + tableStyle + ", columnWidthMap="
", sheetNo=" + sheetNo + + columnWidthMap + '}';
", sheetName='" + sheetName + '\'' +
", clazz=" + clazz +
", head=" + head +
", tableStyle=" + tableStyle +
", columnWidthMap=" + columnWidthMap +
'}';
} }
public Boolean getAutoWidth() { public Boolean getAutoWidth() {

10
src/main/java/com/alibaba/excel/metadata/Table.java

@ -4,7 +4,9 @@ import java.util.List;
/** /**
* @author jipengfei * @author jipengfei
* @deprecated please use {@link com.alibaba.excel.write.metadata.WriteTable}
*/ */
@Deprecated
public class Table { public class Table {
/** /**
*/ */
@ -22,6 +24,10 @@ public class Table {
*/ */
private TableStyle tableStyle; private TableStyle tableStyle;
public Table(Integer tableNo) {
this.tableNo = tableNo;
}
public TableStyle getTableStyle() { public TableStyle getTableStyle() {
return tableStyle; return tableStyle;
} }
@ -30,10 +36,6 @@ public class Table {
this.tableStyle = tableStyle; this.tableStyle = tableStyle;
} }
public Table(Integer tableNo) {
this.tableNo = tableNo;
}
public Class<? extends BaseRowModel> getClazz() { public Class<? extends BaseRowModel> getClazz() {
return clazz; return clazz;
} }

494
src/main/java/com/alibaba/excel/metadata/holder/read/AbstractWriteConfiguration.java

@ -1,494 +0,0 @@
package com.alibaba.excel.metadata.holder.read;
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.Sheet;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKey;
import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.event.Order;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.CellStyle;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.holder.write.WriteConfiguration;
import com.alibaba.excel.metadata.property.CellStyleProperty;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.metadata.property.ExcelHeadProperty;
import com.alibaba.excel.metadata.property.RowHeightProperty;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.listener.ReadListenerRegistryCenter;
import com.alibaba.excel.read.listener.event.AnalysisFinishEvent;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.style.AbstractColumnCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
/**
* sheet holder
*
* @author zhuangjiaju
*/
public abstract class AbstractWriteConfiguration
implements WriteConfiguration, ReadConfiguration, ReadListenerRegistryCenter {
/**
* Need Head
*/
private Boolean needHead;
/**
* Write handler for workbook
*/
private Map<Class<? extends WriteHandler>, List<WriteHandler>> writeHandlerMap;
/**
* Read listener
*/
private List<ReadListener> readListenerList;
/**
* Converter for workbook
*/
private Map<ConverterKey, Converter> readConverterMap;
/**
* Converter for workbook
*/
private Map<Class, Converter> writeConverterMap;
/**
* Excel head property
*/
private ExcelHeadProperty excelHeadProperty;
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*/
private Integer writeRelativeHeadRowIndex;
/**
* Record whether it's new or from cache
*/
private Boolean newInitialization;
/**
* Count the number of added heads when read sheet.
*
* <li>0 - This Sheet has no head ,since the first row are the data
* <li>1 - This Sheet has one row head , this is the default
* <li>2 - This Sheet has two row head ,since the third row is the data
*/
private Integer readHeadRowNumber;
/**
* You can only choose one of the {@link AbstractWriteConfiguration#head} and
* {@link AbstractWriteConfiguration#clazz}
*/
private List<List<String>> head;
/**
* You can only choose one of the {@link AbstractWriteConfiguration#head} and
* {@link AbstractWriteConfiguration#clazz}
*/
private Class clazz;
/**
* Automatic trim includes sheet name and content
*/
private Boolean autoTrim;
public Boolean getNeedHead() {
return needHead;
}
public void setNeedHead(Boolean needHead) {
this.needHead = needHead;
}
public Map<Class<? extends WriteHandler>, List<WriteHandler>> getWriteHandlerMap() {
return writeHandlerMap;
}
public void setWriteHandlerMap(Map<Class<? extends WriteHandler>, List<WriteHandler>> writeHandlerMap) {
this.writeHandlerMap = writeHandlerMap;
}
public ExcelHeadProperty getExcelHeadProperty() {
return excelHeadProperty;
}
public void setExcelHeadProperty(ExcelHeadProperty excelHeadProperty) {
this.excelHeadProperty = excelHeadProperty;
}
public Integer getWriteRelativeHeadRowIndex() {
return writeRelativeHeadRowIndex;
}
public void setWriteRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) {
this.writeRelativeHeadRowIndex = writeRelativeHeadRowIndex;
}
public Boolean getNewInitialization() {
return newInitialization;
}
public void setNewInitialization(Boolean newInitialization) {
this.newInitialization = newInitialization;
}
public List<List<String>> getHead() {
return head;
}
public void setHead(List<List<String>> head) {
this.head = head;
}
public Class getClazz() {
return clazz;
}
public void setClazz(Class clazz) {
this.clazz = clazz;
}
public Boolean getAutoTrim() {
return autoTrim;
}
public void setAutoTrim(Boolean autoTrim) {
this.autoTrim = autoTrim;
}
public List<ReadListener> getReadListenerList() {
return readListenerList;
}
public void setReadListenerList(List<ReadListener> readListenerList) {
this.readListenerList = readListenerList;
}
public Map<ConverterKey, Converter> getReadConverterMap() {
return readConverterMap;
}
public void setReadConverterMap(Map<ConverterKey, Converter> readConverterMap) {
this.readConverterMap = readConverterMap;
}
public Map<Class, Converter> getWriteConverterMap() {
return writeConverterMap;
}
public void setWriteConverterMap(Map<Class, Converter> writeConverterMap) {
this.writeConverterMap = writeConverterMap;
}
public Integer getReadHeadRowNumber() {
return readHeadRowNumber;
}
public void setReadHeadRowNumber(Integer readHeadRowNumber) {
this.readHeadRowNumber = readHeadRowNumber;
}
@Override
public void register(AnalysisEventListener listener) {
readListenerList.add(listener);
}
@Override
public void notifyEndOneRow(AnalysisFinishEvent event, AnalysisContext analysisContext) {
List<CellData> cellDataList = (List<CellData>)event.getAnalysisResult();
if (analysisContext.currentRowNum() > analysisContext.currentSheetHolder().getReadHeadRowNumber()) {
for (ReadListener readListener : readListenerList) {
try {
readListener.invoke(analysisContext.currentRowAnalysisResult(), analysisContext);
} catch (Exception e) {
for (ReadListener readListenerException : readListenerList) {
try {
readListenerException.onException(e, analysisContext);
} catch (Exception exception) {
throw new ExcelAnalysisException("Listen error!", exception);
}
}
}
}
}
// Now is header
if (analysisContext.currentRowNum().equals(analysisContext.currentSheetHolder().getReadHeadRowNumber())) {
buildHead(analysisContext, cellDataList);
}
}
@Override
public void notifyAfterAllAnalysed(AnalysisContext analysisContext) {
for (ReadListener readListener : readListenerList) {
readListener.doAfterAllAnalysed(analysisContext);
}
}
private void buildHead(AnalysisContext analysisContext, List<CellData> cellDataList) {
if (!HeadKindEnum.CLASS.equals(analysisContext.currentConfiguration().excelHeadProperty().getHeadKind())) {
return;
}
List<String> dataList = (List<String>)buildStringList(cellDataList, analysisContext.currentConfiguration());
ExcelHeadProperty excelHeadPropertyData = analysisContext.currentConfiguration().excelHeadProperty();
Map<Integer, Head> headMapData = excelHeadPropertyData.getHeadMap();
Map<Integer, ExcelContentProperty> contentPropertyMapData = excelHeadPropertyData.getContentPropertyMap();
Map<Integer, Head> tmpHeadMap = new HashMap<Integer, Head>(headMapData.size() * 4 / 3 + 1);
Map<Integer, ExcelContentProperty> tmpContentPropertyMap =
new HashMap<Integer, ExcelContentProperty>(contentPropertyMapData.size() * 4 / 3 + 1);
for (Map.Entry<Integer, Head> entry : headMapData.entrySet()) {
Head headData = entry.getValue();
if (headData.getForceIndex()) {
tmpHeadMap.put(entry.getKey(), headData);
tmpContentPropertyMap.put(entry.getKey(), contentPropertyMapData.get(entry.getKey()));
continue;
}
String headName = headData.getHeadNameList().get(0);
for (int i = 0; i < dataList.size(); i++) {
String headString = dataList.get(i);
if (StringUtils.isEmpty(headString)) {
continue;
}
if (analysisContext.currentSheetHolder().getAutoTrim()) {
headString = headString.trim();
}
if (headName.equals(headString)) {
headData.setColumnIndex(i);
tmpHeadMap.put(i, headData);
tmpContentPropertyMap.put(i, contentPropertyMapData.get(entry.getKey()));
break;
}
}
}
excelHeadPropertyData.setHeadMap(tmpHeadMap);
excelHeadPropertyData.setContentPropertyMap(tmpContentPropertyMap);
}
private Object buildStringList(List<CellData> data, ReadConfiguration readConfiguration) {
List<String> list = new ArrayList<String>();
for (CellData cellData : data) {
Converter converter = readConfiguration.readConverterMap()
.get(ConverterKey.buildConverterKey(String.class, cellData.getType()));
if (converter == null) {
throw new ExcelDataConvertException(
"Converter not found, convert " + cellData.getType() + " to String");
}
try {
list.add((String)(converter.convertToJavaData(cellData, null)));
} catch (Exception e) {
throw new ExcelDataConvertException("Convert data " + cellData + " to String error ", e);
}
}
return list;
}
protected Map<Class<? extends WriteHandler>, List<WriteHandler>> sortAndClearUpHandler(
List<WriteHandler> handlerList, Map<Class<? extends WriteHandler>, List<WriteHandler>> parentHandlerMap) {
// add
if (parentHandlerMap != null) {
for (List<WriteHandler> parentHandlerList : parentHandlerMap.values()) {
handlerList.addAll(parentHandlerList);
}
}
// sort
Map<Integer, List<WriteHandler>> orderExcelWriteHandlerMap = new TreeMap<Integer, List<WriteHandler>>();
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<WriteHandler> tempHandlerList = new ArrayList<WriteHandler>();
tempHandlerList.add(handler);
orderExcelWriteHandlerMap.put(order, tempHandlerList);
}
}
// clean up
Set<String> alreadyExistedHandlerSet = new HashSet<String>();
List<WriteHandler> cleanUpHandlerList = new ArrayList<WriteHandler>();
for (Map.Entry<Integer, List<WriteHandler>> 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);
}
cleanUpHandlerList.add(handler);
}
}
// classify
Map<Class<? extends WriteHandler>, List<WriteHandler>> result =
new HashMap<Class<? extends WriteHandler>, List<WriteHandler>>();
result.put(WriteHandler.class, new ArrayList<WriteHandler>());
result.put(WorkbookWriteHandler.class, new ArrayList<WriteHandler>());
result.put(SheetWriteHandler.class, new ArrayList<WriteHandler>());
result.put(RowWriteHandler.class, new ArrayList<WriteHandler>());
result.put(CellWriteHandler.class, new ArrayList<WriteHandler>());
for (WriteHandler writeHandler : cleanUpHandlerList) {
if (writeHandler instanceof CellWriteHandler) {
result.get(CellWriteHandler.class).add(writeHandler);
}
if (writeHandler instanceof RowWriteHandler) {
result.get(RowWriteHandler.class).add(writeHandler);
}
if (writeHandler instanceof SheetWriteHandler) {
result.get(SheetWriteHandler.class).add(writeHandler);
}
if (writeHandler instanceof SheetWriteHandler) {
result.get(SheetWriteHandler.class).add(writeHandler);
}
if (writeHandler instanceof WorkbookWriteHandler) {
result.get(WorkbookWriteHandler.class).add(writeHandler);
}
result.get(WriteHandler.class).add(writeHandler);
}
return result;
}
protected void initAnnotationConfig(List<WriteHandler> handlerList) {
if (!HeadKindEnum.CLASS.equals(getExcelHeadProperty().getHeadKind())) {
return;
}
Map<Integer, Head> headMap = getExcelHeadProperty().getHeadMap();
Map<Integer, ExcelContentProperty> contentPropertyMap = getExcelHeadProperty().getContentPropertyMap();
boolean hasCellStyle = false;
boolean hasColumnWidth = false;
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
if (entry.getValue().getCellStyleProperty() != null) {
hasCellStyle = true;
}
if (entry.getValue().getColumnWidthProperty() != null) {
hasColumnWidth = true;
}
ExcelContentProperty excelContentProperty = contentPropertyMap.get(entry.getKey());
if (excelContentProperty.getCellStyleProperty() != null) {
hasCellStyle = true;
}
}
if (hasCellStyle) {
dealCellStyle(handlerList, contentPropertyMap);
}
if (hasColumnWidth) {
dealColumnWidth(handlerList);
}
dealRowHigh(handlerList, contentPropertyMap);
}
private void dealRowHigh(List<WriteHandler> handlerList, Map<Integer, ExcelContentProperty> contentPropertyMap) {
RowHeightProperty headRowHeightProperty = excelHeadProperty.getHeadRowHeightProperty();
RowHeightProperty contentRowHeightProperty = excelHeadProperty.getContentRowHeightProperty();
if (headRowHeightProperty == null && contentRowHeightProperty == null) {
return;
}
Short headRowHeight = null;
if (headRowHeightProperty != null) {
headRowHeight = headRowHeightProperty.getHeight();
}
Short contentRowHeight = null;
if (contentRowHeightProperty != null) {
contentRowHeight = contentRowHeightProperty.getHeight();
}
handlerList.add(new SimpleRowHeightStyleStrategy(headRowHeight, contentRowHeight));
}
private void dealColumnWidth(List<WriteHandler> handlerList) {
WriteHandler columnWidthStyleStrategy = new AbstractColumnWidthStyleStrategy() {
@Override
protected void setColumnWidth(Sheet sheet, Cell cell, Head head) {
if (head == null) {
return;
}
if (head.getColumnWidthProperty() != null) {
sheet.setColumnWidth(head.getColumnIndex(), head.getColumnWidthProperty().getWidth());
}
}
};
handlerList.add(columnWidthStyleStrategy);
}
private void dealCellStyle(List<WriteHandler> handlerList,
final Map<Integer, ExcelContentProperty> contentPropertyMap) {
WriteHandler columnCellStyleStrategy = new AbstractColumnCellStyleStrategy() {
@Override
protected CellStyle headCellStyle(Head head) {
if (head == null || head.getCellStyleProperty() == null) {
return null;
}
CellStyleProperty cellStyleProperty = head.getCellStyleProperty();
return new CellStyle(cellStyleProperty.getFontName(), cellStyleProperty.getFontHeightInPoints(),
cellStyleProperty.getBold(), cellStyleProperty.getIndexedColors());
}
@Override
protected CellStyle contentCellStyle(Head head) {
if (head == null) {
return null;
}
ExcelContentProperty excelContentProperty = contentPropertyMap.get(head.getColumnIndex());
if (excelContentProperty == null || excelContentProperty.getCellStyleProperty() == null) {
return null;
}
CellStyleProperty cellStyleProperty = excelContentProperty.getCellStyleProperty();
return new CellStyle(cellStyleProperty.getFontName(), cellStyleProperty.getFontHeightInPoints(),
cellStyleProperty.getBold(), cellStyleProperty.getIndexedColors());
}
};
handlerList.add(columnCellStyleStrategy);
}
@Override
public Map<Class<? extends WriteHandler>, List<WriteHandler>> writeHandlerMap() {
return getWriteHandlerMap();
}
@Override
public boolean needHead() {
return getNeedHead();
}
@Override
public int writeRelativeHeadRowIndex() {
return getWriteRelativeHeadRowIndex();
}
@Override
public ExcelHeadProperty excelHeadProperty() {
return getExcelHeadProperty();
}
@Override
public boolean isNew() {
return getNewInitialization();
}
@Override
public List<ReadListener> readListenerList() {
return getReadListenerList();
}
@Override
public Map<ConverterKey, Converter> readConverterMap() {
return getReadConverterMap();
}
@Override
public Map<Class, Converter> writeConverterMap() {
return getWriteConverterMap();
}
}

39
src/main/java/com/alibaba/excel/metadata/holder/read/ReadConfiguration.java

@ -1,39 +0,0 @@
package com.alibaba.excel.metadata.holder.read;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKey;
import com.alibaba.excel.metadata.property.ExcelHeadProperty;
import com.alibaba.excel.read.listener.ReadListener;
/**
*
* Get the corresponding configuration
*
* @author zhuangjiaju
**/
public interface ReadConfiguration {
/**
* What handler does the currently operated cell need to execute
*
* @return
*/
List<ReadListener> readListenerList();
/**
* What converter does the currently operated cell need to execute
*
* @return
*/
Map<ConverterKey, Converter> readConverterMap();
/**
* What 'ExcelHeadProperty' does the currently operated cell need to execute
*
* @return
*/
ExcelHeadProperty excelHeadProperty();
}

235
src/main/java/com/alibaba/excel/metadata/holder/read/SheetHolder.java

@ -1,235 +0,0 @@
package com.alibaba.excel.metadata.holder.read;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKey;
import com.alibaba.excel.metadata.CellStyle;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.metadata.holder.write.AbstractWriteConfiguration;
import com.alibaba.excel.metadata.property.ExcelHeadProperty;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.style.RowCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractHeadColumnWidthStyleStrategy;
/**
* sheet holder
*
* @author zhuangjiaju
*/
public class SheetHolder extends AbstractWriteConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(SheetHolder.class);
/***
* poi sheet
*/
private Sheet sheet;
/***
* sheetNo
*/
private Integer sheetNo;
/***
* sheetName
*/
private String sheetName;
/***
* poi sheet
*/
private WorkbookHolder parentWorkBook;
/***
* has been initialized table
*/
private Map<Integer, TableHolder> hasBeenInitializedTable;
/**
* current param
*/
private com.alibaba.excel.metadata.Sheet sheetParam;
public static SheetHolder buildWriteWorkSheetHolder(com.alibaba.excel.metadata.Sheet sheet,
WorkbookHolder workbookHolder) {
SheetHolder sheetHolder = buildBaseSheetHolder(sheet, workbookHolder);
sheetHolder.setNewInitialization(Boolean.TRUE);
if (sheet.getNeedHead() == null) {
sheetHolder.setNeedHead(workbookHolder.needHead());
} else {
sheetHolder.setNeedHead(sheet.getNeedHead());
}
if (sheet.getWriteRelativeHeadRowIndex() == null) {
sheetHolder.setWriteRelativeHeadRowIndex(workbookHolder.writeRelativeHeadRowIndex());
} else {
sheetHolder.setWriteRelativeHeadRowIndex(sheet.getWriteRelativeHeadRowIndex());
}
// Compatible with old code
compatibleOldCode(sheet);
List<WriteHandler> handlerList = new ArrayList<WriteHandler>();
if (sheet.getCustomWriteHandlerList() != null && !sheet.getCustomWriteHandlerList().isEmpty()) {
handlerList.addAll(sheet.getCustomWriteHandlerList());
}
// Initialization Annotation
sheetHolder.initAnnotationConfig(handlerList);
sheetHolder
.setWriteHandlerMap(sheetHolder.sortAndClearUpHandler(handlerList, workbookHolder.getWriteHandlerMap()));
Map<Class, Converter> converterMap = new HashMap<Class, Converter>(workbookHolder.getWriteConverterMap());
if (sheet.getCustomConverterList() != null && !sheet.getCustomConverterList().isEmpty()) {
for (Converter converter : sheet.getCustomConverterList()) {
converterMap.put(converter.getClass(), converter);
}
}
sheetHolder.setWriteConverterMap(converterMap);
sheetHolder.setHasBeenInitializedTable(new HashMap<Integer, TableHolder>());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sheet writeHandlerMap:{}", sheetHolder.getWriteHandlerMap());
}
return sheetHolder;
}
public static SheetHolder buildReadWorkSheetHolder(com.alibaba.excel.metadata.Sheet sheet,
WorkbookHolder workbookHolder) {
SheetHolder sheetHolder = buildBaseSheetHolder(sheet, workbookHolder);
if (sheet.getReadHeadRowNumber() == null) {
if (workbookHolder.getReadHeadRowNumber() == null) {
sheetHolder.setReadHeadRowNumber(sheetHolder.getExcelHeadProperty().getHeadRowNumber());
} else {
sheetHolder.setReadHeadRowNumber(workbookHolder.getReadHeadRowNumber());
}
} else {
sheetHolder.setReadHeadRowNumber(sheet.getReadHeadRowNumber());
}
Map<ConverterKey, Converter> converterMap =
new HashMap<ConverterKey, Converter>(workbookHolder.getReadConverterMap());
if (sheet.getCustomConverterList() != null && !sheet.getCustomConverterList().isEmpty()) {
for (Converter converter : sheet.getCustomConverterList()) {
converterMap.put(ConverterKey.buildConverterKey(converter), converter);
}
}
sheetHolder.setReadConverterMap(converterMap);
List<ReadListener> readListenerList = new ArrayList<ReadListener>();
if (sheet.getCustomReadListenerList() != null && !sheet.getCustomReadListenerList().isEmpty()) {
readListenerList.addAll(sheet.getCustomReadListenerList());
}
sheetHolder.setReadListenerList(readListenerList);
return sheetHolder;
}
private static SheetHolder buildBaseSheetHolder(com.alibaba.excel.metadata.Sheet sheet,
WorkbookHolder workbookHolder) {
SheetHolder sheetHolder = new SheetHolder();
sheetHolder.setSheetParam(sheet);
sheetHolder.setParentWorkBook(workbookHolder);
boolean noHead = (sheet.getHead() == null || sheet.getHead().isEmpty()) && sheet.getClazz() == null;
if (noHead) {
// Use parent
sheetHolder.setHead(workbookHolder.getHead());
sheetHolder.setClazz(workbookHolder.getClazz());
} else {
sheetHolder.setHead(sheet.getHead());
sheetHolder.setClazz(sheet.getClazz());
}
if (sheet.getAutoTrim() == null) {
workbookHolder.setAutoTrim(workbookHolder.getAutoTrim());
} else {
workbookHolder.setAutoTrim(sheet.getNeedHead());
}
// Initialization property
sheetHolder
.setExcelHeadProperty(new ExcelHeadProperty(sheetHolder.getClazz(), sheetHolder.getHead(), workbookHolder));
return sheetHolder;
}
/**
* Compatible with old code
*/
@Deprecated
private static void compatibleOldCode(com.alibaba.excel.metadata.Sheet sheet) {
if (sheet.getColumnWidthMap() != null && !sheet.getColumnWidthMap().isEmpty()) {
final Map<Integer, Integer> columnWidthMap = sheet.getColumnWidthMap();
if (sheet.getCustomWriteHandlerList() == null) {
sheet.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
sheet.getCustomWriteHandlerList().add(new AbstractHeadColumnWidthStyleStrategy() {
@Override
protected Integer columnWidth(Head head) {
if (columnWidthMap.containsKey(head.getColumnIndex())) {
columnWidthMap.get(head.getColumnIndex());
}
return 20;
}
});
}
if (sheet.getTableStyle() != null) {
final TableStyle tableStyle = sheet.getTableStyle();
if (sheet.getCustomWriteHandlerList() == null) {
sheet.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
CellStyle headCellStyle = new CellStyle();
headCellStyle.setFont(tableStyle.getTableHeadFont());
headCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor());
CellStyle contentCellStyle = new CellStyle();
contentCellStyle.setFont(tableStyle.getTableContentFont());
contentCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor());
sheet.getCustomWriteHandlerList().add(new RowCellStyleStrategy(headCellStyle, contentCellStyle));
}
}
public Sheet getSheet() {
return sheet;
}
public void setSheet(Sheet sheet) {
this.sheet = sheet;
}
public Integer getSheetNo() {
return sheetNo;
}
public void setSheetNo(Integer sheetNo) {
this.sheetNo = sheetNo;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public WorkbookHolder getParentWorkBook() {
return parentWorkBook;
}
public void setParentWorkBook(WorkbookHolder parentWorkBook) {
this.parentWorkBook = parentWorkBook;
}
public Map<Integer, TableHolder> getHasBeenInitializedTable() {
return hasBeenInitializedTable;
}
public void setHasBeenInitializedTable(Map<Integer, TableHolder> hasBeenInitializedTable) {
this.hasBeenInitializedTable = hasBeenInitializedTable;
}
public com.alibaba.excel.metadata.Sheet getSheetParam() {
return sheetParam;
}
public void setSheetParam(com.alibaba.excel.metadata.Sheet sheetParam) {
this.sheetParam = sheetParam;
}
}

138
src/main/java/com/alibaba/excel/metadata/holder/read/TableHolder.java

@ -1,138 +0,0 @@
package com.alibaba.excel.metadata.holder.read;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.CellStyle;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.metadata.holder.write.AbstractWriteConfiguration;
import com.alibaba.excel.metadata.property.ExcelHeadProperty;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.style.RowCellStyleStrategy;
/**
* sheet holder
*
* @author zhuangjiaju
*/
public class TableHolder extends AbstractWriteConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(TableHolder.class);
/***
* poi sheet
*/
private SheetHolder parentSheet;
/***
* tableNo
*/
private Integer tableNo;
/**
* current table param
*/
private Table tableParam;
public static TableHolder buildWriteWorkTableHolder(Table table, SheetHolder sheetHolder,
WorkbookHolder workbookHolder) {
TableHolder tableHolder = new TableHolder();
tableHolder.setTableParam(table);
tableHolder.setParentSheet(sheetHolder);
tableHolder.setTableNo(table.getTableNo());
boolean noHead = (table.getHead() == null || table.getHead().isEmpty()) && table.getClazz() == null;
if (noHead) {
// Use parent
tableHolder.setHead(sheetHolder.getHead());
tableHolder.setClazz(sheetHolder.getClazz());
} else {
tableHolder.setHead(table.getHead());
tableHolder.setClazz(table.getClazz());
}
tableHolder.setNewInitialization(Boolean.TRUE);
// Initialization property
tableHolder.setExcelHeadProperty(
new ExcelHeadProperty(tableHolder.getClazz(), tableHolder.getHead(), workbookHolder.getConvertAllFiled()));
if (table.getNeedHead() == null) {
tableHolder.setNeedHead(sheetHolder.needHead());
} else {
tableHolder.setNeedHead(table.getNeedHead());
}
if (table.getWriteRelativeHeadRowIndex() == null) {
tableHolder.setWriteRelativeHeadRowIndex(sheetHolder.writeRelativeHeadRowIndex());
} else {
tableHolder.setWriteRelativeHeadRowIndex(table.getWriteRelativeHeadRowIndex());
}
// Compatible with old code
compatibleOldCode(table);
List<WriteHandler> handlerList = new ArrayList<WriteHandler>();
if (table.getCustomWriteHandlerList() != null && !table.getCustomWriteHandlerList().isEmpty()) {
handlerList.addAll(table.getCustomWriteHandlerList());
}
// Initialization Annotation
tableHolder.initAnnotationConfig(handlerList);
tableHolder
.setWriteHandlerMap(tableHolder.sortAndClearUpHandler(handlerList, sheetHolder.getWriteHandlerMap()));
Map<Class, Converter> converterMap = new HashMap<Class, Converter>(sheetHolder.getWriteConverterMap());
if (table.getCustomConverterList() != null && !table.getCustomConverterList().isEmpty()) {
for (Converter converter : table.getCustomConverterList()) {
converterMap.put(converter.getClass(), converter);
}
}
tableHolder.setWriteConverterMap(converterMap);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Table writeHandlerMap:{}", tableHolder.getWriteHandlerMap());
}
return tableHolder;
}
/**
* Compatible with old code
*/
@Deprecated
private static void compatibleOldCode(Table table) {
if (table.getTableStyle() != null) {
final TableStyle tableStyle = table.getTableStyle();
if (table.getCustomWriteHandlerList() == null) {
table.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
CellStyle headCellStyle = new CellStyle();
headCellStyle.setFont(tableStyle.getTableHeadFont());
headCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor());
CellStyle contentCellStyle = new CellStyle();
contentCellStyle.setFont(tableStyle.getTableContentFont());
contentCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor());
table.getCustomWriteHandlerList().add(new RowCellStyleStrategy(headCellStyle, contentCellStyle));
}
}
public SheetHolder getParentSheet() {
return parentSheet;
}
public void setParentSheet(SheetHolder parentSheet) {
this.parentSheet = parentSheet;
}
public Integer getTableNo() {
return tableNo;
}
public void setTableNo(Integer tableNo) {
this.tableNo = tableNo;
}
public Table getTableParam() {
return tableParam;
}
public void setTableParam(Table tableParam) {
this.tableParam = tableParam;
}
}

325
src/main/java/com/alibaba/excel/metadata/holder/read/WorkbookHolder.java

@ -1,325 +0,0 @@
package com.alibaba.excel.metadata.holder.read;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.cache.ReadCache;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKey;
import com.alibaba.excel.converters.DefaultConverterLoader;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.holder.write.AbstractWriteConfiguration;
import com.alibaba.excel.read.listener.ModelBuildEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.DefaultWriteHandlerLoader;
import com.alibaba.excel.write.handler.WriteHandler;
/**
* Workbook holder
*
* @author zhuangjiaju
*/
public class WorkbookHolder extends AbstractWriteConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(WorkbookHolder.class);
/***
* poi Workbook
*/
private Workbook workbook;
/**
* prevent duplicate creation of sheet objects
*/
private Map<Integer, SheetHolder> hasBeenInitializedSheet;
/**
* current param
*/
private com.alibaba.excel.metadata.Workbook workbookParam;
/**
* Final output stream
*/
private OutputStream outputStream;
/**
* <li>write: Template input stream
* <li>read: Read InputStream
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
private InputStream inputStream;
/**
* <li>write: Template file
* <li>read: Read file
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
private File file;
/**
* Default true
*/
private Boolean autoCloseStream;
/**
* Excel type
*/
private ExcelTypeEnum excelType;
/**
* This object can be read in the Listener {@link AnalysisEventListener#invoke(Object, AnalysisContext)}
* {@link AnalysisContext#getCustom()}
*
*/
private Object readCustomObject;
/**
* A cache that stores temp data to save memory.Default use {@link com.alibaba.excel.cache.Ehcache}
*/
private ReadCache readCache;
/**
* true if date uses 1904 windowing, or false if using 1900 date windowing.
*
* @return
*/
private Boolean use1904windowing;
/**
* Mmandatory use 'inputStream'
*/
private Boolean mandatoryUseInputStream;
/**
* Temporary files when reading excel
*/
private File readTempFile;
/**
* The default is all excel objects.if true , you can use {@link com.alibaba.excel.annotation.ExcelIgnore} ignore a
* field. 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
private com.alibaba.excel.event.WriteHandler writeHandler;
public static WorkbookHolder buildWriteWorkbookHolder(com.alibaba.excel.metadata.Workbook workbook) {
WorkbookHolder workbookHolder = buildBaseWorkbookHolder(workbook);
workbookHolder.setNewInitialization(Boolean.TRUE);
if (workbook.getNeedHead() == null) {
workbookHolder.setNeedHead(Boolean.TRUE);
} else {
workbookHolder.setNeedHead(workbook.getNeedHead());
}
if (workbook.getWriteRelativeHeadRowIndex() == null) {
workbookHolder.setWriteRelativeHeadRowIndex(0);
} else {
workbookHolder.setWriteRelativeHeadRowIndex(workbook.getWriteRelativeHeadRowIndex());
}
List<WriteHandler> handlerList = new ArrayList<WriteHandler>();
if (workbook.getCustomWriteHandlerList() != null && !workbook.getCustomWriteHandlerList().isEmpty()) {
handlerList.addAll(workbook.getCustomWriteHandlerList());
}
handlerList.addAll(DefaultWriteHandlerLoader.loadDefaultHandler());
workbookHolder.setWriteHandlerMap(workbookHolder.sortAndClearUpHandler(handlerList, null));
Map<Class, Converter> converterMap = DefaultConverterLoader.loadDefaultWriteConverter();
if (workbook.getCustomConverterList() != null && !workbook.getCustomConverterList().isEmpty()) {
for (Converter converter : workbook.getCustomConverterList()) {
converterMap.put(converter.getClass(), converter);
}
}
workbookHolder.setWriteConverterMap(converterMap);
workbookHolder.setHasBeenInitializedSheet(new HashMap<Integer, SheetHolder>());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Wookbook writeHandlerMap:{}", workbookHolder.getWriteHandlerMap());
}
return workbookHolder;
}
public static WorkbookHolder buildReadWorkbookHolder(com.alibaba.excel.metadata.Workbook workbook) {
WorkbookHolder workbookHolder = buildBaseWorkbookHolder(workbook);
if (workbook.getFile() == null && workbookHolder.getInputStream() == null) {
throw new ExcelAnalysisException("Read excel 'file' and 'inputStream' cannot be empty at the same time!");
}
workbookHolder.setReadCustomObject(workbook.getReadCustomObject());
workbookHolder.setReadHeadRowNumber(workbook.getReadHeadRowNumber());
workbookHolder.setReadCache(workbook.getReadCache());
Map<ConverterKey, Converter> converterMap = DefaultConverterLoader.loadDefaultReadConverter();
if (workbook.getCustomConverterList() != null && !workbook.getCustomConverterList().isEmpty()) {
for (Converter converter : workbook.getCustomConverterList()) {
converterMap.put(ConverterKey.buildConverterKey(converter), converter);
}
}
workbookHolder.setReadConverterMap(converterMap);
List<ReadListener> readListenerList = new ArrayList<ReadListener>();
readListenerList.add(new ModelBuildEventListener());
if (workbook.getCustomReadListenerList() != null && !workbook.getCustomReadListenerList().isEmpty()) {
readListenerList.addAll(workbook.getCustomReadListenerList());
}
workbookHolder.setReadListenerList(readListenerList);
return workbookHolder;
}
private static WorkbookHolder buildBaseWorkbookHolder(com.alibaba.excel.metadata.Workbook workbook) {
WorkbookHolder workbookHolder = new WorkbookHolder();
workbookHolder.setUse1904windowing(workbook.getUse1904windowing());
workbookHolder.setWorkbookParam(workbook);
workbookHolder.setInputStream(workbook.getInputStream());
workbookHolder.setFile(workbook.getFile());
workbookHolder.setExcelType(workbook.getExcelType());
workbookHolder.setHead(workbook.getHead());
workbookHolder.setClazz(workbook.getClazz());
if (workbook.getConvertAllFiled() == null) {
workbookHolder.setConvertAllFiled(Boolean.TRUE);
} else {
workbookHolder.setConvertAllFiled(workbook.getConvertAllFiled());
}
if (workbook.getAutoCloseStream() == null) {
workbookHolder.setAutoCloseStream(Boolean.TRUE);
} else {
workbookHolder.setAutoCloseStream(workbook.getAutoCloseStream());
}
if (workbook.getAutoTrim() == null) {
workbookHolder.setAutoTrim(Boolean.TRUE);
} else {
workbookHolder.setAutoTrim(workbook.getNeedHead());
}
return workbookHolder;
}
public Workbook getWorkbook() {
return workbook;
}
public void setWorkbook(Workbook workbook) {
this.workbook = workbook;
}
public Map<Integer, SheetHolder> getHasBeenInitializedSheet() {
return hasBeenInitializedSheet;
}
public void setHasBeenInitializedSheet(Map<Integer, SheetHolder> hasBeenInitializedSheet) {
this.hasBeenInitializedSheet = hasBeenInitializedSheet;
}
public com.alibaba.excel.metadata.Workbook getWorkbookParam() {
return workbookParam;
}
public void setWorkbookParam(com.alibaba.excel.metadata.Workbook workbookParam) {
this.workbookParam = workbookParam;
}
public OutputStream getOutputStream() {
return outputStream;
}
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public com.alibaba.excel.event.WriteHandler getWriteHandler() {
return writeHandler;
}
public void setWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) {
this.writeHandler = writeHandler;
}
public Boolean getAutoCloseStream() {
return autoCloseStream;
}
public void setAutoCloseStream(Boolean autoCloseStream) {
this.autoCloseStream = autoCloseStream;
}
public Boolean getConvertAllFiled() {
return convertAllFiled;
}
public void setConvertAllFiled(Boolean convertAllFiled) {
this.convertAllFiled = convertAllFiled;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public ExcelTypeEnum getExcelType() {
return excelType;
}
public void setExcelType(ExcelTypeEnum excelType) {
this.excelType = excelType;
}
public Object getReadCustomObject() {
return readCustomObject;
}
public void setReadCustomObject(Object readCustomObject) {
this.readCustomObject = readCustomObject;
}
public ReadCache getReadCache() {
return readCache;
}
public void setReadCache(ReadCache readCache) {
this.readCache = readCache;
}
public Boolean getUse1904windowing() {
return use1904windowing;
}
public void setUse1904windowing(Boolean use1904windowing) {
this.use1904windowing = use1904windowing;
}
public Boolean getMandatoryUseInputStream() {
return mandatoryUseInputStream;
}
public void setMandatoryUseInputStream(Boolean mandatoryUseInputStream) {
this.mandatoryUseInputStream = mandatoryUseInputStream;
}
public File getReadTempFile() {
return readTempFile;
}
public void setReadTempFile(File readTempFile) {
this.readTempFile = readTempFile;
}
}

234
src/main/java/com/alibaba/excel/metadata/holder/write/SheetHolder.java

@ -1,234 +0,0 @@
package com.alibaba.excel.metadata.holder.write;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKey;
import com.alibaba.excel.metadata.CellStyle;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.metadata.property.ExcelHeadProperty;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.style.RowCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractHeadColumnWidthStyleStrategy;
/**
* sheet holder
*
* @author zhuangjiaju
*/
public class SheetHolder extends AbstractWriteConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(SheetHolder.class);
/***
* poi sheet
*/
private Sheet sheet;
/***
* sheetNo
*/
private Integer sheetNo;
/***
* sheetName
*/
private String sheetName;
/***
* poi sheet
*/
private WorkbookHolder parentWorkBook;
/***
* has been initialized table
*/
private Map<Integer, TableHolder> hasBeenInitializedTable;
/**
* current param
*/
private com.alibaba.excel.metadata.Sheet sheetParam;
public static SheetHolder buildWriteWorkSheetHolder(com.alibaba.excel.metadata.Sheet sheet,
WorkbookHolder workbookHolder) {
SheetHolder sheetHolder = buildBaseSheetHolder(sheet, workbookHolder);
sheetHolder.setNewInitialization(Boolean.TRUE);
if (sheet.getNeedHead() == null) {
sheetHolder.setNeedHead(workbookHolder.needHead());
} else {
sheetHolder.setNeedHead(sheet.getNeedHead());
}
if (sheet.getWriteRelativeHeadRowIndex() == null) {
sheetHolder.setWriteRelativeHeadRowIndex(workbookHolder.writeRelativeHeadRowIndex());
} else {
sheetHolder.setWriteRelativeHeadRowIndex(sheet.getWriteRelativeHeadRowIndex());
}
// Compatible with old code
compatibleOldCode(sheet);
List<WriteHandler> handlerList = new ArrayList<WriteHandler>();
if (sheet.getCustomWriteHandlerList() != null && !sheet.getCustomWriteHandlerList().isEmpty()) {
handlerList.addAll(sheet.getCustomWriteHandlerList());
}
// Initialization Annotation
sheetHolder.initAnnotationConfig(handlerList);
sheetHolder
.setWriteHandlerMap(sheetHolder.sortAndClearUpHandler(handlerList, workbookHolder.getWriteHandlerMap()));
Map<Class, Converter> converterMap = new HashMap<Class, Converter>(workbookHolder.getWriteConverterMap());
if (sheet.getCustomConverterList() != null && !sheet.getCustomConverterList().isEmpty()) {
for (Converter converter : sheet.getCustomConverterList()) {
converterMap.put(converter.getClass(), converter);
}
}
sheetHolder.setWriteConverterMap(converterMap);
sheetHolder.setHasBeenInitializedTable(new HashMap<Integer, TableHolder>());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sheet writeHandlerMap:{}", sheetHolder.getWriteHandlerMap());
}
return sheetHolder;
}
public static SheetHolder buildReadWorkSheetHolder(com.alibaba.excel.metadata.Sheet sheet,
WorkbookHolder workbookHolder) {
SheetHolder sheetHolder = buildBaseSheetHolder(sheet, workbookHolder);
if (sheet.getReadHeadRowNumber() == null) {
if (workbookHolder.getReadHeadRowNumber() == null) {
sheetHolder.setReadHeadRowNumber(sheetHolder.getExcelHeadProperty().getHeadRowNumber());
} else {
sheetHolder.setReadHeadRowNumber(workbookHolder.getReadHeadRowNumber());
}
} else {
sheetHolder.setReadHeadRowNumber(sheet.getReadHeadRowNumber());
}
Map<ConverterKey, Converter> converterMap =
new HashMap<ConverterKey, Converter>(workbookHolder.getReadConverterMap());
if (sheet.getCustomConverterList() != null && !sheet.getCustomConverterList().isEmpty()) {
for (Converter converter : sheet.getCustomConverterList()) {
converterMap.put(ConverterKey.buildConverterKey(converter), converter);
}
}
sheetHolder.setReadConverterMap(converterMap);
List<ReadListener> readListenerList = new ArrayList<ReadListener>();
if (sheet.getCustomReadListenerList() != null && !sheet.getCustomReadListenerList().isEmpty()) {
readListenerList.addAll(sheet.getCustomReadListenerList());
}
sheetHolder.setReadListenerList(readListenerList);
return sheetHolder;
}
private static SheetHolder buildBaseSheetHolder(com.alibaba.excel.metadata.Sheet sheet,
WorkbookHolder workbookHolder) {
SheetHolder sheetHolder = new SheetHolder();
sheetHolder.setSheetParam(sheet);
sheetHolder.setParentWorkBook(workbookHolder);
boolean noHead = (sheet.getHead() == null || sheet.getHead().isEmpty()) && sheet.getClazz() == null;
if (noHead) {
// Use parent
sheetHolder.setHead(workbookHolder.getHead());
sheetHolder.setClazz(workbookHolder.getClazz());
} else {
sheetHolder.setHead(sheet.getHead());
sheetHolder.setClazz(sheet.getClazz());
}
if (sheet.getAutoTrim() == null) {
workbookHolder.setAutoTrim(workbookHolder.getAutoTrim());
} else {
workbookHolder.setAutoTrim(sheet.getNeedHead());
}
// Initialization property
sheetHolder
.setExcelHeadProperty(new ExcelHeadProperty(sheetHolder.getClazz(), sheetHolder.getHead(), workbookHolder));
return sheetHolder;
}
/**
* Compatible with old code
*/
@Deprecated
private static void compatibleOldCode(com.alibaba.excel.metadata.Sheet sheet) {
if (sheet.getColumnWidthMap() != null && !sheet.getColumnWidthMap().isEmpty()) {
final Map<Integer, Integer> columnWidthMap = sheet.getColumnWidthMap();
if (sheet.getCustomWriteHandlerList() == null) {
sheet.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
sheet.getCustomWriteHandlerList().add(new AbstractHeadColumnWidthStyleStrategy() {
@Override
protected Integer columnWidth(Head head) {
if (columnWidthMap.containsKey(head.getColumnIndex())) {
columnWidthMap.get(head.getColumnIndex());
}
return 20;
}
});
}
if (sheet.getTableStyle() != null) {
final TableStyle tableStyle = sheet.getTableStyle();
if (sheet.getCustomWriteHandlerList() == null) {
sheet.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
CellStyle headCellStyle = new CellStyle();
headCellStyle.setFont(tableStyle.getTableHeadFont());
headCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor());
CellStyle contentCellStyle = new CellStyle();
contentCellStyle.setFont(tableStyle.getTableContentFont());
contentCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor());
sheet.getCustomWriteHandlerList().add(new RowCellStyleStrategy(headCellStyle, contentCellStyle));
}
}
public Sheet getSheet() {
return sheet;
}
public void setSheet(Sheet sheet) {
this.sheet = sheet;
}
public Integer getSheetNo() {
return sheetNo;
}
public void setSheetNo(Integer sheetNo) {
this.sheetNo = sheetNo;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public WorkbookHolder getParentWorkBook() {
return parentWorkBook;
}
public void setParentWorkBook(WorkbookHolder parentWorkBook) {
this.parentWorkBook = parentWorkBook;
}
public Map<Integer, TableHolder> getHasBeenInitializedTable() {
return hasBeenInitializedTable;
}
public void setHasBeenInitializedTable(Map<Integer, TableHolder> hasBeenInitializedTable) {
this.hasBeenInitializedTable = hasBeenInitializedTable;
}
public com.alibaba.excel.metadata.Sheet getSheetParam() {
return sheetParam;
}
public void setSheetParam(com.alibaba.excel.metadata.Sheet sheetParam) {
this.sheetParam = sheetParam;
}
}

235
src/main/java/com/alibaba/excel/read/builder/ExcelReaderBuilder.java

@ -1,6 +1,19 @@
package com.alibaba.excel.read.builder; package com.alibaba.excel.read.builder;
import com.alibaba.excel.write.metadata.Workbook; import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.cache.ReadCache;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.support.ExcelTypeEnum;
/** /**
* Build ExcelWriter * Build ExcelWriter
@ -11,11 +24,227 @@ public class ExcelReaderBuilder {
/** /**
* Workbook * Workbook
*/ */
private Workbook workbook; private ReadWorkbook readWorkbook;
public ExcelReaderBuilder() { public ExcelReaderBuilder() {
this.workbook = new Workbook(); this.readWorkbook = new ReadWorkbook();
}
public ExcelReaderBuilder excelType(ExcelTypeEnum excelType) {
readWorkbook.setExcelType(excelType);
return this;
}
/**
* Read InputStream
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
public ExcelReaderBuilder file(InputStream inputStream) {
readWorkbook.setInputStream(inputStream);
return this;
}
/**
* Read file
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
public ExcelReaderBuilder file(File file) {
readWorkbook.setFile(file);
return this;
}
/**
* Read file
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
public ExcelReaderBuilder file(String pathName) {
return file(new File(pathName));
}
/**
* Read file
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
public ExcelReaderBuilder file(URI uri) {
return file(new File(uri));
} }
/**
* Mandatory use 'inputStream' .Default is false.
* <li>if false,Will transfer 'inputStream' to temporary files to improve efficiency
*/
public ExcelReaderBuilder mandatoryUseInputStream(Boolean mandatoryUseInputStream) {
readWorkbook.setMandatoryUseInputStream(mandatoryUseInputStream);
return this;
}
/**
* Default true
*
* @param autoCloseStream
* @return
*/
public ExcelReaderBuilder autoCloseStream(Boolean autoCloseStream) {
readWorkbook.setAutoCloseStream(autoCloseStream);
return this;
}
/**
* This object can be read in the Listener {@link AnalysisEventListener#invoke(Object, AnalysisContext)}
* {@link AnalysisContext#getCustom()}
*
* @param customObject
* @return
*/
public ExcelReaderBuilder customObject(Object customObject) {
readWorkbook.setCustomObject(customObject);
return this;
}
/**
* A cache that stores temp data to save memory.Default use {@link com.alibaba.excel.cache.Ehcache}
*
* @param readCache
* @return
*/
public ExcelReaderBuilder readCache(ReadCache readCache) {
readWorkbook.setReadCache(readCache);
return this;
}
/**
* The default is all excel objects.if true , you can use {@link com.alibaba.excel.annotation.ExcelIgnore} ignore a
* 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.
*/
@Deprecated
public ExcelReaderBuilder convertAllFiled(Boolean convertAllFiled) {
readWorkbook.setConvertAllFiled(convertAllFiled);
return this;
}
/**
* Count the number of added heads when read sheet.
*
* <li>0 - This Sheet has no head ,since the first row are the data
* <li>1 - This Sheet has one row head , this is the default
* <li>2 - This Sheet has two row head ,since the third row is the data
*
* @param headRowNumber
* @return
*/
public ExcelReaderBuilder headRowNumber(Integer headRowNumber) {
readWorkbook.setHeadRowNumber(headRowNumber);
return this;
}
/**
* You can only choose one of the {@link ExcelReaderBuilder#head(List)} and {@link ExcelReaderBuilder#head(Class)}
*
* @param head
* @return
*/
public ExcelReaderBuilder head(List<List<String>> head) {
readWorkbook.setHead(head);
return this;
}
/**
* You can only choose one of the {@link ExcelReaderBuilder#head(List)} and {@link ExcelReaderBuilder#head(Class)}
*
* @param clazz
* @return
*/
public ExcelReaderBuilder head(Class clazz) {
readWorkbook.setClazz(clazz);
return this;
}
/**
* Custom type conversions override the default.
*
* @param converter
* @return
*/
public ExcelReaderBuilder registerConverter(Converter converter) {
if (readWorkbook.getCustomConverterList() == null) {
readWorkbook.setCustomConverterList(new ArrayList<Converter>());
}
readWorkbook.getCustomConverterList().add(converter);
return this;
}
/**
* Custom type listener run after default
*
* @param readListener
* @return
*/
public ExcelReaderBuilder registerReadListener(ReadListener readListener) {
if (readWorkbook.getCustomReadListenerList() == null) {
readWorkbook.setCustomReadListenerList(new ArrayList<ReadListener>());
}
readWorkbook.getCustomReadListenerList().add(readListener);
return this;
}
/**
* true if date uses 1904 windowing, or false if using 1900 date windowing.
*
* default is false
*
* @param use1904windowing
* @return
*/
public ExcelReaderBuilder use1904windowing(Boolean use1904windowing) {
readWorkbook.setUse1904windowing(use1904windowing);
return this;
}
/**
* Automatic trim includes sheet name and content
*
* @param autoTrim
* @return
*/
public ExcelReaderBuilder autoTrim(Boolean autoTrim) {
readWorkbook.setAutoTrim(autoTrim);
return this;
}
public ExcelReader build() {
return new ExcelReader(readWorkbook);
}
public ExcelReaderSheetBuilder sheet() {
return sheet(null, null);
}
public ExcelReaderSheetBuilder sheet(Integer sheetNo) {
return sheet(sheetNo, null);
}
public ExcelReaderSheetBuilder sheet(String sheetName) {
return sheet(null, sheetName);
}
public ExcelReaderSheetBuilder sheet(Integer sheetNo, String sheetName) {
ExcelReaderSheetBuilder excelReaderSheetBuilder = new ExcelReaderSheetBuilder(build());
if (sheetNo != null) {
excelReaderSheetBuilder.sheetNo(sheetNo);
}
if (sheetName != null) {
excelReaderSheetBuilder.sheetName(sheetName);
}
return excelReaderSheetBuilder;
}
} }

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

@ -0,0 +1,189 @@
package com.alibaba.excel.read.builder;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.event.SyncReadListener;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadSheet;
/**
* Build sheet
*
* @author zhuangjiaju
*/
public class ExcelReaderSheetBuilder {
private ExcelReader excelReader;
/**
* Sheet
*/
private ReadSheet readSheet;
public ExcelReaderSheetBuilder() {
this.readSheet = new ReadSheet();
}
public ExcelReaderSheetBuilder(ExcelReader excelReader) {
this.readSheet = new ReadSheet();
this.excelReader = excelReader;
}
/**
* Starting from 0
*
* @param sheetNo
* @return
*/
public ExcelReaderSheetBuilder sheetNo(Integer sheetNo) {
readSheet.setSheetNo(sheetNo);
return this;
}
/**
* sheet name
*
* @param sheetName
* @return
*/
public ExcelReaderSheetBuilder sheetName(String sheetName) {
readSheet.setSheetName(sheetName);
return this;
}
/**
* Count the number of added heads when read sheet.
*
* <li>0 - This Sheet has no head ,since the first row are the data
* <li>1 - This Sheet has one row head , this is the default
* <li>2 - This Sheet has two row head ,since the third row is the data
*
* @param headRowNumber
* @return
*/
public ExcelReaderSheetBuilder headRowNumber(Integer headRowNumber) {
readSheet.setHeadRowNumber(headRowNumber);
return this;
}
/**
* You can only choose one of the {@link ExcelReaderBuilder#head(List)} and {@link ExcelReaderBuilder#head(Class)}
*
* @param head
* @return
*/
public ExcelReaderSheetBuilder head(List<List<String>> head) {
readSheet.setHead(head);
return this;
}
/**
* You can only choose one of the {@link ExcelReaderBuilder#head(List)} and {@link ExcelReaderBuilder#head(Class)}
*
* @param clazz
* @return
*/
public ExcelReaderSheetBuilder head(Class clazz) {
readSheet.setClazz(clazz);
return this;
}
/**
* Custom type conversions override the default.
*
* @param converter
* @return
*/
public ExcelReaderSheetBuilder registerConverter(Converter converter) {
if (readSheet.getCustomConverterList() == null) {
readSheet.setCustomConverterList(new ArrayList<Converter>());
}
readSheet.getCustomConverterList().add(converter);
return this;
}
/**
* Custom type listener run after default
*
* @param readListener
* @return
*/
public ExcelReaderSheetBuilder registerReadListener(ReadListener readListener) {
if (readSheet.getCustomReadListenerList() == null) {
readSheet.setCustomReadListenerList(new ArrayList<ReadListener>());
}
readSheet.getCustomReadListenerList().add(readListener);
return this;
}
/**
* true if date uses 1904 windowing, or false if using 1900 date windowing.
*
* default is false
*
* @param use1904windowing
* @return
*/
public ExcelReaderSheetBuilder use1904windowing(Boolean use1904windowing) {
readSheet.setUse1904windowing(use1904windowing);
return this;
}
/**
* Automatic trim includes sheet name and content
*
* @param autoTrim
* @return
*/
public ExcelReaderSheetBuilder autoTrim(Boolean autoTrim) {
readSheet.setAutoTrim(autoTrim);
return this;
}
public ReadSheet build() {
return readSheet;
}
/**
* Sax read
*
* @return
*/
public ExcelReaderSheetBuilder doRead() {
if (excelReader == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.read().sheet()' to call this method");
}
excelReader.read(build());
return new ExcelReaderSheetBuilder(excelReader);
}
/**
* Sax read
*
* @return
*/
public void finish() {
if (excelReader == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.read().sheet()' to call this method");
}
excelReader.finish();
}
/**
* Synchronous reads return results
*
* @return
*/
public List<Object> doReadSync() {
if (excelReader == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.read().sheet()' to call this method");
}
SyncReadListener syncReadListener = new SyncReadListener();
registerReadListener(syncReadListener);
excelReader.read(build());
return syncReadListener.getList();
}
}

38
src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java

@ -10,13 +10,13 @@ import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKey; import com.alibaba.excel.converters.ConverterKey;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.enums.HeadKindEnum; import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.event.AbstractIgnoreExceptionReadListener;
import com.alibaba.excel.exception.ExcelDataConvertException; import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.read.metadata.read.ReadConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.metadata.property.ExcelHeadProperty; import com.alibaba.excel.read.metadata.holder.ReadHolder;
import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty;
import net.sf.cglib.beans.BeanMap; import net.sf.cglib.beans.BeanMap;
@ -25,40 +25,38 @@ import net.sf.cglib.beans.BeanMap;
* *
* @author jipengfei * @author jipengfei
*/ */
public class ModelBuildEventListener extends AnalysisEventListener<List<CellData>> { public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener<List<CellData>> {
@Override
public void onException(Exception exception, AnalysisContext context) throws Exception {}
@Override @Override
public void invoke(List<CellData> data, AnalysisContext context) { public void invoke(List<CellData> data, AnalysisContext context) {
ReadConfiguration readConfiguration = context.currentConfiguration(); ReadHolder currentReadHolder = context.currentReadHolder();
if (HeadKindEnum.CLASS.equals(context.currentSheetHolder().getExcelHeadProperty().getHeadKind())) { if (HeadKindEnum.CLASS.equals(currentReadHolder.excelReadHeadProperty().getHeadKind())) {
context.setCurrentRowAnalysisResult(buildUserModel(data, readConfiguration)); context.readRowHolder().setCurrentRowAnalysisResult(buildUserModel(data, currentReadHolder));
return; return;
} }
context.setCurrentRowAnalysisResult(buildStringList(data, readConfiguration)); context.readRowHolder().setCurrentRowAnalysisResult(buildStringList(data, currentReadHolder));
} }
private Object buildStringList(List<CellData> data, ReadConfiguration readConfiguration) { private Object buildStringList(List<CellData> data, ReadHolder currentReadHolder) {
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<String>();
for (CellData cellData : data) { for (CellData cellData : data) {
list.add((String)convertValue(cellData, String.class, null, readConfiguration.readConverterMap())); list.add((String)convertValue(cellData, String.class, null, currentReadHolder.converterMap()));
} }
return list; return list;
} }
private Object buildUserModel(List<CellData> data, ReadConfiguration readConfiguration) { private Object buildUserModel(List<CellData> data, ReadHolder currentReadHolder) {
ExcelHeadProperty excelHeadProperty = readConfiguration.excelHeadProperty(); ExcelReadHeadProperty excelReadHeadProperty = currentReadHolder.excelReadHeadProperty();
Object resultModel; Object resultModel;
try { try {
resultModel = excelHeadProperty.getHeadClazz().newInstance(); resultModel = excelReadHeadProperty.getHeadClazz().newInstance();
} catch (Exception e) { } catch (Exception e) {
throw new ExcelDataConvertException("Can not instance class: " + excelHeadProperty.getHeadClazz().getName(), throw new ExcelDataConvertException(
e); "Can not instance class: " + excelReadHeadProperty.getHeadClazz().getName(), e);
} }
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
Map<Integer, Head> headMap = excelHeadProperty.getHeadMap(); Map<Integer, Head> headMap = excelReadHeadProperty.getHeadMap();
Map<Integer, ExcelContentProperty> contentPropertyMap = excelHeadProperty.getContentPropertyMap(); Map<Integer, ExcelContentProperty> contentPropertyMap = excelReadHeadProperty.getContentPropertyMap();
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) { for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
Integer index = entry.getKey(); Integer index = entry.getKey();
if (index >= data.size()) { if (index >= data.size()) {
@ -70,7 +68,7 @@ public class ModelBuildEventListener extends AnalysisEventListener<List<CellData
} }
ExcelContentProperty excelContentProperty = contentPropertyMap.get(index); ExcelContentProperty excelContentProperty = contentPropertyMap.get(index);
Object value = convertValue(cellData, excelContentProperty.getField().getClass(), excelContentProperty, Object value = convertValue(cellData, excelContentProperty.getField().getClass(), excelContentProperty,
readConfiguration.readConverterMap()); currentReadHolder.converterMap());
if (value != null) { if (value != null) {
map.put(excelContentProperty.getField().getName(), value); map.put(excelContentProperty.getField().getName(), value);
} }

2
src/main/java/com/alibaba/excel/read/listener/ReadListener.java

@ -11,7 +11,7 @@ import com.alibaba.excel.event.Listener;
public interface ReadListener<T> extends Listener { public interface ReadListener<T> extends Listener {
/** /**
* All listeners receive this method when any one Listener does an error report. If an exception is thrown here, the * All listeners receive this method when any one Listener does an error report. If an exception is thrown here, the
* * entire read will terminate. * entire read will terminate.
* *
* @param exception * @param exception
* @param context * @param context

11
src/main/java/com/alibaba/excel/read/metadata/ReadSheet.java

@ -15,6 +15,17 @@ public class ReadSheet extends ReadBasicParameter {
*/ */
private String sheetName; private String sheetName;
public ReadSheet() {}
public ReadSheet(Integer sheetNo) {
this.sheetNo = sheetNo;
}
public ReadSheet(Integer sheetNo, String sheetName) {
this.sheetNo = sheetNo;
this.sheetName = sheetName;
}
public Integer getSheetNo() { public Integer getSheetNo() {
return sheetNo; return sheetNo;
} }

34
src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java

@ -3,6 +3,9 @@ package com.alibaba.excel.read.metadata;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import com.alibaba.excel.cache.ReadCache;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
/** /**
@ -27,14 +30,25 @@ public class ReadWorkbook extends ReadBasicParameter {
* If 'inputStream' and 'file' all not empty,file first * If 'inputStream' and 'file' all not empty,file first
*/ */
private File file; private File file;
/**
* Mandatory use 'inputStream' .Default is false.
* <li>if false,Will transfer 'inputStream' to temporary files to improve efficiency
*/
private Boolean mandatoryUseInputStream;
/** /**
* Default true * Default true
*/ */
private Boolean autoCloseStream; private Boolean autoCloseStream;
/** /**
* Mandatory use 'inputStream' .Default is false * This object can be read in the Listener {@link AnalysisEventListener#invoke(Object, AnalysisContext)}
* {@link AnalysisContext#getCustom()}
*
*/
private Object customObject;
/**
* A cache that stores temp data to save memory.Default use {@link com.alibaba.excel.cache.Ehcache}
*/ */
private Boolean mandatoryUseInputStream; private ReadCache readCache;
/** /**
* The default is all excel objects.Default is true. * 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 true , you can use {@link com.alibaba.excel.annotation.ExcelIgnore} ignore a field.
@ -77,6 +91,14 @@ public class ReadWorkbook extends ReadBasicParameter {
this.autoCloseStream = autoCloseStream; this.autoCloseStream = autoCloseStream;
} }
public Object getCustomObject() {
return customObject;
}
public void setCustomObject(Object customObject) {
this.customObject = customObject;
}
public Boolean getMandatoryUseInputStream() { public Boolean getMandatoryUseInputStream() {
return mandatoryUseInputStream; return mandatoryUseInputStream;
} }
@ -85,6 +107,14 @@ public class ReadWorkbook extends ReadBasicParameter {
this.mandatoryUseInputStream = mandatoryUseInputStream; this.mandatoryUseInputStream = mandatoryUseInputStream;
} }
public ReadCache getReadCache() {
return readCache;
}
public void setReadCache(ReadCache readCache) {
this.readCache = readCache;
}
public Boolean getConvertAllFiled() { public Boolean getConvertAllFiled() {
return convertAllFiled; return convertAllFiled;
} }

31
src/main/java/com/alibaba/excel/read/metadata/holder/AbstractWriteConfiguration.java → src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java

@ -9,6 +9,7 @@ import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKey; import com.alibaba.excel.converters.ConverterKey;
import com.alibaba.excel.enums.HeadKindEnum; import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException; import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelDataConvertException; import com.alibaba.excel.exception.ExcelDataConvertException;
@ -16,6 +17,7 @@ import com.alibaba.excel.metadata.AbstractHolder;
import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.read.listener.ModelBuildEventListener;
import com.alibaba.excel.read.listener.ReadListener; import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.listener.ReadListenerRegistryCenter; import com.alibaba.excel.read.listener.ReadListenerRegistryCenter;
import com.alibaba.excel.read.listener.event.AnalysisFinishEvent; import com.alibaba.excel.read.listener.event.AnalysisFinishEvent;
@ -77,6 +79,10 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
} else { } else {
this.readListenerList = new ArrayList<ReadListener>(parentAbstractReadHolder.getReadListenerList()); this.readListenerList = new ArrayList<ReadListener>(parentAbstractReadHolder.getReadListenerList());
} }
if (HolderEnum.WORKBOOK.equals(holderType())
&& HeadKindEnum.CLASS.equals(excelReadHeadProperty.getHeadKind())) {
readListenerList.add(new ModelBuildEventListener());
}
if (readBasicParameter.getCustomReadListenerList() != null if (readBasicParameter.getCustomReadListenerList() != null
&& !readBasicParameter.getCustomReadListenerList().isEmpty()) { && !readBasicParameter.getCustomReadListenerList().isEmpty()) {
this.readListenerList.addAll(readBasicParameter.getCustomReadListenerList()); this.readListenerList.addAll(readBasicParameter.getCustomReadListenerList());
@ -103,11 +109,12 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
@Override @Override
public void notifyEndOneRow(AnalysisFinishEvent event, AnalysisContext analysisContext) { public void notifyEndOneRow(AnalysisFinishEvent event, AnalysisContext analysisContext) {
List<CellData> cellDataList = (List<CellData>)event.getAnalysisResult(); List<CellData> cellDataList = (List<CellData>)event.getAnalysisResult();
if (analysisContext.currentRowHolder().getRow().getRowNum() > analysisContext.currentSheetHolder() ReadRowHolder readRowHolder = analysisContext.readRowHolder();
.getReadHeadRowNumber()) {
if (readRowHolder.getRowIndex() >= analysisContext.readSheetHolder().getHeadRowNumber()) {
for (ReadListener readListener : readListenerList) { for (ReadListener readListener : readListenerList) {
try { try {
readListener.invoke(analysisContext.currentRowAnalysisResult(), analysisContext); readListener.invoke(readRowHolder.getCurrentRowAnalysisResult(), analysisContext);
} catch (Exception e) { } catch (Exception e) {
for (ReadListener readListenerException : readListenerList) { for (ReadListener readListenerException : readListenerList) {
try { try {
@ -118,9 +125,10 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
} }
} }
} }
return;
} }
// Now is header // Now is header
if (analysisContext.currentRowNum().equals(analysisContext.currentSheetHolder().getReadHeadRowNumber())) { if (analysisContext.readSheetHolder().getHeadRowNumber().equals(readRowHolder.getRowIndex() + 1)) {
buildHead(analysisContext, cellDataList); buildHead(analysisContext, cellDataList);
} }
} }
@ -133,11 +141,11 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
} }
private void buildHead(AnalysisContext analysisContext, List<CellData> cellDataList) { private void buildHead(AnalysisContext analysisContext, List<CellData> cellDataList) {
if (!HeadKindEnum.CLASS.equals(analysisContext.currentConfiguration().excelReadHeadProperty().getHeadKind())) { if (!HeadKindEnum.CLASS.equals(analysisContext.currentReadHolder().excelReadHeadProperty().getHeadKind())) {
return; return;
} }
List<String> dataList = (List<String>)buildStringList(cellDataList, analysisContext.currentConfiguration()); List<String> dataList = (List<String>)buildStringList(cellDataList, analysisContext.currentReadHolder());
ExcelReadHeadProperty excelHeadPropertyData = analysisContext.currentConfiguration().excelReadHeadProperty(); ExcelReadHeadProperty excelHeadPropertyData = analysisContext.readSheetHolder().excelReadHeadProperty();
Map<Integer, Head> headMapData = excelHeadPropertyData.getHeadMap(); Map<Integer, Head> headMapData = excelHeadPropertyData.getHeadMap();
Map<Integer, ExcelContentProperty> contentPropertyMapData = excelHeadPropertyData.getContentPropertyMap(); Map<Integer, ExcelContentProperty> contentPropertyMapData = excelHeadPropertyData.getContentPropertyMap();
Map<Integer, Head> tmpHeadMap = new HashMap<Integer, Head>(headMapData.size() * 4 / 3 + 1); Map<Integer, Head> tmpHeadMap = new HashMap<Integer, Head>(headMapData.size() * 4 / 3 + 1);
@ -156,7 +164,7 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
if (StringUtils.isEmpty(headString)) { if (StringUtils.isEmpty(headString)) {
continue; continue;
} }
if (analysisContext.currentSheetHolder().getAutoTrim()) { if (analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
headString = headString.trim(); headString = headString.trim();
} }
if (headName.equals(headString)) { if (headName.equals(headString)) {
@ -171,12 +179,11 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
excelHeadPropertyData.setContentPropertyMap(tmpContentPropertyMap); excelHeadPropertyData.setContentPropertyMap(tmpContentPropertyMap);
} }
private Object buildStringList(List<CellData> data, private Object buildStringList(List<CellData> data, ReadHolder readHolder) {
com.alibaba.excel.read.metadata.read.ReadConfiguration readConfiguration) {
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<String>();
for (CellData cellData : data) { for (CellData cellData : data) {
Converter converter = readConfiguration.readConverterMap() Converter converter =
.get(ConverterKey.buildConverterKey(String.class, cellData.getType())); readHolder.converterMap().get(ConverterKey.buildConverterKey(String.class, cellData.getType()));
if (converter == null) { if (converter == null) {
throw new ExcelDataConvertException( throw new ExcelDataConvertException(
"Converter not found, convert " + cellData.getType() + " to String"); "Converter not found, convert " + cellData.getType() + " to String");

27
src/main/java/com/alibaba/excel/read/metadata/holder/ReadRowHolder.java

@ -1,7 +1,5 @@
package com.alibaba.excel.read.metadata.holder; package com.alibaba.excel.read.metadata.holder;
import org.apache.poi.ss.usermodel.Row;
import com.alibaba.excel.enums.HolderEnum; import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.Holder; import com.alibaba.excel.metadata.Holder;
@ -12,11 +10,6 @@ import com.alibaba.excel.metadata.Holder;
* @author zhuangjiaju * @author zhuangjiaju
*/ */
public class ReadRowHolder implements Holder { public class ReadRowHolder implements Holder {
/***
* poi row
*/
private Row row;
/** /**
* Some global variables * Some global variables
*/ */
@ -26,17 +19,9 @@ public class ReadRowHolder implements Holder {
*/ */
private Object currentRowAnalysisResult; private Object currentRowAnalysisResult;
/** /**
* Data starting from the first row after the head is removed.Start form 1 * Returns row index of a row in the sheet that contains this cell.Start form 0.
*/ */
private int relativeRowIndex; private int rowIndex;
public Row getRow() {
return row;
}
public void setRow(Row row) {
this.row = row;
}
public GlobalConfiguration getGlobalConfiguration() { public GlobalConfiguration getGlobalConfiguration() {
return globalConfiguration; return globalConfiguration;
@ -54,12 +39,12 @@ public class ReadRowHolder implements Holder {
this.currentRowAnalysisResult = currentRowAnalysisResult; this.currentRowAnalysisResult = currentRowAnalysisResult;
} }
public int getRelativeRowIndex() { public int getRowIndex() {
return relativeRowIndex; return rowIndex;
} }
public void setRelativeRowIndex(int relativeRowIndex) { public void setRowIndex(int rowIndex) {
this.relativeRowIndex = relativeRowIndex; this.rowIndex = rowIndex;
} }
@Override @Override

85
src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java

@ -0,0 +1,85 @@
package com.alibaba.excel.read.metadata.holder;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.read.metadata.ReadSheet;
/**
* sheet holder
*
* @author zhuangjiaju
*/
public class ReadSheetHolder extends AbstractReadHolder {
/**
* current param
*/
private ReadSheet readSheet;
/***
* parent
*/
private ReadWorkbookHolder parentReadWorkbookHolder;
/***
* sheetNo
*/
private Integer sheetNo;
/***
* sheetName
*/
private String sheetName;
/**
* get total row , Data may be inaccurate
*/
@Deprecated
private Integer total;
public ReadSheetHolder(ReadSheet readSheet, ReadWorkbookHolder readWorkbookHolder) {
super(readSheet, null, readWorkbookHolder.getReadWorkbook().getConvertAllFiled());
this.readSheet = readSheet;
this.parentReadWorkbookHolder = readWorkbookHolder;
this.sheetNo = readSheet.getSheetNo();
}
public ReadSheet getReadSheet() {
return readSheet;
}
public void setReadSheet(ReadSheet readSheet) {
this.readSheet = readSheet;
}
public ReadWorkbookHolder getParentReadWorkbookHolder() {
return parentReadWorkbookHolder;
}
public void setParentReadWorkbookHolder(ReadWorkbookHolder parentReadWorkbookHolder) {
this.parentReadWorkbookHolder = parentReadWorkbookHolder;
}
public Integer getSheetNo() {
return sheetNo;
}
public void setSheetNo(Integer sheetNo) {
this.sheetNo = sheetNo;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
@Override
public HolderEnum holderType() {
return HolderEnum.SHEET;
}
}

185
src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java

@ -0,0 +1,185 @@
package com.alibaba.excel.read.metadata.holder;
import java.io.File;
import java.io.InputStream;
import com.alibaba.excel.cache.ReadCache;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.support.ExcelTypeEnum;
/**
* Workbook holder
*
* @author zhuangjiaju
*/
public class ReadWorkbookHolder extends AbstractReadHolder {
/**
* current param
*/
private ReadWorkbook readWorkbook;
/**
* Read InputStream
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
private InputStream inputStream;
/**
* Read file
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
private File file;
/**
* Mandatory use 'inputStream' .Default is false.
* <li>if false,Will transfer 'inputStream' to temporary files to improve efficiency
*/
private Boolean mandatoryUseInputStream;
/**
* Default true
*/
private Boolean autoCloseStream;
/**
* Excel type
*/
private ExcelTypeEnum excelType;
/**
* This object can be read in the Listener {@link AnalysisEventListener#invoke(Object, AnalysisContext)}
* {@link AnalysisContext#getCustom()}
*
*/
private Object customObject;
/**
* A cache that stores temp data to save memory.Default use {@link com.alibaba.excel.cache.Ehcache}
*/
private ReadCache readCache;
/**
* Temporary files when reading excel
*/
private File tempFile;
/**
* The default is all excel objects.if true , you can use {@link com.alibaba.excel.annotation.ExcelIgnore} ignore a
* field. 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;
public ReadWorkbookHolder(ReadWorkbook readWorkbook) {
super(readWorkbook, null, readWorkbook.getConvertAllFiled());
this.readWorkbook = readWorkbook;
if (file == null && inputStream == null) {
throw new ExcelAnalysisException("File and inputStream must be a non-null.");
}
this.inputStream = readWorkbook.getInputStream();
this.file = readWorkbook.getFile();
if (readWorkbook.getMandatoryUseInputStream() == null) {
this.mandatoryUseInputStream = Boolean.FALSE;
} else {
this.mandatoryUseInputStream = readWorkbook.getMandatoryUseInputStream();
}
if (readWorkbook.getAutoCloseStream() == null) {
this.autoCloseStream = Boolean.TRUE;
} else {
this.autoCloseStream = readWorkbook.getAutoCloseStream();
}
if (readWorkbook.getExcelType() == null) {
this.excelType = ExcelTypeEnum.valueOf(file, inputStream);
} else {
this.excelType = readWorkbook.getExcelType();
}
this.customObject = readWorkbook.getCustomObject();
this.readCache = readWorkbook.getReadCache();
}
public ReadWorkbook getReadWorkbook() {
return readWorkbook;
}
public void setReadWorkbook(ReadWorkbook readWorkbook) {
this.readWorkbook = readWorkbook;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public Boolean getAutoCloseStream() {
return autoCloseStream;
}
public void setAutoCloseStream(Boolean autoCloseStream) {
this.autoCloseStream = autoCloseStream;
}
public ExcelTypeEnum getExcelType() {
return excelType;
}
public void setExcelType(ExcelTypeEnum excelType) {
this.excelType = excelType;
}
public Object getCustomObject() {
return customObject;
}
public void setCustomObject(Object customObject) {
this.customObject = customObject;
}
public ReadCache getReadCache() {
return readCache;
}
public void setReadCache(ReadCache readCache) {
this.readCache = readCache;
}
public Boolean getMandatoryUseInputStream() {
return mandatoryUseInputStream;
}
public void setMandatoryUseInputStream(Boolean mandatoryUseInputStream) {
this.mandatoryUseInputStream = mandatoryUseInputStream;
}
public File getTempFile() {
return tempFile;
}
public void setTempFile(File tempFile) {
this.tempFile = tempFile;
}
public Boolean getConvertAllFiled() {
return convertAllFiled;
}
public void setConvertAllFiled(Boolean convertAllFiled) {
this.convertAllFiled = convertAllFiled;
}
@Override
public HolderEnum holderType() {
return HolderEnum.WORKBOOK;
}
}

239
src/main/java/com/alibaba/excel/read/metadata/holder/SheetHolder.java

@ -1,239 +0,0 @@
package com.alibaba.excel.read.metadata.holder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKey;
import com.alibaba.excel.metadata.CellStyle;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.metadata.property.ExcelHeadProperty;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.style.RowCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractHeadColumnWidthStyleStrategy;
/**
* sheet holder
*
* @author zhuangjiaju
*/
public class ReadSheetHolder extends AbstractReadHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(SheetHolder.class);
/***
* poi sheet
*/
private Sheet sheet;
/***
* sheetNo
*/
private Integer sheetNo;
/***
* sheetName
*/
private String sheetName;
/**
* get total row , Data may be inaccurate
*/
@Deprecated
private Integer total;
/***
* poi sheet
*/
private WorkbookHolder parentWorkBook;
/***
* has been initialized table
*/
private Map<Integer, TableHolder> hasBeenInitializedTable;
/**
* current param
*/
private com.alibaba.excel.write.metadata.Sheet sheetParam;
public static SheetHolder buildWriteWorkSheetHolder(com.alibaba.excel.write.metadata.Sheet sheet,
WorkbookHolder workbookHolder) {
SheetHolder sheetHolder = buildBaseSheetHolder(sheet, workbookHolder);
sheetHolder.setNewInitialization(Boolean.TRUE);
if (sheet.getNeedHead() == null) {
sheetHolder.setNeedHead(workbookHolder.needHead());
} else {
sheetHolder.setNeedHead(sheet.getNeedHead());
}
if (sheet.getWriteRelativeHeadRowIndex() == null) {
sheetHolder.setWriteRelativeHeadRowIndex(workbookHolder.writeRelativeHeadRowIndex());
} else {
sheetHolder.setWriteRelativeHeadRowIndex(sheet.getWriteRelativeHeadRowIndex());
}
// Compatible with old code
compatibleOldCode(sheet);
List<WriteHandler> handlerList = new ArrayList<WriteHandler>();
if (sheet.getCustomWriteHandlerList() != null && !sheet.getCustomWriteHandlerList().isEmpty()) {
handlerList.addAll(sheet.getCustomWriteHandlerList());
}
// Initialization Annotation
sheetHolder.initAnnotationConfig(handlerList);
sheetHolder
.setWriteHandlerMap(sheetHolder.sortAndClearUpHandler(handlerList, workbookHolder.getWriteHandlerMap()));
Map<Class, Converter> converterMap = new HashMap<Class, Converter>(workbookHolder.getWriteConverterMap());
if (sheet.getCustomConverterList() != null && !sheet.getCustomConverterList().isEmpty()) {
for (Converter converter : sheet.getCustomConverterList()) {
converterMap.put(converter.getClass(), converter);
}
}
sheetHolder.setWriteConverterMap(converterMap);
sheetHolder.setHasBeenInitializedTable(new HashMap<Integer, TableHolder>());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sheet writeHandlerMap:{}", sheetHolder.getWriteHandlerMap());
}
return sheetHolder;
}
public static SheetHolder buildReadWorkSheetHolder(com.alibaba.excel.write.metadata.Sheet sheet,
WorkbookHolder workbookHolder) {
SheetHolder sheetHolder = buildBaseSheetHolder(sheet, workbookHolder);
if (sheet.getReadHeadRowNumber() == null) {
if (workbookHolder.getReadHeadRowNumber() == null) {
sheetHolder.setReadHeadRowNumber(sheetHolder.getExcelHeadProperty().getHeadRowNumber());
} else {
sheetHolder.setReadHeadRowNumber(workbookHolder.getReadHeadRowNumber());
}
} else {
sheetHolder.setReadHeadRowNumber(sheet.getReadHeadRowNumber());
}
Map<ConverterKey, Converter> converterMap =
new HashMap<ConverterKey, Converter>(workbookHolder.getReadConverterMap());
if (sheet.getCustomConverterList() != null && !sheet.getCustomConverterList().isEmpty()) {
for (Converter converter : sheet.getCustomConverterList()) {
converterMap.put(ConverterKey.buildConverterKey(converter), converter);
}
}
sheetHolder.setReadConverterMap(converterMap);
List<ReadListener> readListenerList = new ArrayList<ReadListener>();
if (sheet.getCustomReadListenerList() != null && !sheet.getCustomReadListenerList().isEmpty()) {
readListenerList.addAll(sheet.getCustomReadListenerList());
}
sheetHolder.setReadListenerList(readListenerList);
return sheetHolder;
}
private static SheetHolder buildBaseSheetHolder(com.alibaba.excel.write.metadata.Sheet sheet,
WorkbookHolder workbookHolder) {
SheetHolder sheetHolder = new SheetHolder();
sheetHolder.setSheetParam(sheet);
sheetHolder.setParentWorkBook(workbookHolder);
boolean noHead = (sheet.getHead() == null || sheet.getHead().isEmpty()) && sheet.getClazz() == null;
if (noHead) {
// Use parent
sheetHolder.setHead(workbookHolder.getHead());
sheetHolder.setClazz(workbookHolder.getClazz());
} else {
sheetHolder.setHead(sheet.getHead());
sheetHolder.setClazz(sheet.getClazz());
}
if (sheet.getAutoTrim() == null) {
workbookHolder.setAutoTrim(workbookHolder.getAutoTrim());
} else {
workbookHolder.setAutoTrim(sheet.getNeedHead());
}
// Initialization property
sheetHolder
.setExcelHeadProperty(new ExcelHeadProperty(sheetHolder.getClazz(), sheetHolder.getHead(), workbookHolder));
return sheetHolder;
}
/**
* Compatible with old code
*/
@Deprecated
private static void compatibleOldCode(com.alibaba.excel.write.metadata.Sheet sheet) {
if (sheet.getColumnWidthMap() != null && !sheet.getColumnWidthMap().isEmpty()) {
final Map<Integer, Integer> columnWidthMap = sheet.getColumnWidthMap();
if (sheet.getCustomWriteHandlerList() == null) {
sheet.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
sheet.getCustomWriteHandlerList().add(new AbstractHeadColumnWidthStyleStrategy() {
@Override
protected Integer columnWidth(Head head) {
if (columnWidthMap.containsKey(head.getColumnIndex())) {
columnWidthMap.get(head.getColumnIndex());
}
return 20;
}
});
}
if (sheet.getTableStyle() != null) {
final TableStyle tableStyle = sheet.getTableStyle();
if (sheet.getCustomWriteHandlerList() == null) {
sheet.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
CellStyle headCellStyle = new CellStyle();
headCellStyle.setFont(tableStyle.getTableHeadFont());
headCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor());
CellStyle contentCellStyle = new CellStyle();
contentCellStyle.setFont(tableStyle.getTableContentFont());
contentCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor());
sheet.getCustomWriteHandlerList().add(new RowCellStyleStrategy(headCellStyle, contentCellStyle));
}
}
public Sheet getSheet() {
return sheet;
}
public void setSheet(Sheet sheet) {
this.sheet = sheet;
}
public Integer getSheetNo() {
return sheetNo;
}
public void setSheetNo(Integer sheetNo) {
this.sheetNo = sheetNo;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public WorkbookHolder getParentWorkBook() {
return parentWorkBook;
}
public void setParentWorkBook(WorkbookHolder parentWorkBook) {
this.parentWorkBook = parentWorkBook;
}
public Map<Integer, TableHolder> getHasBeenInitializedTable() {
return hasBeenInitializedTable;
}
public void setHasBeenInitializedTable(Map<Integer, TableHolder> hasBeenInitializedTable) {
this.hasBeenInitializedTable = hasBeenInitializedTable;
}
public com.alibaba.excel.write.metadata.Sheet getSheetParam() {
return sheetParam;
}
public void setSheetParam(com.alibaba.excel.write.metadata.Sheet sheetParam) {
this.sheetParam = sheetParam;
}
}

138
src/main/java/com/alibaba/excel/read/metadata/holder/TableHolder.java

@ -1,138 +0,0 @@
package com.alibaba.excel.read.metadata.holder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.CellStyle;
import com.alibaba.excel.write.metadata.Table;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.write.metadata.holder.AbstractWriteConfiguration;
import com.alibaba.excel.metadata.property.ExcelHeadProperty;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.style.RowCellStyleStrategy;
/**
* sheet holder
*
* @author zhuangjiaju
*/
public class ReadTableHolder extends AbstractReadHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(TableHolder.class);
/***
* poi sheet
*/
private SheetHolder parentSheet;
/***
* tableNo
*/
private Integer tableNo;
/**
* current table param
*/
private Table tableParam;
public static TableHolder buildWriteWorkTableHolder(Table table, SheetHolder sheetHolder,
WorkbookHolder workbookHolder) {
TableHolder tableHolder = new TableHolder();
tableHolder.setTableParam(table);
tableHolder.setParentSheet(sheetHolder);
tableHolder.setTableNo(table.getTableNo());
boolean noHead = (table.getHead() == null || table.getHead().isEmpty()) && table.getClazz() == null;
if (noHead) {
// Use parent
tableHolder.setHead(sheetHolder.getHead());
tableHolder.setClazz(sheetHolder.getClazz());
} else {
tableHolder.setHead(table.getHead());
tableHolder.setClazz(table.getClazz());
}
tableHolder.setNewInitialization(Boolean.TRUE);
// Initialization property
tableHolder.setExcelHeadProperty(
new ExcelHeadProperty(tableHolder.getClazz(), tableHolder.getHead(), workbookHolder.getConvertAllFiled()));
if (table.getNeedHead() == null) {
tableHolder.setNeedHead(sheetHolder.needHead());
} else {
tableHolder.setNeedHead(table.getNeedHead());
}
if (table.getWriteRelativeHeadRowIndex() == null) {
tableHolder.setWriteRelativeHeadRowIndex(sheetHolder.writeRelativeHeadRowIndex());
} else {
tableHolder.setWriteRelativeHeadRowIndex(table.getWriteRelativeHeadRowIndex());
}
// Compatible with old code
compatibleOldCode(table);
List<WriteHandler> handlerList = new ArrayList<WriteHandler>();
if (table.getCustomWriteHandlerList() != null && !table.getCustomWriteHandlerList().isEmpty()) {
handlerList.addAll(table.getCustomWriteHandlerList());
}
// Initialization Annotation
tableHolder.initAnnotationConfig(handlerList);
tableHolder
.setWriteHandlerMap(tableHolder.sortAndClearUpHandler(handlerList, sheetHolder.getWriteHandlerMap()));
Map<Class, Converter> converterMap = new HashMap<Class, Converter>(sheetHolder.getWriteConverterMap());
if (table.getCustomConverterList() != null && !table.getCustomConverterList().isEmpty()) {
for (Converter converter : table.getCustomConverterList()) {
converterMap.put(converter.getClass(), converter);
}
}
tableHolder.setWriteConverterMap(converterMap);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Table writeHandlerMap:{}", tableHolder.getWriteHandlerMap());
}
return tableHolder;
}
/**
* Compatible with old code
*/
@Deprecated
private static void compatibleOldCode(Table table) {
if (table.getTableStyle() != null) {
final TableStyle tableStyle = table.getTableStyle();
if (table.getCustomWriteHandlerList() == null) {
table.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
CellStyle headCellStyle = new CellStyle();
headCellStyle.setFont(tableStyle.getTableHeadFont());
headCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor());
CellStyle contentCellStyle = new CellStyle();
contentCellStyle.setFont(tableStyle.getTableContentFont());
contentCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor());
table.getCustomWriteHandlerList().add(new RowCellStyleStrategy(headCellStyle, contentCellStyle));
}
}
public SheetHolder getParentSheet() {
return parentSheet;
}
public void setParentSheet(SheetHolder parentSheet) {
this.parentSheet = parentSheet;
}
public Integer getTableNo() {
return tableNo;
}
public void setTableNo(Integer tableNo) {
this.tableNo = tableNo;
}
public Table getTableParam() {
return tableParam;
}
public void setTableParam(Table tableParam) {
this.tableParam = tableParam;
}
}

315
src/main/java/com/alibaba/excel/read/metadata/holder/WorkbookHolder.java

@ -1,315 +0,0 @@
package com.alibaba.excel.read.metadata.holder;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.cache.ReadCache;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKey;
import com.alibaba.excel.converters.DefaultConverterLoader;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.read.listener.ModelBuildEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.DefaultWriteHandlerLoader;
import com.alibaba.excel.write.handler.WriteHandler;
/**
* Workbook holder
*
* @author zhuangjiaju
*/
public class ReadWorkbookHolder extends AbstractReadHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(ReadWorkbookHolder.class);
/***
* poi Workbook
*/
private Workbook workbook;
/**
* current param
*/
private ReadWorkbook readWorkbook;
/**
* Read InputStream
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
private InputStream inputStream;
/**
* Read file
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
private File file;
/**
* Default true
*/
private Boolean autoCloseStream;
/**
* Excel type
*/
private ExcelTypeEnum excelType;
/**
* This object can be read in the Listener {@link AnalysisEventListener#invoke(Object, AnalysisContext)}
* {@link AnalysisContext#getCustom()}
*
*/
private Object readCustomObject;
/**
* A cache that stores temp data to save memory.Default use {@link com.alibaba.excel.cache.Ehcache}
*/
private ReadCache readCache;
/**
* Mmandatory use 'inputStream'
*/
private Boolean mandatoryUseInputStream;
/**
* Temporary files when reading excel
*/
private File readTempFile;
/**
* The default is all excel objects.if true , you can use {@link com.alibaba.excel.annotation.ExcelIgnore} ignore a
* field. 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
private com.alibaba.excel.event.WriteHandler writeHandler;
public static WorkbookHolder buildWriteWorkbookHolder(com.alibaba.excel.write.metadata.Workbook workbook) {
WorkbookHolder workbookHolder = buildBaseWorkbookHolder(workbook);
workbookHolder.setNewInitialization(Boolean.TRUE);
if (workbook.getNeedHead() == null) {
workbookHolder.setNeedHead(Boolean.TRUE);
} else {
workbookHolder.setNeedHead(workbook.getNeedHead());
}
if (workbook.getWriteRelativeHeadRowIndex() == null) {
workbookHolder.setWriteRelativeHeadRowIndex(0);
} else {
workbookHolder.setWriteRelativeHeadRowIndex(workbook.getWriteRelativeHeadRowIndex());
}
List<WriteHandler> handlerList = new ArrayList<WriteHandler>();
if (workbook.getCustomWriteHandlerList() != null && !workbook.getCustomWriteHandlerList().isEmpty()) {
handlerList.addAll(workbook.getCustomWriteHandlerList());
}
handlerList.addAll(DefaultWriteHandlerLoader.loadDefaultHandler());
workbookHolder.setWriteHandlerMap(workbookHolder.sortAndClearUpHandler(handlerList, null));
Map<Class, Converter> converterMap = DefaultConverterLoader.loadDefaultWriteConverter();
if (workbook.getCustomConverterList() != null && !workbook.getCustomConverterList().isEmpty()) {
for (Converter converter : workbook.getCustomConverterList()) {
converterMap.put(converter.getClass(), converter);
}
}
workbookHolder.setWriteConverterMap(converterMap);
workbookHolder.setHasBeenInitializedSheet(new HashMap<Integer, SheetHolder>());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Wookbook writeHandlerMap:{}", workbookHolder.getWriteHandlerMap());
}
return workbookHolder;
}
public static WorkbookHolder buildReadWorkbookHolder(com.alibaba.excel.write.metadata.Workbook workbook) {
WorkbookHolder workbookHolder = buildBaseWorkbookHolder(workbook);
if (workbook.getFile() == null && workbookHolder.getInputStream() == null) {
throw new ExcelAnalysisException("Read excel 'file' and 'inputStream' cannot be empty at the same time!");
}
workbookHolder.setReadCustomObject(workbook.getReadCustomObject());
workbookHolder.setReadHeadRowNumber(workbook.getReadHeadRowNumber());
workbookHolder.setReadCache(workbook.getReadCache());
Map<ConverterKey, Converter> converterMap = DefaultConverterLoader.loadDefaultReadConverter();
if (workbook.getCustomConverterList() != null && !workbook.getCustomConverterList().isEmpty()) {
for (Converter converter : workbook.getCustomConverterList()) {
converterMap.put(ConverterKey.buildConverterKey(converter), converter);
}
}
workbookHolder.setReadConverterMap(converterMap);
List<ReadListener> readListenerList = new ArrayList<ReadListener>();
readListenerList.add(new ModelBuildEventListener());
if (workbook.getCustomReadListenerList() != null && !workbook.getCustomReadListenerList().isEmpty()) {
readListenerList.addAll(workbook.getCustomReadListenerList());
}
workbookHolder.setReadListenerList(readListenerList);
return workbookHolder;
}
private static WorkbookHolder buildBaseWorkbookHolder(com.alibaba.excel.write.metadata.Workbook workbook) {
WorkbookHolder workbookHolder = new WorkbookHolder();
workbookHolder.setUse1904windowing(workbook.getUse1904windowing());
workbookHolder.setWorkbookParam(workbook);
workbookHolder.setInputStream(workbook.getInputStream());
workbookHolder.setFile(workbook.getFile());
workbookHolder.setExcelType(workbook.getExcelType());
workbookHolder.setHead(workbook.getHead());
workbookHolder.setClazz(workbook.getClazz());
if (workbook.getConvertAllFiled() == null) {
workbookHolder.setConvertAllFiled(Boolean.TRUE);
} else {
workbookHolder.setConvertAllFiled(workbook.getConvertAllFiled());
}
if (workbook.getAutoCloseStream() == null) {
workbookHolder.setAutoCloseStream(Boolean.TRUE);
} else {
workbookHolder.setAutoCloseStream(workbook.getAutoCloseStream());
}
if (workbook.getAutoTrim() == null) {
workbookHolder.setAutoTrim(Boolean.TRUE);
} else {
workbookHolder.setAutoTrim(workbook.getNeedHead());
}
return workbookHolder;
}
public Workbook getWorkbook() {
return workbook;
}
public void setWorkbook(Workbook workbook) {
this.workbook = workbook;
}
public Map<Integer, SheetHolder> getHasBeenInitializedSheet() {
return hasBeenInitializedSheet;
}
public void setHasBeenInitializedSheet(Map<Integer, SheetHolder> hasBeenInitializedSheet) {
this.hasBeenInitializedSheet = hasBeenInitializedSheet;
}
public com.alibaba.excel.write.metadata.Workbook getWorkbookParam() {
return workbookParam;
}
public void setWorkbookParam(com.alibaba.excel.write.metadata.Workbook workbookParam) {
this.workbookParam = workbookParam;
}
public OutputStream getOutputStream() {
return outputStream;
}
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public com.alibaba.excel.event.WriteHandler getWriteHandler() {
return writeHandler;
}
public void setWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) {
this.writeHandler = writeHandler;
}
public Boolean getAutoCloseStream() {
return autoCloseStream;
}
public void setAutoCloseStream(Boolean autoCloseStream) {
this.autoCloseStream = autoCloseStream;
}
public Boolean getConvertAllFiled() {
return convertAllFiled;
}
public void setConvertAllFiled(Boolean convertAllFiled) {
this.convertAllFiled = convertAllFiled;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public ExcelTypeEnum getExcelType() {
return excelType;
}
public void setExcelType(ExcelTypeEnum excelType) {
this.excelType = excelType;
}
public Object getReadCustomObject() {
return readCustomObject;
}
public void setReadCustomObject(Object readCustomObject) {
this.readCustomObject = readCustomObject;
}
public ReadCache getReadCache() {
return readCache;
}
public void setReadCache(ReadCache readCache) {
this.readCache = readCache;
}
public Boolean getUse1904windowing() {
return use1904windowing;
}
public void setUse1904windowing(Boolean use1904windowing) {
this.use1904windowing = use1904windowing;
}
public Boolean getMandatoryUseInputStream() {
return mandatoryUseInputStream;
}
public void setMandatoryUseInputStream(Boolean mandatoryUseInputStream) {
this.mandatoryUseInputStream = mandatoryUseInputStream;
}
public File getReadTempFile() {
return readTempFile;
}
public void setReadTempFile(File readTempFile) {
this.readTempFile = readTempFile;
}
@Override
public HolderEnum holderType() {
return HolderEnum.WORKBOOK;
}
}

29
src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java

@ -1,16 +1,25 @@
package com.alibaba.excel.support; package com.alibaba.excel.support;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.apache.poi.poifs.filesystem.FileMagic; import org.apache.poi.poifs.filesystem.FileMagic;
import com.alibaba.excel.exception.ExcelCommonException;
/** /**
* @author jipengfei * @author jipengfei
*/ */
public enum ExcelTypeEnum { public enum ExcelTypeEnum {
/**
XLS(".xls"), XLSX(".xlsx"); * xls
*/
XLS(".xls"),
/**
* xlsx
*/
XLSX(".xlsx");
private String value; private String value;
@ -18,22 +27,26 @@ public enum ExcelTypeEnum {
this.setValue(value); this.setValue(value);
} }
public static ExcelTypeEnum valueOf(InputStream inputStream) { public static ExcelTypeEnum valueOf(File file, InputStream inputStream) {
try { try {
if (!inputStream.markSupported()) { FileMagic fileMagic = null;
return null; if (file != null) {
fileMagic = FileMagic.valueOf(file);
} else {
fileMagic = FileMagic.valueOf(inputStream);
} }
FileMagic fileMagic = FileMagic.valueOf(inputStream);
if (FileMagic.OLE2.equals(fileMagic)) { if (FileMagic.OLE2.equals(fileMagic)) {
return XLS; return XLS;
} }
if (FileMagic.OOXML.equals(fileMagic)) { if (FileMagic.OOXML.equals(fileMagic)) {
return XLSX; return XLSX;
} }
return null;
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new ExcelCommonException(
"Convert excel format exception.You can try specifying the 'excelType' yourself", e);
} }
throw new ExcelCommonException(
"Convert excel format exception.You can try specifying the 'excelType' yourself");
} }
public String getValue() { public String getValue() {

26
src/main/java/com/alibaba/excel/util/WorkBookUtil.java

@ -13,8 +13,8 @@ import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/** /**
* *
@ -22,28 +22,28 @@ import com.alibaba.excel.support.ExcelTypeEnum;
*/ */
public class WorkBookUtil { public class WorkBookUtil {
public static Workbook createWorkBook(WorkbookHolder workbookHolder) public static Workbook createWorkBook(WriteWorkbookHolder writeWorkbookHolder)
throws IOException, InvalidFormatException { throws IOException, InvalidFormatException {
if (ExcelTypeEnum.XLSX.equals(workbookHolder.getExcelType())) { if (ExcelTypeEnum.XLSX.equals(writeWorkbookHolder.getExcelType())) {
if (workbookHolder.getFile() != null) { if (writeWorkbookHolder.getTemplateFile() != null) {
return new SXSSFWorkbook(new XSSFWorkbook(workbookParam.getFile())); return new SXSSFWorkbook(new XSSFWorkbook(writeWorkbookHolder.getTemplateFile()));
} }
if (workbookParam.getInputStream() != null) { if (writeWorkbookHolder.getTemplateInputStream() != null) {
return new SXSSFWorkbook(new XSSFWorkbook(workbookParam.getInputStream())); return new SXSSFWorkbook(new XSSFWorkbook(writeWorkbookHolder.getTemplateInputStream()));
} }
return new SXSSFWorkbook(500); return new SXSSFWorkbook(500);
} }
if (workbookParam.getFile() != null) { if (writeWorkbookHolder.getTemplateFile() != null) {
return new HSSFWorkbook(new POIFSFileSystem(workbookParam.getFile())); return new HSSFWorkbook(new POIFSFileSystem(writeWorkbookHolder.getTemplateFile()));
} }
if (workbookParam.getInputStream() != null) { if (writeWorkbookHolder.getTemplateInputStream() != null) {
return new HSSFWorkbook(new POIFSFileSystem(workbookParam.getInputStream())); return new HSSFWorkbook(new POIFSFileSystem(writeWorkbookHolder.getTemplateInputStream()));
} }
return new HSSFWorkbook(); return new HSSFWorkbook();
} }
public static Sheet createSheet(Workbook workbook, com.alibaba.excel.write.metadata.Sheet sheet) { public static Sheet createSheet(Workbook workbook, String sheetName) {
return workbook.createSheet(sheet.getSheetName() != null ? sheet.getSheetName() : sheet.getSheetNo() + ""); return workbook.createSheet(sheetName);
} }
public static Row createRow(Sheet sheet, int rowNum) { public static Row createRow(Sheet sheet, int rowNum) {

16
src/main/java/com/alibaba/excel/write/ExcelBuilder.java

@ -2,9 +2,9 @@ package com.alibaba.excel.write;
import java.util.List; import java.util.List;
import com.alibaba.excel.write.metadata.Sheet;
import com.alibaba.excel.write.metadata.Table;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy; import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
/** /**
* @author jipengfei * @author jipengfei
@ -16,24 +16,24 @@ public interface ExcelBuilder {
* *
* @param data * @param data
* java basic type or java model extend BaseModel * java basic type or java model extend BaseModel
* @param sheetParam * @param writeSheet
* Write the sheet * Write the sheet
* @deprecated please use{@link ExcelBuilder#addContent(List, Sheet, Table)} * @deprecated please use{@link ExcelBuilder#addContent(List, WriteSheet, WriteTable)}
*/ */
@Deprecated @Deprecated
void addContent(List data, Sheet sheetParam); void addContent(List data, WriteSheet writeSheet);
/** /**
* WorkBook increase value * WorkBook increase value
* *
* @param data * @param data
* java basic type or java model extend BaseModel * java basic type or java model extend BaseModel
* @param sheetParam * @param writeSheet
* Write the sheet * Write the sheet
* @param table * @param writeTable
* Write the table * Write the table
*/ */
void addContent(List data, Sheet sheetParam, Table table); void addContent(List data, WriteSheet writeSheet, WriteTable writeTable);
/** /**
* Creates new cell range. Indexes are zero-based. * Creates new cell range. Indexes are zero-based.

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

@ -7,6 +7,7 @@ import java.util.Set;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import com.alibaba.excel.context.WriteContext; import com.alibaba.excel.context.WriteContext;
@ -15,17 +16,17 @@ import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.exception.ExcelDataConvertException; import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.Sheet;
import com.alibaba.excel.write.metadata.Table;
import com.alibaba.excel.write.metadata.holder.WriteConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.POITempFile; import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.WorkBookUtil; import com.alibaba.excel.util.WorkBookUtil;
import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.RowWriteHandler; import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.Workbook; import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.WriteWorkbook;
import com.alibaba.excel.write.metadata.holder.WriteHolder;
import net.sf.cglib.beans.BeanMap; import net.sf.cglib.beans.BeanMap;
@ -36,20 +37,20 @@ public class ExcelBuilderImpl implements ExcelBuilder {
private WriteContext context; private WriteContext context;
public ExcelBuilderImpl(Workbook workbook) { public ExcelBuilderImpl(WriteWorkbook writeWorkbook) {
// 初始化时候创建临时缓存目录,用于规避POI在并发写bug // Create temporary cache directory at initialization time to avoid POI concurrent write bugs
POITempFile.createPOIFilesDirectory(); FileUtils.createPoiFilesDirectory();
context = new WriteContextImpl(workbook); context = new WriteContextImpl(writeWorkbook);
} }
private void doAddContent(List data) { private void doAddContent(List data) {
if (CollectionUtils.isEmpty(data)) { if (CollectionUtils.isEmpty(data)) {
return; return;
} }
org.apache.poi.ss.usermodel.Sheet currentSheet = context.currentSheetHolder().getSheet(); Sheet currentSheet = context.writeSheetHolder().getSheet();
int rowNum = currentSheet.getLastRowNum(); int rowNum = currentSheet.getLastRowNum();
if (context.currentConfiguration().isNew()) { if (context.currentWriteHolder().isNew()) {
rowNum += context.currentConfiguration().writeRelativeHeadRowIndex(); rowNum += context.currentWriteHolder().relativeHeadRowIndex();
} }
for (int relativeRowIndex = 0; relativeRowIndex < data.size(); relativeRowIndex++) { for (int relativeRowIndex = 0; relativeRowIndex < data.size(); relativeRowIndex++) {
int n = relativeRowIndex + rowNum + 1; int n = relativeRowIndex + rowNum + 1;
@ -58,14 +59,14 @@ public class ExcelBuilderImpl implements ExcelBuilder {
} }
@Override @Override
public void addContent(List data, Sheet sheetParam) { public void addContent(List data, WriteSheet writeSheet) {
addContent(data, sheetParam, null); addContent(data, writeSheet, null);
} }
@Override @Override
public void addContent(List data, Sheet sheetParam, Table table) { public void addContent(List data, WriteSheet writeSheet, WriteTable writeTable) {
context.currentSheet(sheetParam); context.currentSheet(writeSheet);
context.currentTable(table); context.currentTable(writeTable);
doAddContent(data); doAddContent(data);
} }
@ -77,12 +78,12 @@ public class ExcelBuilderImpl implements ExcelBuilder {
@Override @Override
public void merge(int firstRow, int lastRow, int firstCol, int lastCol) { public void merge(int firstRow, int lastRow, int firstCol, int lastCol) {
CellRangeAddress cra = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol); CellRangeAddress cra = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
context.currentSheetHolder().getSheet().addMergedRegion(cra); context.writeSheetHolder().getSheet().addMergedRegion(cra);
} }
private void addOneRowOfDataToExcel(Object oneRowData, int n, int relativeRowIndex) { private void addOneRowOfDataToExcel(Object oneRowData, int n, int relativeRowIndex) {
beforeRowCreate(n, relativeRowIndex); beforeRowCreate(n, relativeRowIndex);
Row row = WorkBookUtil.createRow(context.currentSheetHolder().getSheet(), n); Row row = WorkBookUtil.createRow(context.writeSheetHolder().getSheet(), n);
afterRowCreate(row, relativeRowIndex); afterRowCreate(row, relativeRowIndex);
if (oneRowData instanceof List) { if (oneRowData instanceof List) {
addBasicTypeToExcel((List)oneRowData, row, relativeRowIndex); addBasicTypeToExcel((List)oneRowData, row, relativeRowIndex);
@ -92,33 +93,31 @@ public class ExcelBuilderImpl implements ExcelBuilder {
} }
private void beforeRowCreate(int rowIndex, int relativeRowIndex) { private void beforeRowCreate(int rowIndex, int relativeRowIndex) {
List<WriteHandler> handlerList = List<WriteHandler> handlerList = context.currentWriteHolder().writeHandlerMap().get(RowWriteHandler.class);
context.currentConfiguration().writeHandlerMap().get(RowWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) { if (handlerList == null || handlerList.isEmpty()) {
return; return;
} }
for (WriteHandler writeHandler : handlerList) { for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) { if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).beforeRowCreate(context.currentSheetHolder(), ((RowWriteHandler)writeHandler).beforeRowCreate(context.writeSheetHolder(), context.writeTableHolder(),
context.currentTableHolder(), rowIndex, relativeRowIndex, false); rowIndex, relativeRowIndex, false);
} }
} }
} }
private void afterRowCreate(Row row, int relativeRowIndex) { private void afterRowCreate(Row row, int relativeRowIndex) {
List<WriteHandler> handlerList = List<WriteHandler> handlerList = context.currentWriteHolder().writeHandlerMap().get(RowWriteHandler.class);
context.currentConfiguration().writeHandlerMap().get(RowWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) { if (handlerList == null || handlerList.isEmpty()) {
return; return;
} }
for (WriteHandler writeHandler : handlerList) { for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) { if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).afterRowCreate(context.currentSheetHolder(), ((RowWriteHandler)writeHandler).afterRowCreate(context.writeSheetHolder(), context.writeTableHolder(),
context.currentTableHolder(), row, relativeRowIndex, false); row, relativeRowIndex, false);
} }
} }
if (null != context.currentWorkbookHolder().getWriteHandler()) { if (null != context.writeWorkbookHolder().getWriteWorkbook().getWriteHandler()) {
context.currentWorkbookHolder().getWriteHandler().row(row.getRowNum(), row); context.writeWorkbookHolder().getWriteWorkbook().getWriteHandler().row(row.getRowNum(), row);
} }
} }
@ -126,7 +125,7 @@ public class ExcelBuilderImpl implements ExcelBuilder {
if (CollectionUtils.isEmpty(oneRowData)) { if (CollectionUtils.isEmpty(oneRowData)) {
return; return;
} }
Map<Integer, Head> headMap = context.currentConfiguration().excelHeadProperty().getHeadMap(); Map<Integer, Head> headMap = context.currentWriteHolder().excelWriteHeadProperty().getHeadMap();
int dataIndex = 0; int dataIndex = 0;
int cellIndex = 0; int cellIndex = 0;
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) { for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
@ -154,17 +153,17 @@ public class ExcelBuilderImpl implements ExcelBuilder {
beforeCellCreate(row, head, relativeRowIndex); beforeCellCreate(row, head, relativeRowIndex);
Cell cell = WorkBookUtil.createCell(row, cellIndex); Cell cell = WorkBookUtil.createCell(row, cellIndex);
Object value = oneRowData.get(dataIndex); Object value = oneRowData.get(dataIndex);
converterAndSet(context.currentConfiguration(), value.getClass(), cell, value, null); converterAndSet(context.currentWriteHolder(), value.getClass(), cell, value, null);
afterCellCreate(head, cell, relativeRowIndex); afterCellCreate(head, cell, relativeRowIndex);
} }
private void addJavaObjectToExcel(Object oneRowData, Row row, int relativeRowIndex) { private void addJavaObjectToExcel(Object oneRowData, Row row, int relativeRowIndex) {
WriteConfiguration currentWriteConfiguration = context.currentConfiguration(); WriteHolder currentWriteHolder = context.currentWriteHolder();
BeanMap beanMap = BeanMap.create(oneRowData); BeanMap beanMap = BeanMap.create(oneRowData);
Set<String> beanMapHandledSet = new HashSet<String>(); Set<String> beanMapHandledSet = new HashSet<String>();
Map<Integer, Head> headMap = context.currentConfiguration().excelHeadProperty().getHeadMap(); Map<Integer, Head> headMap = context.currentWriteHolder().excelWriteHeadProperty().getHeadMap();
Map<Integer, ExcelContentProperty> contentPropertyMap = Map<Integer, ExcelContentProperty> contentPropertyMap =
context.currentConfiguration().excelHeadProperty().getContentPropertyMap(); context.currentWriteHolder().excelWriteHeadProperty().getContentPropertyMap();
int cellIndex = 0; int cellIndex = 0;
for (Map.Entry<Integer, ExcelContentProperty> entry : contentPropertyMap.entrySet()) { for (Map.Entry<Integer, ExcelContentProperty> entry : contentPropertyMap.entrySet()) {
cellIndex = entry.getKey(); cellIndex = entry.getKey();
@ -177,7 +176,7 @@ public class ExcelBuilderImpl implements ExcelBuilder {
beforeCellCreate(row, head, relativeRowIndex); beforeCellCreate(row, head, relativeRowIndex);
Cell cell = WorkBookUtil.createCell(row, cellIndex); Cell cell = WorkBookUtil.createCell(row, cellIndex);
Object value = beanMap.get(name); Object value = beanMap.get(name);
converterAndSet(currentWriteConfiguration, excelContentProperty.getField().getType(), cell, value, converterAndSet(currentWriteHolder, excelContentProperty.getField().getType(), cell, value,
excelContentProperty); excelContentProperty);
afterCellCreate(head, cell, relativeRowIndex); afterCellCreate(head, cell, relativeRowIndex);
beanMapHandledSet.add(name); beanMapHandledSet.add(name);
@ -196,49 +195,47 @@ public class ExcelBuilderImpl implements ExcelBuilder {
} }
beforeCellCreate(row, null, relativeRowIndex); beforeCellCreate(row, null, relativeRowIndex);
Cell cell = WorkBookUtil.createCell(row, cellIndex++); Cell cell = WorkBookUtil.createCell(row, cellIndex++);
converterAndSet(currentWriteConfiguration, entry.getValue().getClass(), cell, entry.getValue(), null); converterAndSet(currentWriteHolder, entry.getValue().getClass(), cell, entry.getValue(), null);
afterCellCreate(null, cell, relativeRowIndex); afterCellCreate(null, cell, relativeRowIndex);
} }
} }
private void beforeCellCreate(Row row, Head head, int relativeRowIndex) { private void beforeCellCreate(Row row, Head head, int relativeRowIndex) {
List<WriteHandler> handlerList = List<WriteHandler> handlerList = context.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class);
context.currentConfiguration().writeHandlerMap().get(CellWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) { if (handlerList == null || handlerList.isEmpty()) {
return; return;
} }
for (WriteHandler writeHandler : handlerList) { for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof CellWriteHandler) { if (writeHandler instanceof CellWriteHandler) {
((CellWriteHandler)writeHandler).beforeCellCreate(context.currentSheetHolder(), ((CellWriteHandler)writeHandler).beforeCellCreate(context.writeSheetHolder(),
context.currentTableHolder(), row, head, relativeRowIndex, false); context.writeTableHolder(), row, head, relativeRowIndex, false);
} }
} }
} }
private void afterCellCreate(Head head, Cell cell, int relativeRowIndex) { private void afterCellCreate(Head head, Cell cell, int relativeRowIndex) {
List<WriteHandler> handlerList = List<WriteHandler> handlerList = context.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class);
context.currentConfiguration().writeHandlerMap().get(CellWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) { if (handlerList == null || handlerList.isEmpty()) {
return; return;
} }
for (WriteHandler writeHandler : handlerList) { for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof CellWriteHandler) { if (writeHandler instanceof CellWriteHandler) {
((CellWriteHandler)writeHandler).afterCellCreate(context.currentSheetHolder(), ((CellWriteHandler)writeHandler).afterCellCreate(context.writeSheetHolder(), context.writeTableHolder(),
context.currentTableHolder(), cell, head, relativeRowIndex, false); cell, head, relativeRowIndex, false);
} }
} }
if (null != context.currentWorkbookHolder().getWriteHandler()) { if (null != context.writeWorkbookHolder().getWriteWorkbook().getWriteHandler()) {
context.currentWorkbookHolder().getWriteHandler().cell(cell.getRowIndex(), cell); context.writeWorkbookHolder().getWriteWorkbook().getWriteHandler().cell(cell.getRowIndex(), cell);
} }
} }
private void converterAndSet(WriteConfiguration currentWriteConfiguration, Class clazz, Cell cell, private void converterAndSet(WriteHolder currentWriteHolder, Class clazz, Cell cell, Object value,
Object value, ExcelContentProperty excelContentProperty) { ExcelContentProperty excelContentProperty) {
if (value == null) { if (value == null) {
return; return;
} }
Converter converter = currentWriteConfiguration.converterMap().get(clazz); Converter converter = currentWriteHolder.converterMap().get(clazz);
if (converter == null) { if (converter == null) {
throw new ExcelDataConvertException( throw new ExcelDataConvertException(
"Can not find 'Converter' support class " + clazz.getSimpleName() + "."); "Can not find 'Converter' support class " + clazz.getSimpleName() + ".");
@ -255,6 +252,9 @@ public class ExcelBuilderImpl implements ExcelBuilder {
throw new ExcelDataConvertException( throw new ExcelDataConvertException(
"Convert data:" + value + " return null,at row:" + cell.getRow().getRowNum()); "Convert data:" + value + " return null,at row:" + cell.getRow().getRowNum());
} }
if (cellData.getFormula() != null && cellData.getFormula()) {
cell.setCellFormula(cellData.getFormulaValue());
}
switch (cellData.getType()) { switch (cellData.getType()) {
case STRING: case STRING:
cell.setCellValue(cellData.getStringValue()); cell.setCellValue(cellData.getStringValue());

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

@ -7,15 +7,14 @@ import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.URI; import java.net.URI;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.write.metadata.Workbook;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteWorkbook;
/** /**
* Build ExcelBuilder * Build ExcelBuilder
@ -26,35 +25,20 @@ public class ExcelWriterBuilder {
/** /**
* Workbook * Workbook
*/ */
private Workbook workbook; private WriteWorkbook writeWorkbook;
public ExcelWriterBuilder() { public ExcelWriterBuilder() {
this.workbook = new Workbook(); this.writeWorkbook = new WriteWorkbook();
}
/**
* Count the number of added heads when read sheet.
*
* <li>0 - This Sheet has no head ,since the first row are the data
* <li>1 - This Sheet has one row head , this is the default
* <li>2 - This Sheet has two row head ,since the third row is the data
*
* @param readHeadRowNumber
* @return
*/
public ExcelWriterBuilder readHeadRowNumber(Integer readHeadRowNumber) {
workbook.setReadHeadRowNumber(readHeadRowNumber);
return this;
} }
/** /**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based. * Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
* *
* @param writeRelativeHeadRowIndex * @param relativeHeadRowIndex
* @return * @return
*/ */
public ExcelWriterBuilder writeRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) { public ExcelWriterBuilder relativeHeadRowIndex(Integer relativeHeadRowIndex) {
workbook.setWriteRelativeHeadRowIndex(writeRelativeHeadRowIndex); writeWorkbook.setRelativeHeadRowIndex(relativeHeadRowIndex);
return this; return this;
} }
@ -65,7 +49,7 @@ public class ExcelWriterBuilder {
* @return * @return
*/ */
public ExcelWriterBuilder head(List<List<String>> head) { public ExcelWriterBuilder head(List<List<String>> head) {
workbook.setHead(head); writeWorkbook.setHead(head);
return this; return this;
} }
@ -76,7 +60,7 @@ public class ExcelWriterBuilder {
* @return * @return
*/ */
public ExcelWriterBuilder head(Class clazz) { public ExcelWriterBuilder head(Class clazz) {
workbook.setClazz(clazz); writeWorkbook.setClazz(clazz);
return this; return this;
} }
@ -84,7 +68,7 @@ public class ExcelWriterBuilder {
* Need Head * Need Head
*/ */
public ExcelWriterBuilder needHead(Boolean needHead) { public ExcelWriterBuilder needHead(Boolean needHead) {
workbook.setNeedHead(needHead); writeWorkbook.setNeedHead(needHead);
return this; return this;
} }
@ -95,7 +79,7 @@ public class ExcelWriterBuilder {
* @return * @return
*/ */
public ExcelWriterBuilder autoCloseStream(Boolean autoCloseStream) { public ExcelWriterBuilder autoCloseStream(Boolean autoCloseStream) {
workbook.setAutoCloseStream(autoCloseStream); writeWorkbook.setAutoCloseStream(autoCloseStream);
return this; return this;
} }
@ -111,7 +95,7 @@ public class ExcelWriterBuilder {
*/ */
@Deprecated @Deprecated
public ExcelWriterBuilder convertAllFiled(Boolean convertAllFiled) { public ExcelWriterBuilder convertAllFiled(Boolean convertAllFiled) {
workbook.setConvertAllFiled(convertAllFiled); writeWorkbook.setConvertAllFiled(convertAllFiled);
return this; return this;
} }
@ -122,10 +106,10 @@ public class ExcelWriterBuilder {
* @return * @return
*/ */
public ExcelWriterBuilder registerConverter(Converter converter) { public ExcelWriterBuilder registerConverter(Converter converter) {
if (workbook.getCustomConverterMap() == null) { if (writeWorkbook.getCustomConverterList() == null) {
workbook.setCustomConverterMap(new HashMap<Class, Converter>()); writeWorkbook.setCustomConverterList(new ArrayList<Converter>());
} }
workbook.getCustomConverterMap().put(converter.supportJavaTypeKey(), converter); writeWorkbook.getCustomConverterList().add(converter);
return this; return this;
} }
@ -136,46 +120,46 @@ public class ExcelWriterBuilder {
* @return * @return
*/ */
public ExcelWriterBuilder registerWriteHandler(WriteHandler writeHandler) { public ExcelWriterBuilder registerWriteHandler(WriteHandler writeHandler) {
if (workbook.getCustomWriteHandlerList() == null) { if (writeWorkbook.getCustomWriteHandlerList() == null) {
workbook.setCustomWriteHandlerList(new ArrayList<WriteHandler>()); writeWorkbook.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
} }
workbook.getCustomWriteHandlerList().add(writeHandler); writeWorkbook.getCustomWriteHandlerList().add(writeHandler);
return this; return this;
} }
public ExcelWriterBuilder excelType(ExcelTypeEnum excelType) { public ExcelWriterBuilder excelType(ExcelTypeEnum excelType) {
workbook.setExcelType(excelType); writeWorkbook.setExcelType(excelType);
return this; return this;
} }
public ExcelWriterBuilder outputFile(OutputStream outputStream) { public ExcelWriterBuilder file(OutputStream outputStream) {
workbook.setOutputStream(outputStream); writeWorkbook.setOutputStream(outputStream);
return this; return this;
} }
public ExcelWriterBuilder outputFile(File outputFile) { public ExcelWriterBuilder file(File outputFile) {
try { try {
return outputFile(new FileOutputStream(outputFile)); return file(new FileOutputStream(outputFile));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
throw new ExcelGenerateException("Can not create file", e); throw new ExcelGenerateException("Can not create file", e);
} }
} }
public ExcelWriterBuilder outputFile(String outputPathName) { public ExcelWriterBuilder file(String outputPathName) {
return outputFile(new File(outputPathName)); return file(new File(outputPathName));
} }
public ExcelWriterBuilder outputFile(URI outputUri) { public ExcelWriterBuilder outputFile(URI outputUri) {
return outputFile(new File(outputUri)); return file(new File(outputUri));
} }
public ExcelWriterBuilder withTemplate(InputStream inputStream) { public ExcelWriterBuilder withTemplate(InputStream templateInputStream) {
workbook.setInputStream(inputStream); writeWorkbook.setTemplateInputStream(templateInputStream);
return this; return this;
} }
public ExcelWriterBuilder withTemplate(File file) { public ExcelWriterBuilder withTemplate(File templateFile) {
workbook.setFile(file); writeWorkbook.setTemplateFile(templateFile);
return this; return this;
} }
@ -194,11 +178,35 @@ public class ExcelWriterBuilder {
*/ */
@Deprecated @Deprecated
public ExcelWriterBuilder registerWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) { public ExcelWriterBuilder registerWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) {
workbook.setWriteHandler(writeHandler); writeWorkbook.setWriteHandler(writeHandler);
return this; return this;
} }
public ExcelWriter build() { public ExcelWriter build() {
return new ExcelWriter(workbook); return new ExcelWriter(writeWorkbook);
}
public ExcelWriterSheetBuilder sheet() {
return sheet(null, null);
} }
public ExcelWriterSheetBuilder sheet(Integer sheetNo) {
return sheet(sheetNo, null);
}
public ExcelWriterSheetBuilder sheet(String sheetName) {
return sheet(null, sheetName);
}
public ExcelWriterSheetBuilder sheet(Integer sheetNo, String sheetName) {
ExcelWriterSheetBuilder excelWriterSheetBuilder = new ExcelWriterSheetBuilder(build());
if (sheetNo != null) {
excelWriterSheetBuilder.sheetNo(sheetNo);
}
if (sheetName != null) {
excelWriterSheetBuilder.sheetName(sheetName);
}
return new ExcelWriterSheetBuilder(build());
}
} }

78
src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java

@ -1,12 +1,13 @@
package com.alibaba.excel.write.builder; package com.alibaba.excel.write.builder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.write.metadata.Sheet; import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
/** /**
* Build sheet * Build sheet
@ -14,38 +15,29 @@ import com.alibaba.excel.write.handler.WriteHandler;
* @author zhuangjiaju * @author zhuangjiaju
*/ */
public class ExcelWriterSheetBuilder { public class ExcelWriterSheetBuilder {
private ExcelWriter excelWriter;
/** /**
* Sheet * Sheet
*/ */
private Sheet sheet; private WriteSheet writeSheet;
public ExcelWriterSheetBuilder() { public ExcelWriterSheetBuilder() {
this.sheet = new Sheet(); this.writeSheet = new WriteSheet();
} }
/** public ExcelWriterSheetBuilder(ExcelWriter excelWriter) {
* Count the number of added heads when read sheet. this.writeSheet = new WriteSheet();
* this.excelWriter = excelWriter;
* <li>0 - This Sheet has no head ,since the first row are the data
* <li>1 - This Sheet has one row head , this is the default
* <li>2 - This Sheet has two row head ,since the third row is the data
*
* @param readHeadRowNumber
* @return
*/
public ExcelWriterSheetBuilder readHeadRowNumber(Integer readHeadRowNumber) {
sheet.setReadHeadRowNumber(readHeadRowNumber);
return this;
} }
/** /**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based. * Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
* *
* @param writeRelativeHeadRowIndex * @param relativeHeadRowIndex
* @return * @return
*/ */
public ExcelWriterSheetBuilder writeRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) { public ExcelWriterSheetBuilder relativeHeadRowIndex(Integer relativeHeadRowIndex) {
sheet.setWriteRelativeHeadRowIndex(writeRelativeHeadRowIndex); writeSheet.setRelativeHeadRowIndex(relativeHeadRowIndex);
return this; return this;
} }
@ -57,7 +49,7 @@ public class ExcelWriterSheetBuilder {
* @return * @return
*/ */
public ExcelWriterSheetBuilder head(List<List<String>> head) { public ExcelWriterSheetBuilder head(List<List<String>> head) {
sheet.setHead(head); writeSheet.setHead(head);
return this; return this;
} }
@ -69,7 +61,7 @@ public class ExcelWriterSheetBuilder {
* @return * @return
*/ */
public ExcelWriterSheetBuilder head(Class clazz) { public ExcelWriterSheetBuilder head(Class clazz) {
sheet.setClazz(clazz); writeSheet.setClazz(clazz);
return this; return this;
} }
@ -77,7 +69,7 @@ public class ExcelWriterSheetBuilder {
* Need Head * Need Head
*/ */
public ExcelWriterSheetBuilder needHead(Boolean needHead) { public ExcelWriterSheetBuilder needHead(Boolean needHead) {
sheet.setNeedHead(needHead); writeSheet.setNeedHead(needHead);
return this; return this;
} }
@ -88,10 +80,10 @@ public class ExcelWriterSheetBuilder {
* @return * @return
*/ */
public ExcelWriterSheetBuilder registerConverter(Converter converter) { public ExcelWriterSheetBuilder registerConverter(Converter converter) {
if (sheet.getCustomConverterMap() == null) { if (writeSheet.getCustomConverterList() == null) {
sheet.setCustomConverterMap(new HashMap<Class, Converter>()); writeSheet.setCustomConverterList(new ArrayList<Converter>());
} }
sheet.getCustomConverterMap().put(converter.supportJavaTypeKey(), converter); writeSheet.getCustomConverterList().add(converter);
return this; return this;
} }
@ -102,10 +94,10 @@ public class ExcelWriterSheetBuilder {
* @return * @return
*/ */
public ExcelWriterSheetBuilder registerWriteHandler(WriteHandler writeHandler) { public ExcelWriterSheetBuilder registerWriteHandler(WriteHandler writeHandler) {
if (sheet.getCustomWriteHandlerList() == null) { if (writeSheet.getCustomWriteHandlerList() == null) {
sheet.setCustomWriteHandlerList(new ArrayList<WriteHandler>()); writeSheet.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
} }
sheet.getCustomWriteHandlerList().add(writeHandler); writeSheet.getCustomWriteHandlerList().add(writeHandler);
return this; return this;
} }
@ -116,7 +108,7 @@ public class ExcelWriterSheetBuilder {
* @return * @return
*/ */
public ExcelWriterSheetBuilder sheetNo(Integer sheetNo) { public ExcelWriterSheetBuilder sheetNo(Integer sheetNo) {
sheet.setSheetNo(sheetNo); writeSheet.setSheetNo(sheetNo);
return this; return this;
} }
@ -127,12 +119,32 @@ public class ExcelWriterSheetBuilder {
* @return * @return
*/ */
public ExcelWriterSheetBuilder sheetName(String sheetName) { public ExcelWriterSheetBuilder sheetName(String sheetName) {
sheet.setSheetName(sheetName); writeSheet.setSheetName(sheetName);
return this; return this;
} }
public Sheet build() { public WriteSheet build() {
return sheet; return writeSheet;
}
public ExcelWriterSheetBuilder doWrite(List data) {
if (excelWriter == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.write().sheet()' to call this method");
}
excelWriter.write(data, build());
return new ExcelWriterSheetBuilder(excelWriter);
}
public ExcelWriterTableBuilder table() {
return table(null);
}
public ExcelWriterTableBuilder table(Integer tableNo) {
ExcelWriterTableBuilder excelWriterTableBuilder = new ExcelWriterTableBuilder(excelWriter, build());
if (tableNo != null) {
excelWriterTableBuilder.tableNo(tableNo);
}
return excelWriterTableBuilder;
} }
} }

68
src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java

@ -1,12 +1,14 @@
package com.alibaba.excel.write.builder; package com.alibaba.excel.write.builder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.write.metadata.Table; import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
/** /**
* Build sheet * Build sheet
@ -14,38 +16,32 @@ import com.alibaba.excel.write.handler.WriteHandler;
* @author zhuangjiaju * @author zhuangjiaju
*/ */
public class ExcelWriterTableBuilder { public class ExcelWriterTableBuilder {
private ExcelWriter excelWriter;
private WriteSheet writeSheet;
/** /**
* table * table
*/ */
private Table table; private WriteTable writeTable;
public ExcelWriterTableBuilder() { public ExcelWriterTableBuilder() {
this.table = new Table(); this.writeTable = new WriteTable();
} }
/** public ExcelWriterTableBuilder(ExcelWriter excelWriter, WriteSheet writeSheet) {
* Count the number of added heads when read sheet. this.excelWriter = excelWriter;
* this.writeSheet = writeSheet;
* <li>0 - This Sheet has no head ,since the first row are the data
* <li>1 - This Sheet has one row head , this is the default
* <li>2 - This Sheet has two row head ,since the third row is the data
*
* @param readHeadRowNumber
* @return
*/
public ExcelWriterTableBuilder readHeadRowNumber(Integer readHeadRowNumber) {
table.setReadHeadRowNumber(readHeadRowNumber);
return this;
} }
/** /**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based. * Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
* *
* @param writeRelativeHeadRowIndex * @param relativeHeadRowIndex
* @return * @return
*/ */
public ExcelWriterTableBuilder writeRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) { public ExcelWriterTableBuilder relativeHeadRowIndex(Integer relativeHeadRowIndex) {
table.setWriteRelativeHeadRowIndex(writeRelativeHeadRowIndex); writeTable.setRelativeHeadRowIndex(relativeHeadRowIndex);
return this; return this;
} }
@ -57,7 +53,7 @@ public class ExcelWriterTableBuilder {
* @return * @return
*/ */
public ExcelWriterTableBuilder head(List<List<String>> head) { public ExcelWriterTableBuilder head(List<List<String>> head) {
table.setHead(head); writeTable.setHead(head);
return this; return this;
} }
@ -69,7 +65,7 @@ public class ExcelWriterTableBuilder {
* @return * @return
*/ */
public ExcelWriterTableBuilder head(Class clazz) { public ExcelWriterTableBuilder head(Class clazz) {
table.setClazz(clazz); writeTable.setClazz(clazz);
return this; return this;
} }
@ -77,7 +73,7 @@ public class ExcelWriterTableBuilder {
* Need Head * Need Head
*/ */
public ExcelWriterTableBuilder needHead(Boolean needHead) { public ExcelWriterTableBuilder needHead(Boolean needHead) {
table.setNeedHead(needHead); writeTable.setNeedHead(needHead);
return this; return this;
} }
@ -88,10 +84,10 @@ public class ExcelWriterTableBuilder {
* @return * @return
*/ */
public ExcelWriterTableBuilder registerConverter(Converter converter) { public ExcelWriterTableBuilder registerConverter(Converter converter) {
if (table.getCustomConverterMap() == null) { if (writeTable.getCustomConverterList() == null) {
table.setCustomConverterMap(new HashMap<Class, Converter>()); writeTable.setCustomConverterList(new ArrayList<Converter>());
} }
table.getCustomConverterMap().put(converter.supportJavaTypeKey(), converter); writeTable.getCustomConverterList().add(converter);
return this; return this;
} }
@ -102,10 +98,10 @@ public class ExcelWriterTableBuilder {
* @return * @return
*/ */
public ExcelWriterTableBuilder registerWriteHandler(WriteHandler writeHandler) { public ExcelWriterTableBuilder registerWriteHandler(WriteHandler writeHandler) {
if (table.getCustomWriteHandlerList() == null) { if (writeTable.getCustomWriteHandlerList() == null) {
table.setCustomWriteHandlerList(new ArrayList<WriteHandler>()); writeTable.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
} }
table.getCustomWriteHandlerList().add(writeHandler); writeTable.getCustomWriteHandlerList().add(writeHandler);
return this; return this;
} }
@ -116,12 +112,20 @@ public class ExcelWriterTableBuilder {
* @return * @return
*/ */
public ExcelWriterTableBuilder tableNo(Integer tableNo) { public ExcelWriterTableBuilder tableNo(Integer tableNo) {
table.setTableNo(tableNo); writeTable.setTableNo(tableNo);
return this; return this;
} }
public Table build() { public WriteTable build() {
return table; return writeTable;
}
public ExcelWriterTableBuilder doWrite(List data) {
if (excelWriter == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.write().sheet().table()' to call this method");
}
excelWriter.write(data, writeSheet, build());
return new ExcelWriterTableBuilder(excelWriter, writeSheet);
} }
} }

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

@ -4,8 +4,8 @@ import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.SheetHolder; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.TableHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.sun.istack.internal.Nullable; import com.sun.istack.internal.Nullable;
/** /**
@ -18,26 +18,26 @@ public interface CellWriteHandler extends WriteHandler {
/** /**
* called before create the cell * called before create the cell
* *
* @param sheetHolder * @param writeSheetHolder
* @param tableHolder * @param writeTableHolder
* @param row * @param row
* @param head * @param head
* @param relativeRowIndex * @param relativeRowIndex
* @param isHead * @param isHead
*/ */
void beforeCellCreate(SheetHolder sheetHolder, @Nullable TableHolder tableHolder, Row row, Head head, void beforeCellCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, Row row,
int relativeRowIndex, boolean isHead); Head head, int relativeRowIndex, boolean isHead);
/** /**
* called after the cell is created * called after the cell is created
* *
* @param sheetHolder * @param writeSheetHolder
* @param tableHolder * @param writeTableHolder
* @param cell * @param cell
* @param head * @param head
* @param relativeRowIndex * @param relativeRowIndex
* @param isHead * @param isHead
*/ */
void afterCellCreate(SheetHolder sheetHolder, @Nullable TableHolder tableHolder, Cell cell, Head head, void afterCellCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, Cell cell,
int relativeRowIndex, boolean isHead); Head head, int relativeRowIndex, boolean isHead);
} }

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

@ -2,8 +2,8 @@ package com.alibaba.excel.write.handler;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import com.alibaba.excel.write.metadata.holder.SheetHolder; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.TableHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.sun.istack.internal.Nullable; import com.sun.istack.internal.Nullable;
/** /**
@ -16,24 +16,24 @@ public interface RowWriteHandler extends WriteHandler {
/** /**
* called before create the row * called before create the row
* *
* @param sheetHolder * @param writeSheetHolder
* @param tableHolder * @param writeTableHolder
* @param rowIndex * @param rowIndex
* @param relativeRowIndex * @param relativeRowIndex
* @param isHead * @param isHead
*/ */
void beforeRowCreate(SheetHolder sheetHolder, @Nullable TableHolder tableHolder, int rowIndex, int relativeRowIndex, void beforeRowCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, int rowIndex,
boolean isHead); int relativeRowIndex, boolean isHead);
/** /**
* called after the row is created * called after the row is created
* *
* @param sheetHolder * @param writeSheetHolder
* @param tableHolder * @param writeTableHolder
* @param row * @param row
* @param relativeRowIndex * @param relativeRowIndex
* @param isHead * @param isHead
*/ */
void afterRowCreate(SheetHolder sheetHolder, @Nullable TableHolder tableHolder, Row row, int relativeRowIndex, void afterRowCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, Row row,
boolean isHead); int relativeRowIndex, boolean isHead);
} }

16
src/main/java/com/alibaba/excel/write/handler/SheetWriteHandler.java

@ -1,7 +1,7 @@
package com.alibaba.excel.write.handler; package com.alibaba.excel.write.handler;
import com.alibaba.excel.write.metadata.holder.SheetHolder; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/** /**
* intercepts handle sheet creation * intercepts handle sheet creation
@ -13,16 +13,16 @@ public interface SheetWriteHandler extends WriteHandler {
/** /**
* called before create the sheet * called before create the sheet
* *
* @param workbookHolder * @param writeWorkbookHolder
* @param sheetHolder * @param writeSheetHolder
*/ */
void beforeSheetCreate(WorkbookHolder workbookHolder, SheetHolder sheetHolder); void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder);
/** /**
* called after the sheet is created * called after the sheet is created
* *
* @param workbookHolder * @param writeWorkbookHolder
* @param sheetHolder * @param writeSheetHolder
*/ */
void afterSheetCreate(WorkbookHolder workbookHolder, SheetHolder sheetHolder); void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder);
} }

6
src/main/java/com/alibaba/excel/write/handler/WorkbookWriteHandler.java

@ -1,6 +1,6 @@
package com.alibaba.excel.write.handler; package com.alibaba.excel.write.handler;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/** /**
* intercepts handle Workbook creation * intercepts handle Workbook creation
@ -17,7 +17,7 @@ public interface WorkbookWriteHandler extends WriteHandler {
/** /**
* called after the sheet is created * called after the sheet is created
* *
* @param workbookHolder * @param writeWorkbookHolder
*/ */
void afterWorkbookCreate(WorkbookHolder workbookHolder); void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder);
} }

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

@ -14,7 +14,7 @@ import com.alibaba.excel.write.handler.WriteHandler;
**/ **/
public class WriteWorkbook extends WriteBasicParameter { public class WriteWorkbook extends WriteBasicParameter {
/** /**
* Excel type * Excel type.The default is xlsx
*/ */
private ExcelTypeEnum excelType; private ExcelTypeEnum excelType;
/** /**

86
src/main/java/com/alibaba/excel/write/metadata/holder/UTils.java

@ -1,86 +0,0 @@
package com.alibaba.excel.write.metadata.holder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKey;
import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.read.metadata.read.ReadConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.metadata.property.ExcelHeadProperty;
import com.alibaba.excel.util.StringUtils;
/**
* TODO
*
* @author 罗成
**/
public class UTils {
private void buildHead(AnalysisContext analysisContext, List<CellData> cellDataList) {
if (!HeadKindEnum.CLASS.equals(analysisContext.currentConfiguration().excelHeadProperty().getHeadKind())) {
return;
}
List<String> dataList = (List<String>)buildStringList(cellDataList, analysisContext.currentConfiguration());
ExcelHeadProperty excelHeadPropertyData = analysisContext.currentConfiguration().excelHeadProperty();
Map<Integer, Head> headMapData = excelHeadPropertyData.getHeadMap();
Map<Integer, ExcelContentProperty> contentPropertyMapData = excelHeadPropertyData.getContentPropertyMap();
Map<Integer, Head> tmpHeadMap = new HashMap<Integer, Head>(headMapData.size() * 4 / 3 + 1);
Map<Integer, ExcelContentProperty> tmpContentPropertyMap =
new HashMap<Integer, ExcelContentProperty>(contentPropertyMapData.size() * 4 / 3 + 1);
for (Map.Entry<Integer, Head> entry : headMapData.entrySet()) {
Head headData = entry.getValue();
if (headData.getForceIndex()) {
tmpHeadMap.put(entry.getKey(), headData);
tmpContentPropertyMap.put(entry.getKey(), contentPropertyMapData.get(entry.getKey()));
continue;
}
String headName = headData.getHeadNameList().get(0);
for (int i = 0; i < dataList.size(); i++) {
String headString = dataList.get(i);
if (StringUtils.isEmpty(headString)) {
continue;
}
if (analysisContext.currentSheetHolder().getAutoTrim()) {
headString = headString.trim();
}
if (headName.equals(headString)) {
headData.setColumnIndex(i);
tmpHeadMap.put(i, headData);
tmpContentPropertyMap.put(i, contentPropertyMapData.get(entry.getKey()));
break;
}
}
}
excelHeadPropertyData.setHeadMap(tmpHeadMap);
excelHeadPropertyData.setContentPropertyMap(tmpContentPropertyMap);
}
private Object buildStringList(List<CellData> data, ReadConfiguration readConfiguration) {
List<String> list = new ArrayList<String>();
for (CellData cellData : data) {
Converter converter = readConfiguration.readConverterMap()
.get(ConverterKey.buildConverterKey(String.class, cellData.getType()));
if (converter == null) {
throw new ExcelDataConvertException(
"Converter not found, convert " + cellData.getType() + " to String");
}
try {
list.add((String)(converter.convertToJavaData(cellData, null)));
} catch (Exception e) {
throw new ExcelDataConvertException("Convert data " + cellData + " to String error ", e);
}
}
return list;
}
}

22
src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java

@ -6,7 +6,6 @@ import java.util.Map;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import com.alibaba.excel.enums.HolderEnum; import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.read.metadata.holder.TableHolder;
import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.metadata.WriteSheet;
/** /**
@ -34,11 +33,11 @@ public class WriteSheetHolder extends AbstractWriteHolder {
/*** /***
* poi sheet * poi sheet
*/ */
private WriteWorkbookHolder parentWorkBook; private WriteWorkbookHolder parentWriteWorkbookHolder;
/*** /***
* has been initialized table * has been initialized table
*/ */
private Map<Integer, TableHolder> hasBeenInitializedTable; private Map<Integer, WriteTableHolder> hasBeenInitializedTable;
public WriteSheetHolder(WriteSheet writeSheet, WriteWorkbookHolder writeWorkbookHolder) { public WriteSheetHolder(WriteSheet writeSheet, WriteWorkbookHolder writeWorkbookHolder) {
super(writeSheet, writeWorkbookHolder, writeWorkbookHolder.getWriteWorkbook().getConvertAllFiled()); super(writeSheet, writeWorkbookHolder, writeWorkbookHolder.getWriteWorkbook().getConvertAllFiled());
@ -49,8 +48,8 @@ public class WriteSheetHolder extends AbstractWriteHolder {
} else { } else {
this.sheetName = writeSheet.getSheetName(); this.sheetName = writeSheet.getSheetName();
} }
this.parentWorkBook = writeWorkbookHolder; this.parentWriteWorkbookHolder = writeWorkbookHolder;
this.hasBeenInitializedTable = new HashMap<Integer, TableHolder>(); this.hasBeenInitializedTable = new HashMap<Integer, WriteTableHolder>();
} }
public WriteSheet getWriteSheet() { public WriteSheet getWriteSheet() {
@ -85,20 +84,19 @@ public class WriteSheetHolder extends AbstractWriteHolder {
this.sheetName = sheetName; this.sheetName = sheetName;
} }
public WriteWorkbookHolder getParentWorkBook() { public WriteWorkbookHolder getParentWriteWorkbookHolder() {
return parentWorkBook; return parentWriteWorkbookHolder;
} }
public void setParentWorkBook(WriteWorkbookHolder parentWorkBook) { public void setParentWriteWorkbookHolder(WriteWorkbookHolder parentWriteWorkbookHolder) {
this.parentWorkBook = parentWorkBook; this.parentWriteWorkbookHolder = parentWriteWorkbookHolder;
} }
public Map<Integer, TableHolder> getHasBeenInitializedTable() { public Map<Integer, WriteTableHolder> getHasBeenInitializedTable() {
return hasBeenInitializedTable; return hasBeenInitializedTable;
} }
public void setHasBeenInitializedTable( public void setHasBeenInitializedTable(Map<Integer, WriteTableHolder> hasBeenInitializedTable) {
Map<Integer, TableHolder> hasBeenInitializedTable) {
this.hasBeenInitializedTable = hasBeenInitializedTable; this.hasBeenInitializedTable = hasBeenInitializedTable;
} }

12
src/main/java/com/alibaba/excel/write/metadata/holder/WriteTableHolder.java

@ -12,7 +12,7 @@ public class WriteTableHolder extends AbstractWriteHolder {
/*** /***
* poi sheet * poi sheet
*/ */
private WriteSheetHolder parentSheet; private WriteSheetHolder parentWriteSheetHolder;
/*** /***
* tableNo * tableNo
*/ */
@ -25,17 +25,17 @@ public class WriteTableHolder extends AbstractWriteHolder {
public WriteTableHolder(WriteTable writeTable, WriteSheetHolder writeSheetHolder, public WriteTableHolder(WriteTable writeTable, WriteSheetHolder writeSheetHolder,
WriteWorkbookHolder writeWorkbookHolder) { WriteWorkbookHolder writeWorkbookHolder) {
super(writeTable, writeSheetHolder, writeWorkbookHolder.getWriteWorkbook().getConvertAllFiled()); super(writeTable, writeSheetHolder, writeWorkbookHolder.getWriteWorkbook().getConvertAllFiled());
this.parentSheet = writeSheetHolder; this.parentWriteSheetHolder = writeSheetHolder;
this.tableNo = writeTable.getTableNo(); this.tableNo = writeTable.getTableNo();
this.writeTable = writeTable; this.writeTable = writeTable;
} }
public WriteSheetHolder getParentSheet() { public WriteSheetHolder getParentWriteSheetHolder() {
return parentSheet; return parentWriteSheetHolder;
} }
public void setParentSheet(WriteSheetHolder parentSheet) { public void setParentWriteSheetHolder(WriteSheetHolder parentWriteSheetHolder) {
this.parentSheet = parentSheet; this.parentWriteSheetHolder = parentWriteSheetHolder;
} }
public Integer getTableNo() { public Integer getTableNo() {

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

@ -7,6 +7,8 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.enums.HolderEnum; import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
@ -18,6 +20,7 @@ import com.alibaba.excel.write.metadata.WriteWorkbook;
* @author zhuangjiaju * @author zhuangjiaju
*/ */
public class WriteWorkbookHolder extends AbstractWriteHolder { public class WriteWorkbookHolder extends AbstractWriteHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(WriteWorkbookHolder.class);
/*** /***
* poi Workbook * poi Workbook
*/ */
@ -71,7 +74,14 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
} else { } else {
this.autoCloseStream = writeWorkbook.getAutoCloseStream(); this.autoCloseStream = writeWorkbook.getAutoCloseStream();
} }
this.excelType = writeWorkbook.getExcelType(); if (writeWorkbook.getExcelType() == null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("The default specified xlsx.");
}
this.excelType = ExcelTypeEnum.XLSX;
} else {
this.excelType = writeWorkbook.getExcelType();
}
if (writeWorkbook.getMandatoryUseInputStream() == null) { if (writeWorkbook.getMandatoryUseInputStream() == null) {
this.mandatoryUseInputStream = Boolean.FALSE; this.mandatoryUseInputStream = Boolean.FALSE;
} else { } else {

21
src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java

@ -6,11 +6,11 @@ import org.apache.poi.ss.usermodel.Workbook;
import com.alibaba.excel.event.NotRepeatExecutor; import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.SheetHolder;
import com.alibaba.excel.write.metadata.holder.TableHolder;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder;
import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.WorkbookWriteHandler; import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/** /**
* Cell style strategy * Cell style strategy
@ -27,23 +27,24 @@ public abstract class AbstractCellStyleStrategy implements CellWriteHandler, Wor
public void beforeWorkbookCreate() {} public void beforeWorkbookCreate() {}
@Override @Override
public void afterWorkbookCreate(WorkbookHolder workbookHolder) { public void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) {
initCellStyle(workbookHolder.getWorkbook()); initCellStyle(writeWorkbookHolder.getWorkbook());
} }
@Override @Override
public void beforeCellCreate(SheetHolder sheetHolder, TableHolder tableHolder, Row row, Head head, public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
int relativeRowIndex, boolean isHead) {} Head head, int relativeRowIndex, boolean isHead) {
}
@Override @Override
public void afterCellCreate(SheetHolder sheetHolder, TableHolder tableHolder, Cell cell, Head head, public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
int relativeRowIndex, boolean isHead) { Head head, int relativeRowIndex, boolean isHead) {
if (isHead) { if (isHead) {
setHeadCellStyle(cell, head, relativeRowIndex); setHeadCellStyle(cell, head, relativeRowIndex);
} else { } else {
setContentCellStyle(cell, head, relativeRowIndex); setContentCellStyle(cell, head, relativeRowIndex);
} }
} }
/** /**

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

@ -6,9 +6,9 @@ import org.apache.poi.ss.usermodel.Sheet;
import com.alibaba.excel.event.NotRepeatExecutor; import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.SheetHolder;
import com.alibaba.excel.write.metadata.holder.TableHolder;
import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.sun.istack.internal.Nullable; import com.sun.istack.internal.Nullable;
/** /**
@ -24,16 +24,18 @@ public abstract class AbstractColumnWidthStyleStrategy implements CellWriteHandl
} }
@Override @Override
public void beforeCellCreate(SheetHolder sheetHolder, TableHolder tableHolder, Row row, Head head, public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
int relativeRowIndex, boolean isHead) {} Head head, int relativeRowIndex, boolean isHead) {
}
@Override @Override
public void afterCellCreate(SheetHolder sheetHolder, TableHolder tableHolder, Cell cell, Head head, public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
int relativeRowIndex, boolean isHead) { Head head, int relativeRowIndex, boolean isHead) {
if (!isHead && relativeRowIndex != 0) { if (!isHead && relativeRowIndex != 0) {
return; return;
} }
setColumnWidth(sheetHolder.getSheet(), cell, head); setColumnWidth(writeSheetHolder.getSheet(), cell, head);
} }
/** /**

12
src/main/java/com/alibaba/excel/write/style/row/AbstractRowHeightStyleStrategy.java

@ -3,9 +3,9 @@ package com.alibaba.excel.write.style.row;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import com.alibaba.excel.event.NotRepeatExecutor; import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.write.metadata.holder.SheetHolder;
import com.alibaba.excel.write.metadata.holder.TableHolder;
import com.alibaba.excel.write.handler.RowWriteHandler; import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
/** /**
* Set the row height strategy * Set the row height strategy
@ -20,14 +20,14 @@ public abstract class AbstractRowHeightStyleStrategy implements RowWriteHandler,
} }
@Override @Override
public void beforeRowCreate(SheetHolder sheetHolder, TableHolder tableHolder, int rowIndex, int relativeRowIndex, public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, int rowIndex,
boolean isHead) { int relativeRowIndex, boolean isHead) {
} }
@Override @Override
public void afterRowCreate(SheetHolder sheetHolder, TableHolder tableHolder, Row row, int relativeRowIndex, public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
boolean isHead) { int relativeRowIndex, boolean isHead) {
if (isHead) { if (isHead) {
setHeadColumnHeight(row, relativeRowIndex); setHeadColumnHeight(row, relativeRowIndex);
} else { } else {

39
src/test/java/com/alibaba/easyexcel/test/read/large/LargeData07Test.java

@ -1,12 +1,19 @@
package com.alibaba.easyexcel.test.read.large; package com.alibaba.easyexcel.test.read.large;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.alibaba.easyexcel.test.util.FileUtil;
import com.alibaba.excel.EasyExcelFactory; import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader; import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.write.metadata.Sheet; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
/** /**
* Simple data test * Simple data test
@ -18,13 +25,29 @@ public class LargeData07Test {
@Test @Test
public void large() throws Exception { public void large() throws Exception {
LOGGER.info("start"); EasyExcelFactory.read().registerReadListener(listener).file(in).sheet().sheetNo(sheetNo).doRead().finish();
long start = System.currentTimeMillis();
// InputStream inputStream = FileUtil.readFile("large/large07.xlsx"); //
ExcelReader excelReader = EasyExcelFactory.getReader(null, new LargeDataListener()); // public static List<Object> read(InputStream in, Sheet sheet) {
excelReader.read(new Sheet(1, 1)); // final List<Object> rows = new ArrayList<Object>();
// inputStream.close(); // new ExcelReader(in, null, new AnalysisEventListener<Object>() {
LOGGER.info("time:{}", System.currentTimeMillis() - start); // @Override
// public void invoke(Object object, AnalysisContext context) {
// rows.add(object);
// }
//
// @Override
// public void doAfterAllAnalysed(AnalysisContext context) {}
// }, false).read(sheet);
// return rows;
// }
// LOGGER.info("start");
// long start = System.currentTimeMillis();
// // InputStream inputStream = FileUtil.readFile("large/large07.xlsx");
// ExcelReader excelReader = EasyExcelFactory.getReader(null, new LargeDataListener());
// excelReader.read(new Sheet(1, 1));
// // inputStream.close();
// LOGGER.info("time:{}", System.currentTimeMillis() - start);
} }
@Test @Test

Loading…
Cancel
Save