Browse Source

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

developing
zhuangjiaju 5 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. 223
      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. 18
      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. 10
      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.event.AnalysisEventListener;
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.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
@ -29,7 +31,9 @@ public class EasyExcelFactory {
* @param sheet
* read sheet.
* @return analysis result.
* @deprecated please use 'EasyExcelFactory.read().file(in).sheet(sheetNo).doReadSync();'
*/
@Deprecated
public static List<Object> read(InputStream in, Sheet sheet) {
final List<Object> rows = new ArrayList<Object>();
new ExcelReader(in, null, new AnalysisEventListener<Object>() {
@ -53,7 +57,9 @@ public class EasyExcelFactory {
* read sheet.
* @param listener
* 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) {
new ExcelReader(in, null, listener).read(sheet);
}
@ -66,7 +72,9 @@ public class EasyExcelFactory {
* @param listener
* Callback method after each row is parsed.
* @return ExcelReader.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/
@Deprecated
public static ExcelReader getReader(InputStream in, AnalysisEventListener listener) {
return new ExcelReader(in, null, listener);
}
@ -77,12 +85,11 @@ public class EasyExcelFactory {
* @param outputStream
* the java OutputStream you wish to write the value to.
* @return new ExcelWriter.
* @deprecated please use {@link EasyExcelFactory#writerBuilder()}
* @deprecated please use {@link EasyExcelFactory#write()}
*/
@Deprecated
public static ExcelWriter getWriter(OutputStream outputStream) {
return writerBuilder().outputFile(outputStream).autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE)
.build();
return write().file(outputStream).autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build();
}
/**
@ -95,12 +102,12 @@ public class EasyExcelFactory {
* @param needHead
* Do you need to write the header to the file?
* @return new ExcelWriter
* @deprecated please use {@link EasyExcelFactory#writerBuilder()}
* @deprecated please use {@link EasyExcelFactory#write()}
*/
@Deprecated
public static ExcelWriter getWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) {
return writerBuilder().outputFile(outputStream).excelType(typeEnum).needHead(needHead)
.autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build();
return write().file(outputStream).excelType(typeEnum).needHead(needHead).autoCloseStream(Boolean.FALSE)
.convertAllFiled(Boolean.FALSE).build();
}
/**
@ -114,12 +121,12 @@ public class EasyExcelFactory {
* @param typeEnum
* 03 or 07
* @return new ExcelWriter
* @deprecated please use {@link EasyExcelFactory#writerBuilder()}
* @deprecated please use {@link EasyExcelFactory#write()}
*/
@Deprecated
public static ExcelWriter getWriterWithTemp(InputStream temp, OutputStream outputStream, ExcelTypeEnum typeEnum,
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();
}
@ -137,24 +144,32 @@ public class EasyExcelFactory {
* @param handler
* User-defined callback
* @return new ExcelWriter
* @deprecated please use {@link EasyExcelFactory#writerBuilder()}
* @deprecated please use {@link EasyExcelFactory#write()}
*/
@Deprecated
public static ExcelWriter getWriterWithTempAndHandler(InputStream temp, OutputStream outputStream,
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();
}
public static ExcelWriterBuilder writerBuilder() {
public static ExcelWriterBuilder write() {
return new ExcelWriterBuilder();
}
public static ExcelWriterSheetBuilder writerSheetBuilder() {
public static ExcelWriterSheetBuilder writerSheet() {
return new ExcelWriterSheetBuilder();
}
public static ExcelWriterTableBuilder writerTableBuilder() {
public static ExcelWriterTableBuilder writerTable() {
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;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
@ -9,12 +10,15 @@ import org.slf4j.LoggerFactory;
import com.alibaba.excel.analysis.ExcelAnalyser;
import com.alibaba.excel.analysis.ExcelAnalyserImpl;
import com.alibaba.excel.analysis.ExcelExecutor;
import com.alibaba.excel.cache.MapCache;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.event.AnalysisEventListener;
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.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.support.ExcelTypeEnum;
/**
@ -43,6 +47,7 @@ public class ExcelReader {
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener
* Callback method after each row is parsed.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/
@Deprecated
public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent,
@ -59,24 +64,11 @@ public class ExcelReader {
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener
* Callback method after each row is parsed
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/
@Deprecated
public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener) {
this(in, customContent, eventListener, null, 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);
this(in, customContent, eventListener, true);
}
/**
@ -86,6 +78,7 @@ public class ExcelReader {
* old param Deprecated
* @param eventListener
* Callback method after each row is parsed.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/
@Deprecated
public ExcelReader(AnalysisParam param, AnalysisEventListener eventListener) {
@ -96,59 +89,59 @@ public class ExcelReader {
* Create new reader
*
* @param in
* the POI filesystem that contains the Workbook stream
* @param excelTypeEnum
* 03 or 07
* @param customContent
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener
* Callback method after each row is parsed.
* @param trim
* 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:
* '1234 ' contain a space cannot be converted to int.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/
@Deprecated
public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent,
AnalysisEventListener eventListener, boolean trim) {
this(in, excelTypeEnum, customContent, eventListener, null, trim);
public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener, boolean trim) {
this(in, null, customContent, eventListener, trim);
}
/**
* Create new reader
*
* @param in
* the POI filesystem that contains the Workbook stream
* @param excelTypeEnum
* 03 or 07
* @param customContent
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener
* Callback method after each row is parsed.
* @param trim
* 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:
* '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,
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);
}
@Deprecated
public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent,
AnalysisEventListener eventListener, List<Converter> converters, boolean trim) {
validateParam(in, eventListener);
analyser = new ExcelAnalyserImpl(in, excelTypeEnum, customContent, eventListener, trim);
initConverters(analyser, converters);
}
private void initConverters(ExcelAnalyser analyser, List<Converter> converters) {
if (converters != null && converters.size() > 0) {
for (Converter c : converters) {
analyser.getAnalysisContext().getConverterRegistryCenter().register(c);
AnalysisEventListener eventListener, boolean trim) {
ReadWorkbook readWorkbook = new ReadWorkbook();
readWorkbook.setInputStream(in);
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);
}
public ExcelReader(ReadWorkbook readWorkbook) {
excelAnalyser = new ExcelAnalyserImpl(readWorkbook);
}
/**
@ -160,20 +153,42 @@ public class ExcelReader {
LOGGER.warn("Excel doesn't have any sheets.");
return;
}
for (Sheet sheet : excelExecutor.sheetList()) {
read(sheet);
for (ReadSheet readSheet : excelExecutor.sheetList()) {
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
*
* @param sheet
* Read sheet
* @deprecated please us {@link #read(ReadSheet)}
*/
@Deprecated
public void read(Sheet sheet) {
checkFinished();
excelAnalyser.analysis(sheet);
ReadSheet readSheet = null;
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
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.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.write.metadata.Sheet;
import com.alibaba.excel.write.metadata.Table;
import com.alibaba.excel.write.metadata.Workbook;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.parameter.GenerateParam;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.ExcelBuilder;
import com.alibaba.excel.write.ExcelBuilderImpl;
import com.alibaba.excel.write.handler.WriteHandler;
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
@ -34,36 +35,10 @@ public class ExcelWriter {
/**
* Create new writer
*
* @param templateInputStream
* 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
* @param writeWorkbook
*/
public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum excelType,
boolean needHead, Map<Class, Converter> customConverterMap, List<WriteHandler> customWriteHandlerList) {
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);
public ExcelWriter(WriteWorkbook writeWorkbook) {
excelBuilder = new ExcelBuilderImpl(writeWorkbook);
}
/**
@ -94,7 +69,7 @@ public class ExcelWriter {
*/
@Deprecated
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
public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum,
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) {
List<WriteHandler> customWriteHandlerList = new ArrayList<WriteHandler>();
customWriteHandlerList.add(writeHandler);
Workbook workbook = new Workbook();
workbook.setInputStream(templateInputStream);
workbook.setOutputStream(outputStream);
workbook.setExcelType(typeEnum);
workbook.setNeedHead(needHead);
workbook.setCustomWriteHandlerList(customWriteHandlerList);
excelBuilder = new ExcelBuilderImpl(workbook);
WriteWorkbook writeWorkbook = new WriteWorkbook();
writeWorkbook.setTemplateInputStream(templateInputStream);
writeWorkbook.setOutputStream(outputStream);
writeWorkbook.setExcelType(typeEnum);
writeWorkbook.setNeedHead(needHead);
writeWorkbook.setCustomWriteHandlerList(customWriteHandlerList);
excelBuilder = new ExcelBuilderImpl(writeWorkbook);
}
/**
@ -157,12 +132,12 @@ public class ExcelWriter {
*
* @param data
* Data to be written
* @param sheet
* @param writeSheet
* Write to this sheet
* @return this current writer
*/
public ExcelWriter write(List data, Sheet sheet) {
return write(data, sheet, null);
public ExcelWriter write(List data, WriteSheet writeSheet) {
return write(data, writeSheet, null);
}
/**
@ -170,45 +145,85 @@ public class ExcelWriter {
*
* @param data
* Data to be written
* @param sheet
* @param writeSheet
* Write to this sheet
* @param table
* @param writeTable
* Write to this table
* @return this
*/
public ExcelWriter write(List data, Sheet sheet, Table table) {
excelBuilder.addContent(data, sheet, table);
public ExcelWriter write(List data, WriteSheet writeSheet, WriteTable writeTable) {
excelBuilder.addContent(data, writeSheet, writeTable);
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
*
* @param data
* Data to be written
* @param sheet
* Write to this sheet
* @param table
* Write to this table
* @return this
* @deprecated please use {@link ExcelWriter#write(List, Sheet)}
* @deprecated * @deprecated please use {@link ExcelWriter#write(List, WriteSheet,WriteTable)}
*/
@Deprecated
public ExcelWriter write1(List data, Sheet sheet) {
return write(data, sheet);
public ExcelWriter write(List data, Sheet sheet, Table table) {
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
* Data to be written
* @param 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
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
* @param 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
public ExcelWriter write0(List data, Sheet sheet, Table 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
* @param 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
public ExcelWriter write1(List data, Sheet sheet, Table 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;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.write.metadata.Sheet;
import com.alibaba.excel.read.metadata.ReadSheet;
/**
* Excel file analyser
@ -12,9 +12,9 @@ public interface ExcelAnalyser {
/**
* 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

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.AnalysisContextImpl;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.write.metadata.Sheet;
import com.alibaba.excel.write.metadata.Workbook;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.support.ExcelTypeEnum;
/**
@ -18,14 +18,14 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
private ExcelExecutor excelExecutor;
public ExcelAnalyserImpl(Workbook workbook) {
analysisContext = new AnalysisContextImpl(workbook);
public ExcelAnalyserImpl(ReadWorkbook readWorkbook) {
analysisContext = new AnalysisContextImpl(readWorkbook);
choiceExcelExecutor();
}
private void choiceExcelExecutor() {
try {
ExcelTypeEnum excelType = analysisContext.currentWorkbookHolder().getExcelType();
ExcelTypeEnum excelType = analysisContext.readWorkbookHolder().getExcelType();
if (excelType == null) {
excelExecutor = new XlsxSaxAnalyser(analysisContext);
return;
@ -46,12 +46,15 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
}
@Override
public void analysis(Sheet sheet) {
analysisContext.currentSheet(sheet);
public void analysis(ReadSheet readSheet) {
analysisContext.currentSheet(excelExecutor, readSheet);
excelExecutor.execute();
analysisContext.getEventListener().doAfterAllAnalysed(analysisContext);
analysisContext.readSheetHolder().notifyAfterAllAnalysed(analysisContext);
}
@Override
public void finish() {}
@Override
public com.alibaba.excel.analysis.ExcelExecutor 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 com.alibaba.excel.write.metadata.Sheet;
import com.alibaba.excel.read.metadata.ReadSheet;
/**
* Excel file Executor
@ -11,7 +11,7 @@ import com.alibaba.excel.write.metadata.Sheet;
*/
public interface ExcelExecutor {
List<Sheet> sheetList();
List<ReadSheet> sheetList();
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.SSTRecordHandler;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.event.EachRowAnalysisFinishEvent;
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;
/**
@ -59,26 +60,25 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
private FormatTrackingHSSFListener formatListener;
private List<String> records;
private boolean notAllEmpty = false;
private List<Sheet> sheets = new ArrayList<Sheet>();
private List<ReadSheet> sheets = new ArrayList<ReadSheet>();
private HSSFWorkbook stubWorkbook;
private List<XlsRecordHandler> recordHandlers = new ArrayList<XlsRecordHandler>();
private AnalysisContext analysisContext;
public XlsSaxAnalyser(AnalysisContext context) throws IOException {
this.analysisContext = context;
this.records = new ArrayList<String>();
context.setCurrentRowNum(0);
this.fs = new POIFSFileSystem(analysisContext.getInputStream());
ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder();
if (readWorkbookHolder.getFile() != null) {
this.fs = new POIFSFileSystem(readWorkbookHolder.getFile());
} else {
this.fs = new POIFSFileSystem(readWorkbookHolder.getInputStream());
}
@Override
public List<Sheet> getSheets() {
return sheets;
}
@Override
public List<Sheet> sheetList() {
return null;
public List<ReadSheet> sheetList() {
return sheets;
}
@Override
@ -112,10 +112,11 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
lastColumnNumber = 0;
records = new ArrayList<String>();
notAllEmpty = false;
sheets = new ArrayList<Sheet>();
sheets = new ArrayList<ReadSheet>();
buildXlsRecordHandlers();
}
@Override
public void processRecord(Record record) {
int thisRow = -1;
int thisColumn = -1;
@ -129,10 +130,9 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
break;
}
}
// If we got something to print out, do so
if (thisStr != null) {
if (analysisContext.trim()) {
if (analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
thisStr = thisStr.trim();
}
if (!"".equals(thisStr)) {
@ -165,9 +165,9 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelExecutor {
if (lastColumnNumber == -1) {
lastColumnNumber = 0;
}
analysisContext.setCurrentRowNum(row);
if (notAllEmpty) {
notify(new EachRowAnalysisFinishEvent(new ArrayList<String>(records)));
analysisContext.readSheetHolder()
.notifyEndOneRow(new EachRowAnalysisFinishEvent(new ArrayList<String>(records)), analysisContext);
}
records.clear();
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;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.write.metadata.Sheet;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.Record;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.metadata.ReadSheet;
public class BOFRecordHandler extends AbstractXlsRecordHandler {
private List<BoundSheetRecord> boundSheetRecords = new ArrayList<BoundSheetRecord>();
private BoundSheetRecord[] orderedBSRs;
private int sheetIndex;
private List<Sheet> sheets;
private List<ReadSheet> sheets;
private AnalysisContext context;
private boolean analyAllSheet;
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.workbookBuildingListener = workbookBuildingListener;
this.sheets = sheets;
}
@Override
public boolean support(Record record) {
return BoundSheetRecord.sid == record.getSid() || BOFRecord.sid == record.getSid();
@ -40,12 +44,10 @@ public class BOFRecordHandler extends AbstractXlsRecordHandler {
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
}
sheetIndex++;
Sheet sheet = new Sheet(sheetIndex, 0);
sheet.setSheetName(orderedBSRs[sheetIndex - 1].getSheetname());
sheets.add(sheet);
ReadSheet readSheet = new ReadSheet(sheetIndex, orderedBSRs[sheetIndex - 1].getSheetname());
sheets.add(readSheet);
if (this.analyAllSheet) {
context.setCurrentSheet(sheet);
context.currentSheet(null, readSheet);
}
}
}
@ -53,7 +55,7 @@ public class BOFRecordHandler extends AbstractXlsRecordHandler {
@Override
public void init() {
if (context.getCurrentSheet() == null) {
if (context.readSheetHolder() == null) {
this.analyAllSheet = true;
}
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.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.write.metadata.Sheet;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder;
import com.alibaba.excel.util.FileUtils;
/**
@ -36,82 +36,85 @@ import com.alibaba.excel.util.FileUtils;
*/
public class XlsxSaxAnalyser implements ExcelExecutor {
private AnalysisContext analysisContext;
private List<Sheet> sheetList;
private List<ReadSheet> sheetList;
private Map<Integer, InputStream> sheetMap;
public XlsxSaxAnalyser(AnalysisContext analysisContext) throws Exception {
this.analysisContext = analysisContext;
analysisContext.setCurrentRowNum(0);
WorkbookHolder workbookHolder = analysisContext.currentWorkbookHolder();
if (workbookHolder.getReadCache() == null) {
workbookHolder.setReadCache(new Ehcache());
// Initialize cache
ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder();
if (readWorkbookHolder.getReadCache() == null) {
readWorkbookHolder.setReadCache(new Ehcache());
}
workbookHolder.getReadCache().init(analysisContext);
readWorkbookHolder.getReadCache().init(analysisContext);
OPCPackage pkg = readOpcPackage(workbookHolder);
OPCPackage pkg = readOpcPackage(readWorkbookHolder);
// Analysis sharedStringsTable.xml
analysisSharedStringsTable(pkg, workbookHolder);
analysisSharedStringsTable(pkg, readWorkbookHolder);
XSSFReader xssfReader = new XSSFReader(pkg);
analysisUse1904WindowDate(xssfReader, workbookHolder);
analysisUse1904WindowDate(xssfReader, readWorkbookHolder);
sheetList = new ArrayList<Sheet>();
sheetList = new ArrayList<ReadSheet>();
sheetMap = new HashMap<Integer, InputStream>();
XSSFReader.SheetIterator ite = (XSSFReader.SheetIterator)xssfReader.getSheetsData();
int index = 0;
if (!ite.hasNext()) {
throw new ExcelAnalysisException("Can not find any sheet!");
}
while (ite.hasNext()) {
InputStream inputStream = ite.next();
Sheet sheet = new Sheet();
sheet.setSheetNo(index);
sheet.setSheetName(ite.getSheetName());
sheetList.add(sheet);
sheetList.add(new ReadSheet(index, ite.getSheetName()));
sheetMap.put(index, inputStream);
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();
WorkbookDocument ctWorkbook = WorkbookDocument.Factory.parse(workbookXml);
CTWorkbook wb = ctWorkbook.getWorkbook();
CTWorkbookPr prefix = wb.getWorkbookPr();
if (prefix != null && prefix.getDate1904()) {
workbookHolder.setUse1904windowing(Boolean.TRUE);
readWorkbookHolder.getGlobalConfiguration().setUse1904windowing(Boolean.TRUE);
}
}
private void analysisSharedStringsTable(OPCPackage pkg, WorkbookHolder workbookHolder) throws Exception {
ContentHandler handler = new SharedStringsTableHandler(workbookHolder.getReadCache());
private void analysisSharedStringsTable(OPCPackage pkg, ReadWorkbookHolder readWorkbookHolder) throws Exception {
ContentHandler handler = new SharedStringsTableHandler(readWorkbookHolder.getReadCache());
parseXmlSource(pkg.getPartsByContentType(XSSFRelation.SHARED_STRINGS.getContentType()).get(0).getInputStream(),
handler);
workbookHolder.getReadCache().putFinished();
readWorkbookHolder.getReadCache().putFinished();
}
private OPCPackage readOpcPackage(WorkbookHolder workbookHolder) throws Exception {
if (workbookHolder.getFile() != null) {
return OPCPackage.open(workbookHolder.getFile());
private OPCPackage readOpcPackage(ReadWorkbookHolder readWorkbookHolder) throws Exception {
if (readWorkbookHolder.getFile() != null) {
return OPCPackage.open(readWorkbookHolder.getFile());
}
if (workbookHolder.getMandatoryUseInputStream()) {
return OPCPackage.open(workbookHolder.getInputStream());
if (readWorkbookHolder.getMandatoryUseInputStream()) {
return OPCPackage.open(readWorkbookHolder.getInputStream());
}
File readTempFile = FileUtils.createCacheTmpFile();
workbookHolder.setReadTempFile(readTempFile);
readWorkbookHolder.setTempFile(readTempFile);
File tempFile = new File(readTempFile.getPath(), UUID.randomUUID().toString() + ".xlsx");
FileUtils.writeToFile(readTempFile, workbookHolder.getInputStream());
FileUtils.writeToFile(readTempFile, readWorkbookHolder.getInputStream());
return OPCPackage.open(tempFile);
}
@Override
public List<Sheet> sheetList() {
public List<ReadSheet> sheetList() {
return sheetList;
}
@Override
public void execute() {
parseXmlSource(sheetMap.get(analysisContext.currentSheetHolder().getSheetNo()),
parseXmlSource(sheetMap.get(analysisContext.readSheetHolder().getSheetNo()),
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
public void endHandle(String name) {
analysisContext.currentSheetHolder().notifyEndOneRow(
analysisContext.readSheetHolder().notifyEndOneRow(
new EachRowAnalysisFinishEvent(rowResultHandler.getCurRowContent(), rowResultHandler.getColumnSize()),
analysisContext);
rowResultHandler.clearResult();

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

@ -1,6 +1,8 @@
package com.alibaba.excel.context;
import com.alibaba.excel.analysis.ExcelExecutor;
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.ReadSheetHolder;
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder;
@ -15,28 +17,48 @@ public interface AnalysisContext {
/**
* Select the current table
*
* @param excelExecutor
* @param readSheet
*/
void currentSheet(ReadSheet readSheet);
void currentSheet(ExcelExecutor excelExecutor, ReadSheet readSheet);
/**
* All information about the workbook you are currently working on
*
* @return
*/
ReadWorkbookHolder currentWorkbookHolder();
ReadWorkbookHolder readWorkbookHolder();
/**
* All information about the sheet you are currently working on
*
* @return
*/
ReadSheetHolder currentSheetHolder();
ReadSheetHolder readSheetHolder();
/**
* Set row of currently operated cell
*
* @param readRowHolder
*/
void readRowHolder(ReadRowHolder readRowHolder);
/**
* Row of currently operated cell
*
* @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.LoggerFactory;
import com.alibaba.excel.write.metadata.holder.SheetHolder;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder;
import com.alibaba.excel.write.metadata.Sheet;
import com.alibaba.excel.write.metadata.Workbook;
import com.alibaba.excel.analysis.ExcelExecutor;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.read.metadata.ReadSheet;
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
*/
private WorkbookHolder currentWorkbookHolder;
private ReadWorkbookHolder readWorkbookHolder;
/**
* 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) {
if (workbook == null) {
public AnalysisContextImpl(ReadWorkbook readWorkbook) {
if (readWorkbook == null) {
throw new IllegalArgumentException("Workbook argument cannot be null");
}
currentWorkbookHolder = WorkbookHolder.buildReadWorkbookHolder(workbook);
readWorkbookHolder = new ReadWorkbookHolder(readWorkbook);
currentReadHolder = readWorkbookHolder;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Initialization 'AnalysisContextImpl' complete");
}
}
@Override
public void currentSheet(Sheet sheet) {
if (sheet == null) {
public void currentSheet(ExcelExecutor excelExecutor, ReadSheet readSheet) {
if (readSheet == null) {
throw new IllegalArgumentException("Sheet argument cannot be null");
}
if (sheet.getSheetNo() == null || sheet.getSheetNo() <= 0) {
sheet.setSheetNo(0);
}
currentSheetHolder = SheetHolder.buildReadWorkSheetHolder(sheet, currentWorkbookHolder);
readSheetHolder = new ReadSheetHolder(readSheet, readWorkbookHolder);
currentReadHolder = readSheetHolder;
selectSheet(excelExecutor);
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;
import com.alibaba.excel.write.metadata.Table;
import com.alibaba.excel.write.metadata.holder.WriteConfiguration;
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.metadata.Sheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.holder.WriteHolder;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* Write context
@ -16,44 +16,44 @@ public interface WriteContext {
/**
* 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
*
* @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
*/
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
*/
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
*/
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
*/
TableHolder currentTableHolder();
WriteHolder currentWriteHolder();
/**
* close

223
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.metadata.Head;
import com.alibaba.excel.metadata.property.ExcelHeadProperty;
import com.alibaba.excel.util.WorkBookUtil;
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.metadata.Table;
import com.alibaba.excel.write.metadata.Workbook;
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.metadata.holder.WriteConfiguration;
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 com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
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.
@ -39,31 +40,31 @@ public class WriteContextImpl implements WriteContext {
/**
* The Workbook currently written
*/
private WorkbookHolder currentWorkbookHolder;
private WriteWorkbookHolder writeWorkbookHolder;
/**
* Current sheet holder
*/
private SheetHolder currentSheetHolder;
private WriteSheetHolder writeSheetHolder;
/**
* The table currently written
*/
private TableHolder currentTableHolder;
private WriteTableHolder writeTableHolder;
/**
* Configuration of currently operated cell
*/
private WriteConfiguration currentWriteConfiguration;
private WriteHolder currentWriteHolder;
public WriteContextImpl(Workbook workbook) {
if (workbook == null) {
public WriteContextImpl(WriteWorkbook writeWorkbook) {
if (writeWorkbook == null) {
throw new IllegalArgumentException("Workbook argument cannot be null");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Begin to Initialization 'WriteContextImpl'");
}
initCurrentWorkbookHolder(workbook);
initCurrentWorkbookHolder(writeWorkbook);
beforeWorkbookCreate();
try {
currentWorkbookHolder.setWorkbook(WorkBookUtil.createWorkBook(currentWorkbookHolder));
writeWorkbookHolder.setWorkbook(WorkBookUtil.createWorkBook(writeWorkbookHolder));
} catch (Exception e) {
throw new ExcelGenerateException("Create workbook failure", e);
}
@ -74,7 +75,7 @@ public class WriteContextImpl implements WriteContext {
}
private void beforeWorkbookCreate() {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(WorkbookWriteHandler.class);
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(WorkbookWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
@ -86,159 +87,159 @@ public class WriteContextImpl implements WriteContext {
}
private void afterWorkbookCreate() {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(WorkbookWriteHandler.class);
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(WorkbookWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof WorkbookWriteHandler) {
((WorkbookWriteHandler)writeHandler).afterWorkbookCreate(currentWorkbookHolder);
((WorkbookWriteHandler)writeHandler).afterWorkbookCreate(writeWorkbookHolder);
}
}
}
private void initCurrentWorkbookHolder(Workbook workbook) {
currentWorkbookHolder = new WorkbookHolder(workbook);
currentWriteConfiguration = currentWorkbookHolder;
private void initCurrentWorkbookHolder(WriteWorkbook writeWorkbook) {
writeWorkbookHolder = new WriteWorkbookHolder(writeWorkbook);
currentWriteHolder = writeWorkbookHolder;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CurrentConfiguration is currentWorkbookHolder");
LOGGER.debug("CurrentConfiguration is writeWorkbookHolder");
}
}
/**
* @param sheet
* @param writeSheet
*/
@Override
public void currentSheet(com.alibaba.excel.write.metadata.Sheet sheet) {
if (sheet == null) {
public void currentSheet(WriteSheet writeSheet) {
if (writeSheet == 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");
sheet.setSheetNo(0);
writeSheet.setSheetNo(0);
}
if (currentWorkbookHolder.getHasBeenInitializedSheet().containsKey(sheet.getSheetNo())) {
if (writeWorkbookHolder.getHasBeenInitializedSheet().containsKey(writeSheet.getSheetNo())) {
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());
currentSheetHolder.setNewInitialization(Boolean.FALSE);
currentTableHolder = null;
currentWriteConfiguration = currentSheetHolder;
writeSheetHolder = writeWorkbookHolder.getHasBeenInitializedSheet().get(writeSheet.getSheetNo());
writeSheetHolder.setNewInitialization(Boolean.FALSE);
writeTableHolder = null;
currentWriteHolder = writeSheetHolder;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CurrentConfiguration is currentSheetHolder");
LOGGER.debug("CurrentConfiguration is writeSheetHolder");
}
return;
}
initCurrentSheetHolder(sheet);
initCurrentSheetHolder(writeSheet);
beforeSheetCreate();
// Initialization current sheet
initSheet(sheet);
initSheet();
afterSheetCreate();
}
private void beforeSheetCreate() {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(SheetWriteHandler.class);
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(SheetWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof SheetWriteHandler) {
((SheetWriteHandler)writeHandler).beforeSheetCreate(currentWorkbookHolder, currentSheetHolder);
((SheetWriteHandler)writeHandler).beforeSheetCreate(writeWorkbookHolder, writeSheetHolder);
}
}
}
private void afterSheetCreate() {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(SheetWriteHandler.class);
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(SheetWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof SheetWriteHandler) {
((SheetWriteHandler)writeHandler).afterSheetCreate(currentWorkbookHolder, currentSheetHolder);
((SheetWriteHandler)writeHandler).afterSheetCreate(writeWorkbookHolder, writeSheetHolder);
}
}
if (null != currentWorkbookHolder.getWriteHandler()) {
currentWorkbookHolder.getWriteHandler().sheet(currentSheetHolder.getSheetNo(),
currentSheetHolder.getSheet());
if (null != writeWorkbookHolder.getWriteWorkbook().getWriteHandler()) {
writeWorkbookHolder.getWriteWorkbook().getWriteHandler().sheet(writeSheetHolder.getSheetNo(),
writeSheetHolder.getSheet());
}
}
private void initCurrentSheetHolder(com.alibaba.excel.write.metadata.Sheet sheet) {
currentSheetHolder = new SheetHolder(sheet, currentWorkbookHolder);
currentWorkbookHolder.getHasBeenInitializedSheet().put(sheet.getSheetNo(), currentSheetHolder);
currentTableHolder = null;
currentWriteConfiguration = currentSheetHolder;
private void initCurrentSheetHolder(WriteSheet writeSheet) {
writeSheetHolder = new WriteSheetHolder(writeSheet, writeWorkbookHolder);
writeWorkbookHolder.getHasBeenInitializedSheet().put(writeSheet.getSheetNo(), writeSheetHolder);
writeTableHolder = null;
currentWriteHolder = writeSheetHolder;
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;
try {
currentSheet = currentWorkbookHolder.getWorkbook().getSheetAt(sheet.getSheetNo());
currentSheet = writeWorkbookHolder.getWorkbook().getSheetAt(writeSheetHolder.getSheetNo());
} catch (Exception e) {
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
initHead(currentSheetHolder.getExcelHeadProperty());
initHead(writeSheetHolder.excelWriteHeadProperty());
}
public void initHead(ExcelHeadProperty excelHeadProperty) {
if (!currentWriteConfiguration.needHead() || !currentSheetHolder.getExcelHeadProperty().hasHead()) {
public void initHead(ExcelWriteHeadProperty excelWriteHeadProperty) {
if (!currentWriteHolder.needHead() || !currentWriteHolder.excelWriteHeadProperty().hasHead()) {
return;
}
int lastRowNum = currentSheetHolder.getSheet().getLastRowNum();
int rowIndex = lastRowNum + currentWriteConfiguration.writeRelativeHeadRowIndex();
int lastRowNum = writeSheetHolder.getSheet().getLastRowNum();
int rowIndex = lastRowNum + currentWriteHolder.relativeHeadRowIndex();
// Combined head
addMergedRegionToCurrentSheet(excelHeadProperty, rowIndex);
for (int relativeRowIndex = 0, i = rowIndex; i < excelHeadProperty.getHeadRowNumber() + rowIndex;
addMergedRegionToCurrentSheet(excelWriteHeadProperty, rowIndex);
for (int relativeRowIndex = 0, i = rowIndex; i < excelWriteHeadProperty.getHeadRowNumber() + rowIndex;
i++, relativeRowIndex++) {
beforeRowCreate(rowIndex, relativeRowIndex);
Row row = WorkBookUtil.createRow(currentSheetHolder.getSheet(), i);
Row row = WorkBookUtil.createRow(writeSheetHolder.getSheet(), i);
afterRowCreate(row, relativeRowIndex);
addOneRowOfHeadDataToExcel(row, excelHeadProperty.getHeadMap(), relativeRowIndex);
addOneRowOfHeadDataToExcel(row, excelWriteHeadProperty.getHeadMap(), 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()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).beforeRowCreate(currentSheetHolder, currentTableHolder, rowIndex,
((RowWriteHandler)writeHandler).beforeRowCreate(writeSheetHolder, writeTableHolder, rowIndex,
relativeRowIndex, true);
}
}
}
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()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).afterRowCreate(currentSheetHolder, currentTableHolder, row,
((RowWriteHandler)writeHandler).afterRowCreate(writeSheetHolder, writeTableHolder, row,
relativeRowIndex, true);
}
}
if (null != currentWorkbookHolder.getWriteHandler()) {
currentWorkbookHolder.getWriteHandler().row(row.getRowNum(), row);
if (null != writeWorkbookHolder.getWriteWorkbook().getWriteHandler()) {
writeWorkbookHolder.getWriteWorkbook().getWriteHandler().row(row.getRowNum(), row);
}
}
private void addMergedRegionToCurrentSheet(ExcelHeadProperty excelHeadProperty, int rowIndex) {
for (com.alibaba.excel.metadata.CellRange cellRangeModel : excelHeadProperty.headCellRangeList()) {
currentSheetHolder.getSheet().addMergedRegion(new CellRangeAddress(cellRangeModel.getFirstRow() + rowIndex,
private void addMergedRegionToCurrentSheet(ExcelWriteHeadProperty excelWriteHeadProperty, int rowIndex) {
for (com.alibaba.excel.metadata.CellRange cellRangeModel : excelWriteHeadProperty.headCellRangeList()) {
writeSheetHolder.getSheet().addMergedRegion(new CellRangeAddress(cellRangeModel.getFirstRow() + rowIndex,
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) {
List<WriteHandler> handlerList = currentWriteConfiguration.writeHandlerMap().get(CellWriteHandler.class);
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(CellWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof CellWriteHandler) {
((CellWriteHandler)writeHandler).beforeCellCreate(currentSheetHolder, currentTableHolder, row, head,
((CellWriteHandler)writeHandler).beforeCellCreate(writeSheetHolder, writeTableHolder, row, head,
relativeRowIndex, true);
}
}
}
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()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof CellWriteHandler) {
((CellWriteHandler)writeHandler).afterCellCreate(currentSheetHolder, currentTableHolder, cell, head,
((CellWriteHandler)writeHandler).afterCellCreate(writeSheetHolder, writeTableHolder, cell, head,
relativeRowIndex, true);
}
}
if (null != currentWorkbookHolder.getWriteHandler()) {
currentWorkbookHolder.getWriteHandler().cell(cell.getRowIndex(), cell);
if (null != writeWorkbookHolder.getWriteWorkbook().getWriteHandler()) {
writeWorkbookHolder.getWriteWorkbook().getWriteHandler().cell(cell.getRowIndex(), cell);
}
}
@Override
public void currentTable(Table table) {
if (table == null) {
public void currentTable(WriteTable writeTable) {
if (writeTable == null) {
return;
}
if (table.getTableNo() == null || table.getTableNo() <= 0) {
table.setTableNo(0);
if (writeTable.getTableNo() == null || writeTable.getTableNo() <= 0) {
writeTable.setTableNo(0);
}
if (currentSheetHolder.getHasBeenInitializedTable().containsKey(table.getTableNo())) {
if (writeSheetHolder.getHasBeenInitializedTable().containsKey(writeTable.getTableNo())) {
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());
currentTableHolder.setNewInitialization(Boolean.FALSE);
currentWriteConfiguration = currentTableHolder;
writeTableHolder = writeSheetHolder.getHasBeenInitializedTable().get(writeTable.getTableNo());
writeTableHolder.setNewInitialization(Boolean.FALSE);
currentWriteHolder = writeTableHolder;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CurrentConfiguration is currentTableHolder");
LOGGER.debug("CurrentConfiguration is writeTableHolder");
}
return;
}
initCurrentTableHolder(table);
initHead(currentTableHolder.getExcelHeadProperty());
initCurrentTableHolder(writeTable);
initHead(writeTableHolder.excelWriteHeadProperty());
}
private void initCurrentTableHolder(Table table) {
currentTableHolder = new TableHolder(table, currentSheetHolder, currentWorkbookHolder);
currentSheetHolder.getHasBeenInitializedTable().put(table.getTableNo(), currentTableHolder);
currentWriteConfiguration = currentTableHolder;
private void initCurrentTableHolder(WriteTable writeTable) {
writeTableHolder = new WriteTableHolder(writeTable, writeSheetHolder, writeWorkbookHolder);
writeSheetHolder.getHasBeenInitializedTable().put(writeTable.getTableNo(), writeTableHolder);
currentWriteHolder = writeTableHolder;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CurrentConfiguration is currentTableHolder");
LOGGER.debug("CurrentConfiguration is writeTableHolder");
}
}
@Override
public WriteConfiguration currentConfiguration() {
return currentWriteConfiguration;
public WriteWorkbookHolder writeWorkbookHolder() {
return writeWorkbookHolder;
}
@Override
public WorkbookHolder currentWorkbookHolder() {
return currentWorkbookHolder;
public WriteSheetHolder writeSheetHolder() {
return writeSheetHolder;
}
@Override
public SheetHolder currentSheetHolder() {
return currentSheetHolder;
public WriteTableHolder writeTableHolder() {
return writeTableHolder;
}
@Override
public TableHolder currentTableHolder() {
return currentTableHolder;
public WriteHolder currentWriteHolder() {
return currentWriteHolder;
}
@Override
public void finish() {
try {
currentWorkbookHolder.getWorkbook().write(currentWorkbookHolder.getOutputStream());
currentWorkbookHolder.getWorkbook().close();
if (currentWorkbookHolder.getAutoCloseStream()) {
if (currentWorkbookHolder.getOutputStream() != null) {
currentWorkbookHolder.getOutputStream().close();
}
if (currentWorkbookHolder.getTemplateInputStream() != null) {
currentWorkbookHolder.getTemplateInputStream().close();
writeWorkbookHolder.getWorkbook().write(writeWorkbookHolder.getOutputStream());
writeWorkbookHolder.getWorkbook().close();
if (writeWorkbookHolder.getAutoCloseStream()) {
if (writeWorkbookHolder.getOutputStream() != null) {
writeWorkbookHolder.getOutputStream().close();
}
if (writeWorkbookHolder.getTemplateInputStream() != null) {
writeWorkbookHolder.getTemplateInputStream().close();
}
}
} 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}
*/
private Boolean booleanValue;
/**
* Support only when reading
*/
private Boolean readIsFormula;
/**
* Support only when reading
*/
private String readFormula;
private Boolean formula;
private String formulaValue;
public CellData(String stringValue) {
this(CellDataTypeEnum.STRING, stringValue);
@ -44,7 +37,7 @@ public class CellData {
}
this.type = type;
this.stringValue = stringValue;
this.readIsFormula = Boolean.FALSE;
this.formula = Boolean.FALSE;
}
public CellData(Double doubleValue) {
@ -53,7 +46,7 @@ public class CellData {
}
this.type = CellDataTypeEnum.NUMBER;
this.doubleValue = doubleValue;
this.readIsFormula = Boolean.FALSE;
this.formula = Boolean.FALSE;
}
public CellData(Boolean booleanValue) {
@ -62,7 +55,7 @@ public class CellData {
}
this.type = CellDataTypeEnum.BOOLEAN;
this.booleanValue = booleanValue;
this.readIsFormula = Boolean.FALSE;
this.formula = Boolean.FALSE;
}
public CellData(CellDataTypeEnum type) {
@ -70,7 +63,7 @@ public class CellData {
throw new IllegalArgumentException("Type can not be null");
}
this.type = type;
this.readIsFormula = Boolean.FALSE;
this.formula = Boolean.FALSE;
}
public CellDataTypeEnum getType() {
@ -105,20 +98,20 @@ public class CellData {
this.booleanValue = booleanValue;
}
public Boolean getReadIsFormula() {
return readIsFormula;
public Boolean getFormula() {
return formula;
}
public void setReadIsFormula(Boolean readIsFormula) {
this.readIsFormula = readIsFormula;
public void setFormula(Boolean formula) {
this.formula = formula;
}
public String getReadFormula() {
return readFormula;
public String getFormulaValue() {
return formulaValue;
}
public void setReadFormula(String readFormula) {
this.readFormula = readFormula;
public void setFormulaValue(String formulaValue) {
this.formulaValue = formulaValue;
}
@Override

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

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

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

@ -4,7 +4,9 @@ import java.util.List;
/**
* @author jipengfei
* @deprecated please use {@link com.alibaba.excel.write.metadata.WriteTable}
*/
@Deprecated
public class Table {
/**
*/
@ -22,6 +24,10 @@ public class Table {
*/
private TableStyle tableStyle;
public Table(Integer tableNo) {
this.tableNo = tableNo;
}
public TableStyle getTableStyle() {
return tableStyle;
}
@ -30,10 +36,6 @@ public class Table {
this.tableStyle = tableStyle;
}
public Table(Integer tableNo) {
this.tableNo = tableNo;
}
public Class<? extends BaseRowModel> getClazz() {
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;
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
@ -11,11 +24,227 @@ public class ExcelReaderBuilder {
/**
* Workbook
*/
private Workbook workbook;
private ReadWorkbook readWorkbook;
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.enums.CellDataTypeEnum;
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.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.read.metadata.holder.ReadHolder;
import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty;
import net.sf.cglib.beans.BeanMap;
@ -25,40 +25,38 @@ import net.sf.cglib.beans.BeanMap;
*
* @author jipengfei
*/
public class ModelBuildEventListener extends AnalysisEventListener<List<CellData>> {
@Override
public void onException(Exception exception, AnalysisContext context) throws Exception {}
public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener<List<CellData>> {
@Override
public void invoke(List<CellData> data, AnalysisContext context) {
ReadConfiguration readConfiguration = context.currentConfiguration();
if (HeadKindEnum.CLASS.equals(context.currentSheetHolder().getExcelHeadProperty().getHeadKind())) {
context.setCurrentRowAnalysisResult(buildUserModel(data, readConfiguration));
ReadHolder currentReadHolder = context.currentReadHolder();
if (HeadKindEnum.CLASS.equals(currentReadHolder.excelReadHeadProperty().getHeadKind())) {
context.readRowHolder().setCurrentRowAnalysisResult(buildUserModel(data, currentReadHolder));
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>();
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;
}
private Object buildUserModel(List<CellData> data, ReadConfiguration readConfiguration) {
ExcelHeadProperty excelHeadProperty = readConfiguration.excelHeadProperty();
private Object buildUserModel(List<CellData> data, ReadHolder currentReadHolder) {
ExcelReadHeadProperty excelReadHeadProperty = currentReadHolder.excelReadHeadProperty();
Object resultModel;
try {
resultModel = excelHeadProperty.getHeadClazz().newInstance();
resultModel = excelReadHeadProperty.getHeadClazz().newInstance();
} catch (Exception e) {
throw new ExcelDataConvertException("Can not instance class: " + excelHeadProperty.getHeadClazz().getName(),
e);
throw new ExcelDataConvertException(
"Can not instance class: " + excelReadHeadProperty.getHeadClazz().getName(), e);
}
Map<String, Object> map = new HashMap<String, Object>();
Map<Integer, Head> headMap = excelHeadProperty.getHeadMap();
Map<Integer, ExcelContentProperty> contentPropertyMap = excelHeadProperty.getContentPropertyMap();
Map<Integer, Head> headMap = excelReadHeadProperty.getHeadMap();
Map<Integer, ExcelContentProperty> contentPropertyMap = excelReadHeadProperty.getContentPropertyMap();
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
Integer index = entry.getKey();
if (index >= data.size()) {
@ -70,7 +68,7 @@ public class ModelBuildEventListener extends AnalysisEventListener<List<CellData
}
ExcelContentProperty excelContentProperty = contentPropertyMap.get(index);
Object value = convertValue(cellData, excelContentProperty.getField().getClass(), excelContentProperty,
readConfiguration.readConverterMap());
currentReadHolder.converterMap());
if (value != null) {
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 {
/**
* 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 context

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

@ -15,6 +15,17 @@ public class ReadSheet extends ReadBasicParameter {
*/
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() {
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.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;
/**
@ -27,14 +30,25 @@ public class ReadWorkbook extends ReadBasicParameter {
* 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;
/**
* 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.
* <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;
}
public Object getCustomObject() {
return customObject;
}
public void setCustomObject(Object customObject) {
this.customObject = customObject;
}
public Boolean getMandatoryUseInputStream() {
return mandatoryUseInputStream;
}
@ -85,6 +107,14 @@ public class ReadWorkbook extends ReadBasicParameter {
this.mandatoryUseInputStream = mandatoryUseInputStream;
}
public ReadCache getReadCache() {
return readCache;
}
public void setReadCache(ReadCache readCache) {
this.readCache = readCache;
}
public Boolean getConvertAllFiled() {
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.ConverterKey;
import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
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.Head;
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.ReadListenerRegistryCenter;
import com.alibaba.excel.read.listener.event.AnalysisFinishEvent;
@ -77,6 +79,10 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
} else {
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
&& !readBasicParameter.getCustomReadListenerList().isEmpty()) {
this.readListenerList.addAll(readBasicParameter.getCustomReadListenerList());
@ -103,11 +109,12 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
@Override
public void notifyEndOneRow(AnalysisFinishEvent event, AnalysisContext analysisContext) {
List<CellData> cellDataList = (List<CellData>)event.getAnalysisResult();
if (analysisContext.currentRowHolder().getRow().getRowNum() > analysisContext.currentSheetHolder()
.getReadHeadRowNumber()) {
ReadRowHolder readRowHolder = analysisContext.readRowHolder();
if (readRowHolder.getRowIndex() >= analysisContext.readSheetHolder().getHeadRowNumber()) {
for (ReadListener readListener : readListenerList) {
try {
readListener.invoke(analysisContext.currentRowAnalysisResult(), analysisContext);
readListener.invoke(readRowHolder.getCurrentRowAnalysisResult(), analysisContext);
} catch (Exception e) {
for (ReadListener readListenerException : readListenerList) {
try {
@ -118,9 +125,10 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
}
}
}
return;
}
// Now is header
if (analysisContext.currentRowNum().equals(analysisContext.currentSheetHolder().getReadHeadRowNumber())) {
if (analysisContext.readSheetHolder().getHeadRowNumber().equals(readRowHolder.getRowIndex() + 1)) {
buildHead(analysisContext, cellDataList);
}
}
@ -133,11 +141,11 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
}
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;
}
List<String> dataList = (List<String>)buildStringList(cellDataList, analysisContext.currentConfiguration());
ExcelReadHeadProperty excelHeadPropertyData = analysisContext.currentConfiguration().excelReadHeadProperty();
List<String> dataList = (List<String>)buildStringList(cellDataList, analysisContext.currentReadHolder());
ExcelReadHeadProperty excelHeadPropertyData = analysisContext.readSheetHolder().excelReadHeadProperty();
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);
@ -156,7 +164,7 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
if (StringUtils.isEmpty(headString)) {
continue;
}
if (analysisContext.currentSheetHolder().getAutoTrim()) {
if (analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
headString = headString.trim();
}
if (headName.equals(headString)) {
@ -171,12 +179,11 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
excelHeadPropertyData.setContentPropertyMap(tmpContentPropertyMap);
}
private Object buildStringList(List<CellData> data,
com.alibaba.excel.read.metadata.read.ReadConfiguration readConfiguration) {
private Object buildStringList(List<CellData> data, ReadHolder readHolder) {
List<String> list = new ArrayList<String>();
for (CellData cellData : data) {
Converter converter = readConfiguration.readConverterMap()
.get(ConverterKey.buildConverterKey(String.class, cellData.getType()));
Converter converter =
readHolder.converterMap().get(ConverterKey.buildConverterKey(String.class, cellData.getType()));
if (converter == null) {
throw new ExcelDataConvertException(
"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;
import org.apache.poi.ss.usermodel.Row;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.Holder;
@ -12,11 +10,6 @@ import com.alibaba.excel.metadata.Holder;
* @author zhuangjiaju
*/
public class ReadRowHolder implements Holder {
/***
* poi row
*/
private Row row;
/**
* Some global variables
*/
@ -26,17 +19,9 @@ public class ReadRowHolder implements Holder {
*/
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;
public Row getRow() {
return row;
}
public void setRow(Row row) {
this.row = row;
}
private int rowIndex;
public GlobalConfiguration getGlobalConfiguration() {
return globalConfiguration;
@ -54,12 +39,12 @@ public class ReadRowHolder implements Holder {
this.currentRowAnalysisResult = currentRowAnalysisResult;
}
public int getRelativeRowIndex() {
return relativeRowIndex;
public int getRowIndex() {
return rowIndex;
}
public void setRelativeRowIndex(int relativeRowIndex) {
this.relativeRowIndex = relativeRowIndex;
public void setRowIndex(int rowIndex) {
this.rowIndex = rowIndex;
}
@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;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.poifs.filesystem.FileMagic;
import com.alibaba.excel.exception.ExcelCommonException;
/**
* @author jipengfei
*/
public enum ExcelTypeEnum {
XLS(".xls"), XLSX(".xlsx");
/**
* xls
*/
XLS(".xls"),
/**
* xlsx
*/
XLSX(".xlsx");
private String value;
@ -18,22 +27,26 @@ public enum ExcelTypeEnum {
this.setValue(value);
}
public static ExcelTypeEnum valueOf(InputStream inputStream) {
public static ExcelTypeEnum valueOf(File file, InputStream inputStream) {
try {
if (!inputStream.markSupported()) {
return null;
FileMagic fileMagic = null;
if (file != null) {
fileMagic = FileMagic.valueOf(file);
} else {
fileMagic = FileMagic.valueOf(inputStream);
}
FileMagic fileMagic = FileMagic.valueOf(inputStream);
if (FileMagic.OLE2.equals(fileMagic)) {
return XLS;
}
if (FileMagic.OOXML.equals(fileMagic)) {
return XLSX;
}
return null;
} 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() {

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.usermodel.XSSFWorkbook;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder;
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 static Workbook createWorkBook(WorkbookHolder workbookHolder)
public static Workbook createWorkBook(WriteWorkbookHolder writeWorkbookHolder)
throws IOException, InvalidFormatException {
if (ExcelTypeEnum.XLSX.equals(workbookHolder.getExcelType())) {
if (workbookHolder.getFile() != null) {
return new SXSSFWorkbook(new XSSFWorkbook(workbookParam.getFile()));
if (ExcelTypeEnum.XLSX.equals(writeWorkbookHolder.getExcelType())) {
if (writeWorkbookHolder.getTemplateFile() != null) {
return new SXSSFWorkbook(new XSSFWorkbook(writeWorkbookHolder.getTemplateFile()));
}
if (workbookParam.getInputStream() != null) {
return new SXSSFWorkbook(new XSSFWorkbook(workbookParam.getInputStream()));
if (writeWorkbookHolder.getTemplateInputStream() != null) {
return new SXSSFWorkbook(new XSSFWorkbook(writeWorkbookHolder.getTemplateInputStream()));
}
return new SXSSFWorkbook(500);
}
if (workbookParam.getFile() != null) {
return new HSSFWorkbook(new POIFSFileSystem(workbookParam.getFile()));
if (writeWorkbookHolder.getTemplateFile() != null) {
return new HSSFWorkbook(new POIFSFileSystem(writeWorkbookHolder.getTemplateFile()));
}
if (workbookParam.getInputStream() != null) {
return new HSSFWorkbook(new POIFSFileSystem(workbookParam.getInputStream()));
if (writeWorkbookHolder.getTemplateInputStream() != null) {
return new HSSFWorkbook(new POIFSFileSystem(writeWorkbookHolder.getTemplateInputStream()));
}
return new HSSFWorkbook();
}
public static Sheet createSheet(Workbook workbook, com.alibaba.excel.write.metadata.Sheet sheet) {
return workbook.createSheet(sheet.getSheetName() != null ? sheet.getSheetName() : sheet.getSheetNo() + "");
public static Sheet createSheet(Workbook workbook, String sheetName) {
return workbook.createSheet(sheetName);
}
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 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.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
/**
* @author jipengfei
@ -16,24 +16,24 @@ public interface ExcelBuilder {
*
* @param data
* java basic type or java model extend BaseModel
* @param sheetParam
* @param writeSheet
* Write the sheet
* @deprecated please use{@link ExcelBuilder#addContent(List, Sheet, Table)}
* @deprecated please use{@link ExcelBuilder#addContent(List, WriteSheet, WriteTable)}
*/
@Deprecated
void addContent(List data, Sheet sheetParam);
void addContent(List data, WriteSheet writeSheet);
/**
* WorkBook increase value
*
* @param data
* java basic type or java model extend BaseModel
* @param sheetParam
* @param writeSheet
* Write the sheet
* @param table
* @param writeTable
* 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.

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.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
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.metadata.CellData;
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.util.CollectionUtils;
import com.alibaba.excel.util.POITempFile;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.WorkBookUtil;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.RowWriteHandler;
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;
@ -36,20 +37,20 @@ public class ExcelBuilderImpl implements ExcelBuilder {
private WriteContext context;
public ExcelBuilderImpl(Workbook workbook) {
// 初始化时候创建临时缓存目录,用于规避POI在并发写bug
POITempFile.createPOIFilesDirectory();
context = new WriteContextImpl(workbook);
public ExcelBuilderImpl(WriteWorkbook writeWorkbook) {
// Create temporary cache directory at initialization time to avoid POI concurrent write bugs
FileUtils.createPoiFilesDirectory();
context = new WriteContextImpl(writeWorkbook);
}
private void doAddContent(List data) {
if (CollectionUtils.isEmpty(data)) {
return;
}
org.apache.poi.ss.usermodel.Sheet currentSheet = context.currentSheetHolder().getSheet();
Sheet currentSheet = context.writeSheetHolder().getSheet();
int rowNum = currentSheet.getLastRowNum();
if (context.currentConfiguration().isNew()) {
rowNum += context.currentConfiguration().writeRelativeHeadRowIndex();
if (context.currentWriteHolder().isNew()) {
rowNum += context.currentWriteHolder().relativeHeadRowIndex();
}
for (int relativeRowIndex = 0; relativeRowIndex < data.size(); relativeRowIndex++) {
int n = relativeRowIndex + rowNum + 1;
@ -58,14 +59,14 @@ public class ExcelBuilderImpl implements ExcelBuilder {
}
@Override
public void addContent(List data, Sheet sheetParam) {
addContent(data, sheetParam, null);
public void addContent(List data, WriteSheet writeSheet) {
addContent(data, writeSheet, null);
}
@Override
public void addContent(List data, Sheet sheetParam, Table table) {
context.currentSheet(sheetParam);
context.currentTable(table);
public void addContent(List data, WriteSheet writeSheet, WriteTable writeTable) {
context.currentSheet(writeSheet);
context.currentTable(writeTable);
doAddContent(data);
}
@ -77,12 +78,12 @@ public class ExcelBuilderImpl implements ExcelBuilder {
@Override
public void merge(int firstRow, int lastRow, int firstCol, int 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) {
beforeRowCreate(n, relativeRowIndex);
Row row = WorkBookUtil.createRow(context.currentSheetHolder().getSheet(), n);
Row row = WorkBookUtil.createRow(context.writeSheetHolder().getSheet(), n);
afterRowCreate(row, relativeRowIndex);
if (oneRowData instanceof List) {
addBasicTypeToExcel((List)oneRowData, row, relativeRowIndex);
@ -92,33 +93,31 @@ public class ExcelBuilderImpl implements ExcelBuilder {
}
private void beforeRowCreate(int rowIndex, int relativeRowIndex) {
List<WriteHandler> handlerList =
context.currentConfiguration().writeHandlerMap().get(RowWriteHandler.class);
List<WriteHandler> handlerList = context.currentWriteHolder().writeHandlerMap().get(RowWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).beforeRowCreate(context.currentSheetHolder(),
context.currentTableHolder(), rowIndex, relativeRowIndex, false);
((RowWriteHandler)writeHandler).beforeRowCreate(context.writeSheetHolder(), context.writeTableHolder(),
rowIndex, relativeRowIndex, false);
}
}
}
private void afterRowCreate(Row row, int relativeRowIndex) {
List<WriteHandler> handlerList =
context.currentConfiguration().writeHandlerMap().get(RowWriteHandler.class);
List<WriteHandler> handlerList = context.currentWriteHolder().writeHandlerMap().get(RowWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).afterRowCreate(context.currentSheetHolder(),
context.currentTableHolder(), row, relativeRowIndex, false);
((RowWriteHandler)writeHandler).afterRowCreate(context.writeSheetHolder(), context.writeTableHolder(),
row, relativeRowIndex, false);
}
}
if (null != context.currentWorkbookHolder().getWriteHandler()) {
context.currentWorkbookHolder().getWriteHandler().row(row.getRowNum(), row);
if (null != context.writeWorkbookHolder().getWriteWorkbook().getWriteHandler()) {
context.writeWorkbookHolder().getWriteWorkbook().getWriteHandler().row(row.getRowNum(), row);
}
}
@ -126,7 +125,7 @@ public class ExcelBuilderImpl implements ExcelBuilder {
if (CollectionUtils.isEmpty(oneRowData)) {
return;
}
Map<Integer, Head> headMap = context.currentConfiguration().excelHeadProperty().getHeadMap();
Map<Integer, Head> headMap = context.currentWriteHolder().excelWriteHeadProperty().getHeadMap();
int dataIndex = 0;
int cellIndex = 0;
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
@ -154,17 +153,17 @@ public class ExcelBuilderImpl implements ExcelBuilder {
beforeCellCreate(row, head, relativeRowIndex);
Cell cell = WorkBookUtil.createCell(row, cellIndex);
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);
}
private void addJavaObjectToExcel(Object oneRowData, Row row, int relativeRowIndex) {
WriteConfiguration currentWriteConfiguration = context.currentConfiguration();
WriteHolder currentWriteHolder = context.currentWriteHolder();
BeanMap beanMap = BeanMap.create(oneRowData);
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 =
context.currentConfiguration().excelHeadProperty().getContentPropertyMap();
context.currentWriteHolder().excelWriteHeadProperty().getContentPropertyMap();
int cellIndex = 0;
for (Map.Entry<Integer, ExcelContentProperty> entry : contentPropertyMap.entrySet()) {
cellIndex = entry.getKey();
@ -177,7 +176,7 @@ public class ExcelBuilderImpl implements ExcelBuilder {
beforeCellCreate(row, head, relativeRowIndex);
Cell cell = WorkBookUtil.createCell(row, cellIndex);
Object value = beanMap.get(name);
converterAndSet(currentWriteConfiguration, excelContentProperty.getField().getType(), cell, value,
converterAndSet(currentWriteHolder, excelContentProperty.getField().getType(), cell, value,
excelContentProperty);
afterCellCreate(head, cell, relativeRowIndex);
beanMapHandledSet.add(name);
@ -196,49 +195,47 @@ public class ExcelBuilderImpl implements ExcelBuilder {
}
beforeCellCreate(row, null, relativeRowIndex);
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);
}
}
private void beforeCellCreate(Row row, Head head, int relativeRowIndex) {
List<WriteHandler> handlerList =
context.currentConfiguration().writeHandlerMap().get(CellWriteHandler.class);
List<WriteHandler> handlerList = context.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof CellWriteHandler) {
((CellWriteHandler)writeHandler).beforeCellCreate(context.currentSheetHolder(),
context.currentTableHolder(), row, head, relativeRowIndex, false);
((CellWriteHandler)writeHandler).beforeCellCreate(context.writeSheetHolder(),
context.writeTableHolder(), row, head, relativeRowIndex, false);
}
}
}
private void afterCellCreate(Head head, Cell cell, int relativeRowIndex) {
List<WriteHandler> handlerList =
context.currentConfiguration().writeHandlerMap().get(CellWriteHandler.class);
List<WriteHandler> handlerList = context.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof CellWriteHandler) {
((CellWriteHandler)writeHandler).afterCellCreate(context.currentSheetHolder(),
context.currentTableHolder(), cell, head, relativeRowIndex, false);
((CellWriteHandler)writeHandler).afterCellCreate(context.writeSheetHolder(), context.writeTableHolder(),
cell, head, relativeRowIndex, false);
}
}
if (null != context.currentWorkbookHolder().getWriteHandler()) {
context.currentWorkbookHolder().getWriteHandler().cell(cell.getRowIndex(), cell);
if (null != context.writeWorkbookHolder().getWriteWorkbook().getWriteHandler()) {
context.writeWorkbookHolder().getWriteWorkbook().getWriteHandler().cell(cell.getRowIndex(), cell);
}
}
private void converterAndSet(WriteConfiguration currentWriteConfiguration, Class clazz, Cell cell,
Object value, ExcelContentProperty excelContentProperty) {
private void converterAndSet(WriteHolder currentWriteHolder, Class clazz, Cell cell, Object value,
ExcelContentProperty excelContentProperty) {
if (value == null) {
return;
}
Converter converter = currentWriteConfiguration.converterMap().get(clazz);
Converter converter = currentWriteHolder.converterMap().get(clazz);
if (converter == null) {
throw new ExcelDataConvertException(
"Can not find 'Converter' support class " + clazz.getSimpleName() + ".");
@ -255,6 +252,9 @@ public class ExcelBuilderImpl implements ExcelBuilder {
throw new ExcelDataConvertException(
"Convert data:" + value + " return null,at row:" + cell.getRow().getRowNum());
}
if (cellData.getFormula() != null && cellData.getFormula()) {
cell.setCellFormula(cellData.getFormulaValue());
}
switch (cellData.getType()) {
case STRING:
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.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.write.metadata.Workbook;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteWorkbook;
/**
* Build ExcelBuilder
@ -26,35 +25,20 @@ public class ExcelWriterBuilder {
/**
* Workbook
*/
private Workbook workbook;
private WriteWorkbook writeWorkbook;
public ExcelWriterBuilder() {
this.workbook = new Workbook();
}
/**
* 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;
this.writeWorkbook = new WriteWorkbook();
}
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*
* @param writeRelativeHeadRowIndex
* @param relativeHeadRowIndex
* @return
*/
public ExcelWriterBuilder writeRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) {
workbook.setWriteRelativeHeadRowIndex(writeRelativeHeadRowIndex);
public ExcelWriterBuilder relativeHeadRowIndex(Integer relativeHeadRowIndex) {
writeWorkbook.setRelativeHeadRowIndex(relativeHeadRowIndex);
return this;
}
@ -65,7 +49,7 @@ public class ExcelWriterBuilder {
* @return
*/
public ExcelWriterBuilder head(List<List<String>> head) {
workbook.setHead(head);
writeWorkbook.setHead(head);
return this;
}
@ -76,7 +60,7 @@ public class ExcelWriterBuilder {
* @return
*/
public ExcelWriterBuilder head(Class clazz) {
workbook.setClazz(clazz);
writeWorkbook.setClazz(clazz);
return this;
}
@ -84,7 +68,7 @@ public class ExcelWriterBuilder {
* Need Head
*/
public ExcelWriterBuilder needHead(Boolean needHead) {
workbook.setNeedHead(needHead);
writeWorkbook.setNeedHead(needHead);
return this;
}
@ -95,7 +79,7 @@ public class ExcelWriterBuilder {
* @return
*/
public ExcelWriterBuilder autoCloseStream(Boolean autoCloseStream) {
workbook.setAutoCloseStream(autoCloseStream);
writeWorkbook.setAutoCloseStream(autoCloseStream);
return this;
}
@ -111,7 +95,7 @@ public class ExcelWriterBuilder {
*/
@Deprecated
public ExcelWriterBuilder convertAllFiled(Boolean convertAllFiled) {
workbook.setConvertAllFiled(convertAllFiled);
writeWorkbook.setConvertAllFiled(convertAllFiled);
return this;
}
@ -122,10 +106,10 @@ public class ExcelWriterBuilder {
* @return
*/
public ExcelWriterBuilder registerConverter(Converter converter) {
if (workbook.getCustomConverterMap() == null) {
workbook.setCustomConverterMap(new HashMap<Class, Converter>());
if (writeWorkbook.getCustomConverterList() == null) {
writeWorkbook.setCustomConverterList(new ArrayList<Converter>());
}
workbook.getCustomConverterMap().put(converter.supportJavaTypeKey(), converter);
writeWorkbook.getCustomConverterList().add(converter);
return this;
}
@ -136,46 +120,46 @@ public class ExcelWriterBuilder {
* @return
*/
public ExcelWriterBuilder registerWriteHandler(WriteHandler writeHandler) {
if (workbook.getCustomWriteHandlerList() == null) {
workbook.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
if (writeWorkbook.getCustomWriteHandlerList() == null) {
writeWorkbook.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
workbook.getCustomWriteHandlerList().add(writeHandler);
writeWorkbook.getCustomWriteHandlerList().add(writeHandler);
return this;
}
public ExcelWriterBuilder excelType(ExcelTypeEnum excelType) {
workbook.setExcelType(excelType);
writeWorkbook.setExcelType(excelType);
return this;
}
public ExcelWriterBuilder outputFile(OutputStream outputStream) {
workbook.setOutputStream(outputStream);
public ExcelWriterBuilder file(OutputStream outputStream) {
writeWorkbook.setOutputStream(outputStream);
return this;
}
public ExcelWriterBuilder outputFile(File outputFile) {
public ExcelWriterBuilder file(File outputFile) {
try {
return outputFile(new FileOutputStream(outputFile));
return file(new FileOutputStream(outputFile));
} catch (FileNotFoundException e) {
throw new ExcelGenerateException("Can not create file", e);
}
}
public ExcelWriterBuilder outputFile(String outputPathName) {
return outputFile(new File(outputPathName));
public ExcelWriterBuilder file(String outputPathName) {
return file(new File(outputPathName));
}
public ExcelWriterBuilder outputFile(URI outputUri) {
return outputFile(new File(outputUri));
return file(new File(outputUri));
}
public ExcelWriterBuilder withTemplate(InputStream inputStream) {
workbook.setInputStream(inputStream);
public ExcelWriterBuilder withTemplate(InputStream templateInputStream) {
writeWorkbook.setTemplateInputStream(templateInputStream);
return this;
}
public ExcelWriterBuilder withTemplate(File file) {
workbook.setFile(file);
public ExcelWriterBuilder withTemplate(File templateFile) {
writeWorkbook.setTemplateFile(templateFile);
return this;
}
@ -194,11 +178,35 @@ public class ExcelWriterBuilder {
*/
@Deprecated
public ExcelWriterBuilder registerWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) {
workbook.setWriteHandler(writeHandler);
writeWorkbook.setWriteHandler(writeHandler);
return this;
}
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;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.alibaba.excel.ExcelWriter;
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.metadata.WriteSheet;
/**
* Build sheet
@ -14,38 +15,29 @@ import com.alibaba.excel.write.handler.WriteHandler;
* @author zhuangjiaju
*/
public class ExcelWriterSheetBuilder {
private ExcelWriter excelWriter;
/**
* Sheet
*/
private Sheet sheet;
private WriteSheet writeSheet;
public ExcelWriterSheetBuilder() {
this.sheet = new Sheet();
this.writeSheet = new WriteSheet();
}
/**
* 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 ExcelWriterSheetBuilder readHeadRowNumber(Integer readHeadRowNumber) {
sheet.setReadHeadRowNumber(readHeadRowNumber);
return this;
public ExcelWriterSheetBuilder(ExcelWriter excelWriter) {
this.writeSheet = new WriteSheet();
this.excelWriter = excelWriter;
}
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*
* @param writeRelativeHeadRowIndex
* @param relativeHeadRowIndex
* @return
*/
public ExcelWriterSheetBuilder writeRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) {
sheet.setWriteRelativeHeadRowIndex(writeRelativeHeadRowIndex);
public ExcelWriterSheetBuilder relativeHeadRowIndex(Integer relativeHeadRowIndex) {
writeSheet.setRelativeHeadRowIndex(relativeHeadRowIndex);
return this;
}
@ -57,7 +49,7 @@ public class ExcelWriterSheetBuilder {
* @return
*/
public ExcelWriterSheetBuilder head(List<List<String>> head) {
sheet.setHead(head);
writeSheet.setHead(head);
return this;
}
@ -69,7 +61,7 @@ public class ExcelWriterSheetBuilder {
* @return
*/
public ExcelWriterSheetBuilder head(Class clazz) {
sheet.setClazz(clazz);
writeSheet.setClazz(clazz);
return this;
}
@ -77,7 +69,7 @@ public class ExcelWriterSheetBuilder {
* Need Head
*/
public ExcelWriterSheetBuilder needHead(Boolean needHead) {
sheet.setNeedHead(needHead);
writeSheet.setNeedHead(needHead);
return this;
}
@ -88,10 +80,10 @@ public class ExcelWriterSheetBuilder {
* @return
*/
public ExcelWriterSheetBuilder registerConverter(Converter converter) {
if (sheet.getCustomConverterMap() == null) {
sheet.setCustomConverterMap(new HashMap<Class, Converter>());
if (writeSheet.getCustomConverterList() == null) {
writeSheet.setCustomConverterList(new ArrayList<Converter>());
}
sheet.getCustomConverterMap().put(converter.supportJavaTypeKey(), converter);
writeSheet.getCustomConverterList().add(converter);
return this;
}
@ -102,10 +94,10 @@ public class ExcelWriterSheetBuilder {
* @return
*/
public ExcelWriterSheetBuilder registerWriteHandler(WriteHandler writeHandler) {
if (sheet.getCustomWriteHandlerList() == null) {
sheet.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
if (writeSheet.getCustomWriteHandlerList() == null) {
writeSheet.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
sheet.getCustomWriteHandlerList().add(writeHandler);
writeSheet.getCustomWriteHandlerList().add(writeHandler);
return this;
}
@ -116,7 +108,7 @@ public class ExcelWriterSheetBuilder {
* @return
*/
public ExcelWriterSheetBuilder sheetNo(Integer sheetNo) {
sheet.setSheetNo(sheetNo);
writeSheet.setSheetNo(sheetNo);
return this;
}
@ -127,12 +119,32 @@ public class ExcelWriterSheetBuilder {
* @return
*/
public ExcelWriterSheetBuilder sheetName(String sheetName) {
sheet.setSheetName(sheetName);
writeSheet.setSheetName(sheetName);
return this;
}
public Sheet build() {
return sheet;
public WriteSheet build() {
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;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.alibaba.excel.ExcelWriter;
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.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
/**
* Build sheet
@ -14,38 +16,32 @@ import com.alibaba.excel.write.handler.WriteHandler;
* @author zhuangjiaju
*/
public class ExcelWriterTableBuilder {
private ExcelWriter excelWriter;
private WriteSheet writeSheet;
/**
* table
*/
private Table table;
private WriteTable writeTable;
public ExcelWriterTableBuilder() {
this.table = new Table();
this.writeTable = new WriteTable();
}
/**
* 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 ExcelWriterTableBuilder readHeadRowNumber(Integer readHeadRowNumber) {
table.setReadHeadRowNumber(readHeadRowNumber);
return this;
public ExcelWriterTableBuilder(ExcelWriter excelWriter, WriteSheet writeSheet) {
this.excelWriter = excelWriter;
this.writeSheet = writeSheet;
}
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*
* @param writeRelativeHeadRowIndex
* @param relativeHeadRowIndex
* @return
*/
public ExcelWriterTableBuilder writeRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) {
table.setWriteRelativeHeadRowIndex(writeRelativeHeadRowIndex);
public ExcelWriterTableBuilder relativeHeadRowIndex(Integer relativeHeadRowIndex) {
writeTable.setRelativeHeadRowIndex(relativeHeadRowIndex);
return this;
}
@ -57,7 +53,7 @@ public class ExcelWriterTableBuilder {
* @return
*/
public ExcelWriterTableBuilder head(List<List<String>> head) {
table.setHead(head);
writeTable.setHead(head);
return this;
}
@ -69,7 +65,7 @@ public class ExcelWriterTableBuilder {
* @return
*/
public ExcelWriterTableBuilder head(Class clazz) {
table.setClazz(clazz);
writeTable.setClazz(clazz);
return this;
}
@ -77,7 +73,7 @@ public class ExcelWriterTableBuilder {
* Need Head
*/
public ExcelWriterTableBuilder needHead(Boolean needHead) {
table.setNeedHead(needHead);
writeTable.setNeedHead(needHead);
return this;
}
@ -88,10 +84,10 @@ public class ExcelWriterTableBuilder {
* @return
*/
public ExcelWriterTableBuilder registerConverter(Converter converter) {
if (table.getCustomConverterMap() == null) {
table.setCustomConverterMap(new HashMap<Class, Converter>());
if (writeTable.getCustomConverterList() == null) {
writeTable.setCustomConverterList(new ArrayList<Converter>());
}
table.getCustomConverterMap().put(converter.supportJavaTypeKey(), converter);
writeTable.getCustomConverterList().add(converter);
return this;
}
@ -102,10 +98,10 @@ public class ExcelWriterTableBuilder {
* @return
*/
public ExcelWriterTableBuilder registerWriteHandler(WriteHandler writeHandler) {
if (table.getCustomWriteHandlerList() == null) {
table.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
if (writeTable.getCustomWriteHandlerList() == null) {
writeTable.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
table.getCustomWriteHandlerList().add(writeHandler);
writeTable.getCustomWriteHandlerList().add(writeHandler);
return this;
}
@ -116,12 +112,20 @@ public class ExcelWriterTableBuilder {
* @return
*/
public ExcelWriterTableBuilder tableNo(Integer tableNo) {
table.setTableNo(tableNo);
writeTable.setTableNo(tableNo);
return this;
}
public Table build() {
return table;
public WriteTable build() {
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 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.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.sun.istack.internal.Nullable;
/**
@ -18,26 +18,26 @@ public interface CellWriteHandler extends WriteHandler {
/**
* called before create the cell
*
* @param sheetHolder
* @param tableHolder
* @param writeSheetHolder
* @param writeTableHolder
* @param row
* @param head
* @param relativeRowIndex
* @param isHead
*/
void beforeCellCreate(SheetHolder sheetHolder, @Nullable TableHolder tableHolder, Row row, Head head,
int relativeRowIndex, boolean isHead);
void beforeCellCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, Row row,
Head head, int relativeRowIndex, boolean isHead);
/**
* called after the cell is created
*
* @param sheetHolder
* @param tableHolder
* @param writeSheetHolder
* @param writeTableHolder
* @param cell
* @param head
* @param relativeRowIndex
* @param isHead
*/
void afterCellCreate(SheetHolder sheetHolder, @Nullable TableHolder tableHolder, Cell cell, Head head,
int relativeRowIndex, boolean isHead);
void afterCellCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, Cell cell,
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 com.alibaba.excel.write.metadata.holder.SheetHolder;
import com.alibaba.excel.write.metadata.holder.TableHolder;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.sun.istack.internal.Nullable;
/**
@ -16,24 +16,24 @@ public interface RowWriteHandler extends WriteHandler {
/**
* called before create the row
*
* @param sheetHolder
* @param tableHolder
* @param writeSheetHolder
* @param writeTableHolder
* @param rowIndex
* @param relativeRowIndex
* @param isHead
*/
void beforeRowCreate(SheetHolder sheetHolder, @Nullable TableHolder tableHolder, int rowIndex, int relativeRowIndex,
boolean isHead);
void beforeRowCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, int rowIndex,
int relativeRowIndex, boolean isHead);
/**
* called after the row is created
*
* @param sheetHolder
* @param tableHolder
* @param writeSheetHolder
* @param writeTableHolder
* @param row
* @param relativeRowIndex
* @param isHead
*/
void afterRowCreate(SheetHolder sheetHolder, @Nullable TableHolder tableHolder, Row row, int relativeRowIndex,
boolean isHead);
void afterRowCreate(WriteSheetHolder writeSheetHolder, @Nullable WriteTableHolder writeTableHolder, Row row,
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;
import com.alibaba.excel.write.metadata.holder.SheetHolder;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* intercepts handle sheet creation
@ -13,16 +13,16 @@ public interface SheetWriteHandler extends WriteHandler {
/**
* called before create the sheet
*
* @param workbookHolder
* @param sheetHolder
* @param writeWorkbookHolder
* @param writeSheetHolder
*/
void beforeSheetCreate(WorkbookHolder workbookHolder, SheetHolder sheetHolder);
void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder);
/**
* called after the sheet is created
*
* @param workbookHolder
* @param sheetHolder
* @param writeWorkbookHolder
* @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;
import com.alibaba.excel.write.metadata.holder.WorkbookHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* intercepts handle Workbook creation
@ -17,7 +17,7 @@ public interface WorkbookWriteHandler extends WriteHandler {
/**
* 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 {
/**
* Excel type
* Excel type.The default is xlsx
*/
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 com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.read.metadata.holder.TableHolder;
import com.alibaba.excel.write.metadata.WriteSheet;
/**
@ -34,11 +33,11 @@ public class WriteSheetHolder extends AbstractWriteHolder {
/***
* poi sheet
*/
private WriteWorkbookHolder parentWorkBook;
private WriteWorkbookHolder parentWriteWorkbookHolder;
/***
* has been initialized table
*/
private Map<Integer, TableHolder> hasBeenInitializedTable;
private Map<Integer, WriteTableHolder> hasBeenInitializedTable;
public WriteSheetHolder(WriteSheet writeSheet, WriteWorkbookHolder writeWorkbookHolder) {
super(writeSheet, writeWorkbookHolder, writeWorkbookHolder.getWriteWorkbook().getConvertAllFiled());
@ -49,8 +48,8 @@ public class WriteSheetHolder extends AbstractWriteHolder {
} else {
this.sheetName = writeSheet.getSheetName();
}
this.parentWorkBook = writeWorkbookHolder;
this.hasBeenInitializedTable = new HashMap<Integer, TableHolder>();
this.parentWriteWorkbookHolder = writeWorkbookHolder;
this.hasBeenInitializedTable = new HashMap<Integer, WriteTableHolder>();
}
public WriteSheet getWriteSheet() {
@ -85,20 +84,19 @@ public class WriteSheetHolder extends AbstractWriteHolder {
this.sheetName = sheetName;
}
public WriteWorkbookHolder getParentWorkBook() {
return parentWorkBook;
public WriteWorkbookHolder getParentWriteWorkbookHolder() {
return parentWriteWorkbookHolder;
}
public void setParentWorkBook(WriteWorkbookHolder parentWorkBook) {
this.parentWorkBook = parentWorkBook;
public void setParentWriteWorkbookHolder(WriteWorkbookHolder parentWriteWorkbookHolder) {
this.parentWriteWorkbookHolder = parentWriteWorkbookHolder;
}
public Map<Integer, TableHolder> getHasBeenInitializedTable() {
public Map<Integer, WriteTableHolder> getHasBeenInitializedTable() {
return hasBeenInitializedTable;
}
public void setHasBeenInitializedTable(
Map<Integer, TableHolder> hasBeenInitializedTable) {
public void setHasBeenInitializedTable(Map<Integer, WriteTableHolder> 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
*/
private WriteSheetHolder parentSheet;
private WriteSheetHolder parentWriteSheetHolder;
/***
* tableNo
*/
@ -25,17 +25,17 @@ public class WriteTableHolder extends AbstractWriteHolder {
public WriteTableHolder(WriteTable writeTable, WriteSheetHolder writeSheetHolder,
WriteWorkbookHolder writeWorkbookHolder) {
super(writeTable, writeSheetHolder, writeWorkbookHolder.getWriteWorkbook().getConvertAllFiled());
this.parentSheet = writeSheetHolder;
this.parentWriteSheetHolder = writeSheetHolder;
this.tableNo = writeTable.getTableNo();
this.writeTable = writeTable;
}
public WriteSheetHolder getParentSheet() {
return parentSheet;
public WriteSheetHolder getParentWriteSheetHolder() {
return parentWriteSheetHolder;
}
public void setParentSheet(WriteSheetHolder parentSheet) {
this.parentSheet = parentSheet;
public void setParentWriteSheetHolder(WriteSheetHolder parentWriteSheetHolder) {
this.parentWriteSheetHolder = parentWriteSheetHolder;
}
public Integer getTableNo() {

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

@ -7,6 +7,8 @@ import java.util.HashMap;
import java.util.Map;
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.support.ExcelTypeEnum;
@ -18,6 +20,7 @@ import com.alibaba.excel.write.metadata.WriteWorkbook;
* @author zhuangjiaju
*/
public class WriteWorkbookHolder extends AbstractWriteHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(WriteWorkbookHolder.class);
/***
* poi Workbook
*/
@ -71,7 +74,14 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
} else {
this.autoCloseStream = writeWorkbook.getAutoCloseStream();
}
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) {
this.mandatoryUseInputStream = Boolean.FALSE;
} 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.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.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
@ -27,23 +27,24 @@ public abstract class AbstractCellStyleStrategy implements CellWriteHandler, Wor
public void beforeWorkbookCreate() {}
@Override
public void afterWorkbookCreate(WorkbookHolder workbookHolder) {
initCellStyle(workbookHolder.getWorkbook());
public void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) {
initCellStyle(writeWorkbookHolder.getWorkbook());
}
@Override
public void beforeCellCreate(SheetHolder sheetHolder, TableHolder tableHolder, Row row, Head head,
int relativeRowIndex, boolean isHead) {}
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Head head, int relativeRowIndex, boolean isHead) {
}
@Override
public void afterCellCreate(SheetHolder sheetHolder, TableHolder tableHolder, Cell cell, Head head,
int relativeRowIndex, boolean isHead) {
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
Head head, int relativeRowIndex, boolean isHead) {
if (isHead) {
setHeadCellStyle(cell, head, relativeRowIndex);
} else {
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.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.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.sun.istack.internal.Nullable;
/**
@ -24,16 +24,18 @@ public abstract class AbstractColumnWidthStyleStrategy implements CellWriteHandl
}
@Override
public void beforeCellCreate(SheetHolder sheetHolder, TableHolder tableHolder, Row row, Head head,
int relativeRowIndex, boolean isHead) {}
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Head head, int relativeRowIndex, boolean isHead) {
}
@Override
public void afterCellCreate(SheetHolder sheetHolder, TableHolder tableHolder, Cell cell, Head head,
int relativeRowIndex, boolean isHead) {
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
Head head, int relativeRowIndex, boolean isHead) {
if (!isHead && relativeRowIndex != 0) {
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 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.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
/**
* Set the row height strategy
@ -20,14 +20,14 @@ public abstract class AbstractRowHeightStyleStrategy implements RowWriteHandler,
}
@Override
public void beforeRowCreate(SheetHolder sheetHolder, TableHolder tableHolder, int rowIndex, int relativeRowIndex,
boolean isHead) {
public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, int rowIndex,
int relativeRowIndex, boolean isHead) {
}
@Override
public void afterRowCreate(SheetHolder sheetHolder, TableHolder tableHolder, Row row, int relativeRowIndex,
boolean isHead) {
public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
int relativeRowIndex, boolean isHead) {
if (isHead) {
setHeadColumnHeight(row, relativeRowIndex);
} else {

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

@ -1,12 +1,19 @@
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.easyexcel.test.util.FileUtil;
import com.alibaba.excel.EasyExcelFactory;
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
@ -18,13 +25,29 @@ public class LargeData07Test {
@Test
public void large() throws Exception {
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);
EasyExcelFactory.read().registerReadListener(listener).file(in).sheet().sheetNo(sheetNo).doRead().finish();
//
// public static List<Object> read(InputStream in, Sheet sheet) {
// final List<Object> rows = new ArrayList<Object>();
// new ExcelReader(in, null, new AnalysisEventListener<Object>() {
// @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

Loading…
Cancel
Save