Browse Source

修改一些流程性异常 并 将写 测试完成

bugfix
zhuangjiaju 5 years ago
parent
commit
be4b3795a1
  1. 6
      pom.xml
  2. 111
      src/main/java/com/alibaba/excel/EasyExcelFactory.java
  3. 301
      src/main/java/com/alibaba/excel/context/WriteContextImpl.java
  4. 12
      src/main/java/com/alibaba/excel/converters/DefaultConverterBuilder.java
  5. 105
      src/main/java/com/alibaba/excel/metadata/BasicParameter.java
  6. 7
      src/main/java/com/alibaba/excel/metadata/ExcelHeadProperty.java
  7. 130
      src/main/java/com/alibaba/excel/metadata/Sheet.java
  8. 86
      src/main/java/com/alibaba/excel/metadata/Table.java
  9. 103
      src/main/java/com/alibaba/excel/metadata/Workbook.java
  10. 224
      src/main/java/com/alibaba/excel/metadata/holder/AbstractConfigurationSelector.java
  11. 183
      src/main/java/com/alibaba/excel/metadata/holder/SheetHolder.java
  12. 166
      src/main/java/com/alibaba/excel/metadata/holder/TableHolder.java
  13. 135
      src/main/java/com/alibaba/excel/metadata/holder/WorkbookHolder.java
  14. 8
      src/main/java/com/alibaba/excel/util/StyleUtil.java
  15. 4
      src/main/java/com/alibaba/excel/util/WorkBookUtil.java
  16. 105
      src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java
  17. 172
      src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java
  18. 152
      src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java
  19. 127
      src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java
  20. 3
      src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerBuilder.java
  21. 8
      src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java
  22. 7
      src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java
  23. 7
      src/main/java/com/alibaba/excel/write/style/column/SimpleColumnWidthStyleStrategy.java
  24. 11
      src/test/java/com/alibaba/easyexcel/test/util/FileUtil.java
  25. 19
      src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData.java
  26. 17
      src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData03Test.java
  27. 38
      src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData07Test.java
  28. 5
      src/test/resources/logback.xml

6
pom.xml

@ -82,6 +82,12 @@
<version>1.2.3</version> <version>1.2.3</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>

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

@ -11,6 +11,8 @@ import com.alibaba.excel.event.WriteHandler;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder; import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterTableBuilder;
/** /**
* Reader and writer factory class * Reader and writer factory class
@ -22,8 +24,10 @@ public class EasyExcelFactory {
/** /**
* Quickly read small filesno more than 10,000 lines. * Quickly read small filesno more than 10,000 lines.
* *
* @param in the POI filesystem that contains the Workbook stream. * @param in
* @param sheet read sheet. * the POI filesystem that contains the Workbook stream.
* @param sheet
* read sheet.
* @return analysis result. * @return analysis result.
*/ */
public static List<Object> read(InputStream in, Sheet sheet) { public static List<Object> read(InputStream in, Sheet sheet) {
@ -35,8 +39,7 @@ public class EasyExcelFactory {
} }
@Override @Override
public void doAfterAllAnalysed(AnalysisContext context) { public void doAfterAllAnalysed(AnalysisContext context) {}
}
}, false).read(sheet); }, false).read(sheet);
return rows; return rows;
} }
@ -44,9 +47,12 @@ public class EasyExcelFactory {
/** /**
* Parsing large file * Parsing large file
* *
* @param in the POI filesystem that contains the Workbook stream. * @param in
* @param sheet read sheet. * the POI filesystem that contains the Workbook stream.
* @param listener Callback method after each row is parsed. * @param sheet
* read sheet.
* @param listener
* Callback method after each row is parsed.
*/ */
public static void readBySax(InputStream in, Sheet sheet, AnalysisEventListener listener) { public static void readBySax(InputStream in, Sheet sheet, AnalysisEventListener listener) {
new ExcelReader(in, null, listener).read(sheet); new ExcelReader(in, null, listener).read(sheet);
@ -55,8 +61,10 @@ public class EasyExcelFactory {
/** /**
* Get ExcelReader. * Get ExcelReader.
* *
* @param in the POI filesystem that contains the Workbook stream. * @param in
* @param listener Callback method after each row is parsed. * the POI filesystem that contains the Workbook stream.
* @param listener
* Callback method after each row is parsed.
* @return ExcelReader. * @return ExcelReader.
*/ */
public static ExcelReader getReader(InputStream in, AnalysisEventListener listener) { public static ExcelReader getReader(InputStream in, AnalysisEventListener listener) {
@ -66,79 +74,86 @@ public class EasyExcelFactory {
/** /**
* Get ExcelWriter * Get ExcelWriter
* *
* @param outputStream the java OutputStream you wish to write the value to. * @param outputStream
* the java OutputStream you wish to write the value to.
* @return new ExcelWriter. * @return new ExcelWriter.
* @deprecated please use {@link EasyExcelFactory#writerBuilder()}
*/ */
@Deprecated
public static ExcelWriter getWriter(OutputStream outputStream) { public static ExcelWriter getWriter(OutputStream outputStream) {
return writerBuilder().outputFile(outputStream).build(); return writerBuilder().outputFile(outputStream).autoCloseStream(Boolean.FALSE).build();
} }
/** /**
* Get ExcelWriter * Get ExcelWriter
* *
* @param outputStream the java OutputStream you wish to write the value to. * @param outputStream
* @param typeEnum 03 or 07 * the java OutputStream you wish to write the value to.
* @param needHead Do you need to write the header to the file? * @param typeEnum
* @return new ExcelWriter * 03 or 07
* @param needHead
* Do you need to write the header to the file?
* @return new ExcelWriter
* @deprecated please use {@link EasyExcelFactory#writerBuilder()}
*/ */
@Deprecated
public static ExcelWriter getWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { public static ExcelWriter getWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) {
if (needHead) { return writerBuilder().outputFile(outputStream).excelType(typeEnum).needHead(needHead)
return writerBuilder().outputFile(outputStream).excelType(typeEnum).build(); .autoCloseStream(Boolean.FALSE).build();
} else {
return writerBuilder().outputFile(outputStream).excelType(typeEnum).doNotNeedHead().build();
}
} }
/** /**
* Get ExcelWriter with a template file * Get ExcelWriter with a template file
* *
* @param temp Append value after a POI file , Can be nullthe template POI filesystem that contains the * @param temp
* Workbook stream) * Append value after a POI file , Can be nullthe template POI filesystem that contains the Workbook
* @param outputStream the java OutputStream you wish to write the value to * stream)
* @param typeEnum 03 or 07 * @param outputStream
* @return new ExcelWriter * the java OutputStream you wish to write the value to
* @param typeEnum
* 03 or 07
* @return new ExcelWriter
* @deprecated please use {@link EasyExcelFactory#writerBuilder()}
*/ */
@Deprecated
public static ExcelWriter getWriterWithTemp(InputStream temp, OutputStream outputStream, ExcelTypeEnum typeEnum, public static ExcelWriter getWriterWithTemp(InputStream temp, OutputStream outputStream, ExcelTypeEnum typeEnum,
boolean needHead) { boolean needHead) {
if (needHead) { return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).needHead(needHead)
return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).build(); .autoCloseStream(Boolean.FALSE).build();
} else {
return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).doNotNeedHead()
.build();
}
} }
/** /**
* Get ExcelWriter with a template file * Get ExcelWriter with a template file
* *
* @param temp Append value after a POI file , Can be nullthe template POI filesystem that contains the * @param temp
* Workbook stream) * Append value after a POI file , Can be nullthe template POI filesystem that contains the Workbook
* @param outputStream the java OutputStream you wish to write the value to * stream)
* @param typeEnum 03 or 07 * @param outputStream
* the java OutputStream you wish to write the value to
* @param typeEnum
* 03 or 07
* @param needHead * @param needHead
* @param handler User-defined callback * @param handler
* @return new ExcelWriter * User-defined callback
* @return new ExcelWriter
* @deprecated please use {@link EasyExcelFactory#writerBuilder()}
*/ */
@Deprecated
public static ExcelWriter getWriterWithTempAndHandler(InputStream temp, OutputStream outputStream, public static ExcelWriter getWriterWithTempAndHandler(InputStream temp, OutputStream outputStream,
ExcelTypeEnum typeEnum, boolean needHead, WriteHandler handler) { ExcelTypeEnum typeEnum, boolean needHead, WriteHandler handler) {
if (needHead) { return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).needHead(needHead)
return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum) .registerWriteHandler(handler).autoCloseStream(Boolean.FALSE).build();
.registerWriteHandler(handler).build();
} else {
return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).doNotNeedHead()
.registerWriteHandler(handler).build();
}
} }
public static ExcelWriterBuilder writerBuilder() { public static ExcelWriterBuilder writerBuilder() {
return new ExcelWriterBuilder(); return new ExcelWriterBuilder();
} }
public static ExcelWriterBuilder writerSheetBuilder() { public static ExcelWriterSheetBuilder writerSheetBuilder() {
return new ExcelWriterBuilder(); return new ExcelWriterSheetBuilder();
} }
public static ExcelWriterBuilder writerTableBuilder() { public static ExcelWriterTableBuilder writerTableBuilder() {
return new ExcelWriterBuilder(); return new ExcelWriterTableBuilder();
} }
} }

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

@ -1,13 +1,7 @@
package com.alibaba.excel.context; package com.alibaba.excel.context;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List; 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.Cell;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
@ -16,27 +10,20 @@ import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.DefaultConverterBuilder;
import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.event.Order;
import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.CellStyle;
import com.alibaba.excel.metadata.ExcelHeadProperty; import com.alibaba.excel.metadata.ExcelHeadProperty;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.Table; import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.metadata.holder.ConfigurationSelector; import com.alibaba.excel.metadata.holder.ConfigurationSelector;
import com.alibaba.excel.metadata.holder.SheetHolder; import com.alibaba.excel.metadata.holder.SheetHolder;
import com.alibaba.excel.metadata.holder.TableHolder; import com.alibaba.excel.metadata.holder.TableHolder;
import com.alibaba.excel.metadata.holder.WorkbookHolder; import com.alibaba.excel.metadata.holder.WorkbookHolder;
import com.alibaba.excel.util.WorkBookUtil; import com.alibaba.excel.util.WorkBookUtil;
import com.alibaba.excel.write.handler.DefaultWriteHandlerBuilder; 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.SheetWriteHandler;
import com.alibaba.excel.write.handler.WorkbookWriteHandler; import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.style.RowCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractHeadColumnWidthStyleStrategy;
/** /**
* A context is the main anchorage point of a excel writer. * A context is the main anchorage point of a excel writer.
@ -109,72 +96,13 @@ public class WriteContextImpl implements WriteContext {
} }
private void initCurrentWorkbookHolder(com.alibaba.excel.metadata.Workbook workbook) { private void initCurrentWorkbookHolder(com.alibaba.excel.metadata.Workbook workbook) {
currentWorkbookHolder = new WorkbookHolder(); currentWorkbookHolder = new WorkbookHolder(workbook);
currentWorkbookHolder.setWorkbookParam(workbook);
currentWorkbookHolder.setTemplateInputStream(workbook.getTemplateInputStream());
currentWorkbookHolder.setOutputStream(workbook.getOutputStream());
if (workbook.getNeedHead() == null) {
currentWorkbookHolder.setNeedHead(Boolean.TRUE);
} else {
currentWorkbookHolder.setNeedHead(workbook.getNeedHead());
}
if (workbook.getWriteRelativeHeadRowIndex() == null) {
currentWorkbookHolder.setWriteRelativeHeadRowIndex(0);
} else {
currentWorkbookHolder.setWriteRelativeHeadRowIndex(workbook.getWriteRelativeHeadRowIndex());
}
List<WriteHandler> handlerList = new ArrayList<WriteHandler>();
if (workbook.getCustomWriteHandlerList() != null && !workbook.getCustomWriteHandlerList().isEmpty()) {
handlerList.addAll(workbook.getCustomWriteHandlerList());
}
handlerList.addAll(DefaultWriteHandlerBuilder.loadDefaultHandler());
currentWorkbookHolder.setWriteHandlerList(sortAndClearUpHandler(handlerList));
Map<Class, Converter> converterMap = DefaultConverterBuilder.loadDefaultWriteConverter();
if (workbook.getCustomConverterMap() != null && !workbook.getCustomConverterMap().isEmpty()) {
converterMap.putAll(workbook.getCustomConverterMap());
}
currentWorkbookHolder.setConverterMap(converterMap);
currentWorkbookHolder.setHasBeenInitializedSheet(new HashMap<Integer, SheetHolder>());
currentConfigurationSelector = currentWorkbookHolder; currentConfigurationSelector = currentWorkbookHolder;
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CurrentConfigurationSelector is currentWorkbookHolder"); LOGGER.debug("CurrentConfigurationSelector is currentWorkbookHolder");
} }
} }
private List<WriteHandler> sortAndClearUpHandler(List<WriteHandler> handlerList) {
// 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> result = 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);
}
result.add(handler);
}
}
return result;
}
/** /**
* @param sheet * @param sheet
*/ */
@ -191,6 +119,7 @@ public class WriteContextImpl implements WriteContext {
LOGGER.debug("Sheet:{} is already existed", sheet.getSheetNo()); LOGGER.debug("Sheet:{} is already existed", sheet.getSheetNo());
} }
currentSheetHolder = currentWorkbookHolder.getHasBeenInitializedSheet().get(sheet.getSheetNo()); currentSheetHolder = currentWorkbookHolder.getHasBeenInitializedSheet().get(sheet.getSheetNo());
currentSheetHolder.setNewInitialization(Boolean.FALSE);
currentTableHolder = null; currentTableHolder = null;
currentConfigurationSelector = currentSheetHolder; currentConfigurationSelector = currentSheetHolder;
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
@ -198,7 +127,6 @@ public class WriteContextImpl implements WriteContext {
} }
return; return;
} }
initCurrentSheetHolder(sheet); initCurrentSheetHolder(sheet);
beforeSheetCreate(); beforeSheetCreate();
// Initialization current sheet // Initialization current sheet
@ -228,36 +156,14 @@ public class WriteContextImpl implements WriteContext {
((SheetWriteHandler)writeHandler).afterSheetCreate(currentWorkbookHolder, currentSheetHolder); ((SheetWriteHandler)writeHandler).afterSheetCreate(currentWorkbookHolder, currentSheetHolder);
} }
} }
if (null != currentWorkbookHolder.getWriteHandler()) {
currentWorkbookHolder.getWriteHandler().sheet(currentSheetHolder.getSheetNo(),
currentSheetHolder.getSheet());
}
} }
private void initCurrentSheetHolder(com.alibaba.excel.metadata.Sheet sheet) { private void initCurrentSheetHolder(com.alibaba.excel.metadata.Sheet sheet) {
currentSheetHolder = new SheetHolder(); currentSheetHolder = new SheetHolder(sheet, currentWorkbookHolder);
currentSheetHolder.setSheetParam(sheet);
currentSheetHolder.setParentWorkBook(currentWorkbookHolder);
if (sheet.getNeedHead() == null) {
currentSheetHolder.setNeedHead(currentConfigurationSelector.needHead());
} else {
currentSheetHolder.setNeedHead(sheet.getNeedHead());
}
if (sheet.getWriteRelativeHeadRowIndex() == null) {
currentSheetHolder.setWriteRelativeHeadRowIndex(currentConfigurationSelector.writeRelativeHeadRowIndex());
} else {
currentSheetHolder.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());
}
handlerList.addAll(currentConfigurationSelector.writeHandlerList());
currentSheetHolder.setWriteHandlerList(sortAndClearUpHandler(handlerList));
Map<Class, Converter> converterMap = new HashMap<Class, Converter>(currentConfigurationSelector.converterMap());
if (sheet.getCustomConverterMap() != null && !sheet.getCustomConverterMap().isEmpty()) {
converterMap.putAll(sheet.getCustomConverterMap());
}
currentSheetHolder.setConverterMap(converterMap);
currentSheetHolder.setHasBeenInitializedTable(new HashMap<Integer, TableHolder>());
currentWorkbookHolder.getHasBeenInitializedSheet().put(sheet.getSheetNo(), currentSheetHolder); currentWorkbookHolder.getHasBeenInitializedSheet().put(sheet.getSheetNo(), currentSheetHolder);
currentTableHolder = null; currentTableHolder = null;
currentConfigurationSelector = currentSheetHolder; currentConfigurationSelector = currentSheetHolder;
@ -266,41 +172,6 @@ public class WriteContextImpl implements WriteContext {
} }
} }
/**
* Compatible with old code
*/
@Deprecated
private 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 int 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));
}
}
private void initSheet(com.alibaba.excel.metadata.Sheet sheet) { private void initSheet(com.alibaba.excel.metadata.Sheet sheet) {
Sheet currentSheet; Sheet currentSheet;
try { try {
@ -313,7 +184,8 @@ public class WriteContextImpl implements WriteContext {
} }
currentSheetHolder.setSheet(currentSheet); currentSheetHolder.setSheet(currentSheet);
// Initialization head // Initialization head
currentSheetHolder.setExcelHeadProperty(new ExcelHeadProperty(sheet.getClazz(), sheet.getHead())); currentSheetHolder
.setExcelHeadProperty(new ExcelHeadProperty(currentSheetHolder.getClazz(), currentSheetHolder.getHead()));
// Initialization head // Initialization head
initHead(currentSheetHolder.getExcelHeadProperty()); initHead(currentSheetHolder.getExcelHeadProperty());
} }
@ -322,28 +194,90 @@ public class WriteContextImpl implements WriteContext {
if (!currentConfigurationSelector.needHead() || !currentSheetHolder.getExcelHeadProperty().hasHead()) { if (!currentConfigurationSelector.needHead() || !currentSheetHolder.getExcelHeadProperty().hasHead()) {
return; return;
} }
int startRow = currentSheetHolder.getSheet().getLastRowNum(); int lastRowNum = currentSheetHolder.getSheet().getLastRowNum();
startRow += currentConfigurationSelector.writeRelativeHeadRowIndex(); int rowIndex = lastRowNum + currentConfigurationSelector.writeRelativeHeadRowIndex();
// Combined head // Combined head
addMergedRegionToCurrentSheet(excelHeadProperty, startRow); addMergedRegionToCurrentSheet(excelHeadProperty, rowIndex);
for (int i = startRow; i < excelHeadProperty.getHeadRowNumber() + startRow; i++) { for (int relativeRowIndex = 0, i = rowIndex; i < excelHeadProperty.getHeadRowNumber() + rowIndex;
i++, relativeRowIndex++) {
beforeRowCreate(rowIndex, relativeRowIndex);
Row row = WorkBookUtil.createRow(currentSheetHolder.getSheet(), i); Row row = WorkBookUtil.createRow(currentSheetHolder.getSheet(), i);
addOneRowOfHeadDataToExcel(row, i, excelHeadProperty.getHeadList()); afterRowCreate(row, relativeRowIndex);
addOneRowOfHeadDataToExcel(row, excelHeadProperty.getHeadList(), relativeRowIndex);
}
}
private void beforeRowCreate(int rowIndex, int relativeRowIndex) {
List<WriteHandler> handlerList = currentConfigurationSelector.writeHandlerMap().get(RowWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).beforeRowCreate(currentSheetHolder, currentTableHolder, rowIndex,
relativeRowIndex, true);
}
} }
} }
private void addMergedRegionToCurrentSheet(ExcelHeadProperty excelHeadProperty, int startRow) { private void afterRowCreate(Row row, int relativeRowIndex) {
List<WriteHandler> handlerList = currentConfigurationSelector.writeHandlerMap().get(RowWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).afterRowCreate(currentSheetHolder, currentTableHolder, row,
relativeRowIndex, true);
}
}
if (null != currentWorkbookHolder.getWriteHandler()) {
currentWorkbookHolder.getWriteHandler().row(row.getRowNum(), row);
}
}
private void addMergedRegionToCurrentSheet(ExcelHeadProperty excelHeadProperty, int rowIndex) {
for (com.alibaba.excel.metadata.CellRange cellRangeModel : excelHeadProperty.getCellRangeModels()) { for (com.alibaba.excel.metadata.CellRange cellRangeModel : excelHeadProperty.getCellRangeModels()) {
currentSheetHolder.getSheet().addMergedRegion(new CellRangeAddress(cellRangeModel.getFirstRow() + startRow, currentSheetHolder.getSheet().addMergedRegion(new CellRangeAddress(cellRangeModel.getFirstRow() + rowIndex,
cellRangeModel.getLastRow() + startRow, cellRangeModel.getFirstCol(), cellRangeModel.getLastCol())); cellRangeModel.getLastRow() + rowIndex, cellRangeModel.getFirstCol(), cellRangeModel.getLastCol()));
} }
} }
private void addOneRowOfHeadDataToExcel(Row row, int rowIndex, List<Head> headList) { private void addOneRowOfHeadDataToExcel(Row row, List<Head> headList, int relativeRowIndex) {
for (int i = 0; i < headList.size(); i++) { for (int i = 0; i < headList.size(); i++) {
Head head = headList.get(i); Head head = headList.get(i);
// TODO 创建cell beforeCellCreate(row, headList.get(i), relativeRowIndex);
Cell cell = WorkBookUtil.createCell(row, i, head.getHeadName(i)); Cell cell = WorkBookUtil.createCell(row, i, head.getHeadName(i));
afterCellCreate(headList.get(i), cell, relativeRowIndex);
}
}
private void beforeCellCreate(Row row, Head head, int relativeRowIndex) {
List<WriteHandler> handlerList = currentConfigurationSelector.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,
relativeRowIndex, true);
}
}
}
private void afterCellCreate(Head head, Cell cell, int relativeRowIndex) {
List<WriteHandler> handlerList = currentConfigurationSelector.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,
relativeRowIndex, true);
}
}
if (null != currentWorkbookHolder.getWriteHandler()) {
currentWorkbookHolder.getWriteHandler().cell(cell.getRowIndex(), cell);
} }
} }
@ -360,6 +294,7 @@ public class WriteContextImpl implements WriteContext {
LOGGER.debug("Table:{} is already existed", table.getTableNo()); LOGGER.debug("Table:{} is already existed", table.getTableNo());
} }
currentTableHolder = currentSheetHolder.getHasBeenInitializedTable().get(table.getTableNo()); currentTableHolder = currentSheetHolder.getHasBeenInitializedTable().get(table.getTableNo());
currentTableHolder.setNewInitialization(Boolean.FALSE);
currentConfigurationSelector = currentTableHolder; currentConfigurationSelector = currentTableHolder;
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CurrentConfigurationSelector is currentTableHolder"); LOGGER.debug("CurrentConfigurationSelector is currentTableHolder");
@ -368,65 +303,20 @@ public class WriteContextImpl implements WriteContext {
} }
initCurrentTableHolder(table); initCurrentTableHolder(table);
// Initialization head // Initialization head
currentTableHolder.setExcelHeadProperty(new ExcelHeadProperty(table.getClazz(), table.getHead())); currentTableHolder
.setExcelHeadProperty(new ExcelHeadProperty(currentTableHolder.getClazz(), currentTableHolder.getHead()));
initHead(currentTableHolder.getExcelHeadProperty()); initHead(currentTableHolder.getExcelHeadProperty());
} }
private void initCurrentTableHolder(com.alibaba.excel.metadata.Table table) { private void initCurrentTableHolder(com.alibaba.excel.metadata.Table table) {
currentTableHolder = new TableHolder(); currentTableHolder = new TableHolder(table, currentSheetHolder);
currentTableHolder.setTableParam(table); currentSheetHolder.getHasBeenInitializedTable().put(table.getTableNo(), currentTableHolder);
currentTableHolder.setParentSheet(currentSheetHolder);
currentTableHolder.setTableNo(table.getTableNo());
if (table.getNeedHead() == null) {
currentTableHolder.setNeedHead(currentConfigurationSelector.needHead());
} else {
currentTableHolder.setNeedHead(table.getNeedHead());
}
if (table.getWriteRelativeHeadRowIndex() == null) {
currentTableHolder.setWriteRelativeHeadRowIndex(currentConfigurationSelector.writeRelativeHeadRowIndex());
} else {
currentTableHolder.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());
}
handlerList.addAll(currentConfigurationSelector.writeHandlerList());
currentTableHolder.setWriteHandlerList(sortAndClearUpHandler(handlerList));
Map<Class, Converter> converterMap = new HashMap<Class, Converter>(currentConfigurationSelector.converterMap());
if (table.getCustomConverterMap() != null && !table.getCustomConverterMap().isEmpty()) {
converterMap.putAll(table.getCustomConverterMap());
}
currentTableHolder.setConverterMap(converterMap);
currentConfigurationSelector = currentTableHolder; currentConfigurationSelector = currentTableHolder;
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CurrentConfigurationSelector is currentTableHolder"); LOGGER.debug("CurrentConfigurationSelector is currentTableHolder");
} }
} }
/**
* Compatible with old code
*/
@Deprecated
private void compatibleOldCode(com.alibaba.excel.metadata.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));
}
}
@Override @Override
public ConfigurationSelector currentConfigurationSelector() { public ConfigurationSelector currentConfigurationSelector() {
return currentConfigurationSelector; return currentConfigurationSelector;
@ -452,14 +342,19 @@ public class WriteContextImpl implements WriteContext {
try { try {
currentWorkbookHolder.getWorkbook().write(currentWorkbookHolder.getOutputStream()); currentWorkbookHolder.getWorkbook().write(currentWorkbookHolder.getOutputStream());
currentWorkbookHolder.getWorkbook().close(); currentWorkbookHolder.getWorkbook().close();
if (currentWorkbookHolder.getOutputStream() != null) { if (currentWorkbookHolder.getAutoCloseStream()) {
currentWorkbookHolder.getOutputStream().close(); if (currentWorkbookHolder.getOutputStream() != null) {
} currentWorkbookHolder.getOutputStream().close();
if (currentWorkbookHolder.getTemplateInputStream() != null) { }
currentWorkbookHolder.getTemplateInputStream().close(); if (currentWorkbookHolder.getTemplateInputStream() != null) {
currentWorkbookHolder.getTemplateInputStream().close();
}
} }
} catch (IOException e) { } catch (IOException e) {
throw new ExcelGenerateException("Can not close IO", e); throw new ExcelGenerateException("Can not close IO", e);
} }
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Finished write.");
}
} }
} }

12
src/main/java/com/alibaba/excel/converters/DefaultConverterBuilder.java

@ -5,6 +5,7 @@ import java.util.Map;
import com.alibaba.excel.converters.bigdecimal.BigDecimalNumberConverter; import com.alibaba.excel.converters.bigdecimal.BigDecimalNumberConverter;
import com.alibaba.excel.converters.date.DateStringConverter; import com.alibaba.excel.converters.date.DateStringConverter;
import com.alibaba.excel.converters.string.StringStringConverter;
/** /**
* Build default handler * Build default handler
@ -19,13 +20,16 @@ public class DefaultConverterBuilder {
*/ */
public static Map<Class, Converter> loadDefaultWriteConverter() { public static Map<Class, Converter> loadDefaultWriteConverter() {
Map<Class, Converter> converterMap = new HashMap<Class, Converter>(); Map<Class, Converter> converterMap = new HashMap<Class, Converter>();
DateStringConverter dateStringConverter = new DateStringConverter(); putConverter(converterMap, new DateStringConverter());
converterMap.put(dateStringConverter.supportJavaTypeKey(), dateStringConverter); putConverter(converterMap, new BigDecimalNumberConverter());
BigDecimalNumberConverter bigDecimalNumberConverter = new BigDecimalNumberConverter(); putConverter(converterMap, new StringStringConverter());
converterMap.put(bigDecimalNumberConverter.supportJavaTypeKey(), bigDecimalNumberConverter);
return converterMap; return converterMap;
} }
private static void putConverter(Map<Class, Converter> converterMap, Converter converter) {
converterMap.put(converter.supportJavaTypeKey(), converter);
}
/** /**
* Load default read converter * Load default read converter
* *

105
src/main/java/com/alibaba/excel/metadata/BasicParameter.java

@ -0,0 +1,105 @@
package com.alibaba.excel.metadata;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.write.handler.WriteHandler;
/**
* Basic parameter
*
* @author zhuangjiaju
**/
public class BasicParameter {
/**
* 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;
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*/
private Integer writeRelativeHeadRowIndex;
/**
* You can only choose one of the {@link BasicParameter#head} and {@link BasicParameter#clazz}
*/
private List<List<String>> head;
/**
* You can only choose one of the {@link BasicParameter#head} and {@link BasicParameter#clazz}
*/
private Class clazz;
/**
* Need Head
*/
private Boolean needHead;
/**
* Custom type conversions override the default
*/
private Map<Class, Converter> customConverterMap = new HashMap<Class, Converter>();
/**
* Custom type handler override the default
*/
private List<WriteHandler> customWriteHandlerList = new ArrayList<WriteHandler>();
public Integer getReadHeadRowNumber() {
return readHeadRowNumber;
}
public void setReadHeadRowNumber(Integer readHeadRowNumber) {
this.readHeadRowNumber = readHeadRowNumber;
}
public Integer getWriteRelativeHeadRowIndex() {
return writeRelativeHeadRowIndex;
}
public void setWriteRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) {
this.writeRelativeHeadRowIndex = writeRelativeHeadRowIndex;
}
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 getNeedHead() {
return needHead;
}
public void setNeedHead(Boolean needHead) {
this.needHead = needHead;
}
public Map<Class, Converter> getCustomConverterMap() {
return customConverterMap;
}
public void setCustomConverterMap(Map<Class, Converter> customConverterMap) {
this.customConverterMap = customConverterMap;
}
public List<WriteHandler> getCustomWriteHandlerList() {
return customWriteHandlerList;
}
public void setCustomWriteHandlerList(List<WriteHandler> customWriteHandlerList) {
this.customWriteHandlerList = customWriteHandlerList;
}
}

7
src/main/java/com/alibaba/excel/metadata/ExcelHeadProperty.java

@ -62,12 +62,11 @@ public class ExcelHeadProperty {
// convert headClazz to head // convert headClazz to head
initColumnProperties(); initColumnProperties();
} }
initHeadRowNumber(); initHeadRowNumber();
} }
public static ExcelHeadProperty buildExcelHeadProperty(ExcelHeadProperty excelHeadProperty, public static ExcelHeadProperty buildExcelHeadProperty(ExcelHeadProperty excelHeadProperty, Class clazz,
Class clazz, List<String> headOneRow) { List<String> headOneRow) {
if (excelHeadProperty == null) { if (excelHeadProperty == null) {
return new ExcelHeadProperty(clazz, new ArrayList<List<String>>()); return new ExcelHeadProperty(clazz, new ArrayList<List<String>>());
} }
@ -206,7 +205,7 @@ public class ExcelHeadProperty {
} }
public boolean hasHead() { public boolean hasHead() {
return headKind == HeadKindEnum.NONE; return headKind != HeadKindEnum.NONE;
} }
public int getHeadRowNumber() { public int getHeadRowNumber() {

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

@ -4,9 +4,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder; import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.style.RowCellStyleStrategy; import com.alibaba.excel.write.style.RowCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy; import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
@ -15,7 +13,7 @@ import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
* *
* @author jipengfei * @author jipengfei
*/ */
public class Sheet { public class Sheet extends BasicParameter {
/** /**
* Starting from 0 * Starting from 0
*/ */
@ -24,39 +22,6 @@ public class Sheet {
* sheet name * sheet name
*/ */
private String sheetName; private String sheetName;
/**
* 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;
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*/
private Integer writeRelativeHeadRowIndex;
/**
* You can only choose one of the {@link Sheet#head} and {@link Sheet#clazz}
*/
private List<List<String>> head;
/**
* You can only choose one of the {@link Sheet#head} and {@link Sheet#clazz}
*/
private Class clazz;
/**
* Custom type conversions override the default
*/
private Map<Class, Converter> customConverterMap;
/**
* Need Head
*/
private Boolean needHead;
/**
* Custom type handler override the default
*/
private List<WriteHandler> customWriteHandlerList;
/** /**
* column with * column with
* *
@ -72,7 +37,21 @@ public class Sheet {
@Deprecated @Deprecated
private TableStyle tableStyle; private TableStyle tableStyle;
public Sheet() {} public Sheet() {
super();
}
/**
* Create sheet
*
* @param sheetNo
* @param sheetName
*/
public Sheet(Integer sheetNo, String sheetName) {
super();
this.sheetNo = sheetNo;
this.sheetName = sheetName;
}
/** /**
* It was 'sheetNo' starting from 1 and now it is starting from 0 * It was 'sheetNo' starting from 1 and now it is starting from 0
@ -83,8 +62,9 @@ public class Sheet {
*/ */
@Deprecated @Deprecated
public Sheet(int sheetNo, int readHeadRowNumber) { public Sheet(int sheetNo, int readHeadRowNumber) {
super();
this.sheetNo = sheetNo - 1; this.sheetNo = sheetNo - 1;
this.readHeadRowNumber = readHeadRowNumber; setReadHeadRowNumber(readHeadRowNumber);
} }
/** /**
@ -95,6 +75,7 @@ public class Sheet {
*/ */
@Deprecated @Deprecated
public Sheet(int sheetNo) { public Sheet(int sheetNo) {
super();
this.sheetNo = sheetNo - 1; this.sheetNo = sheetNo - 1;
} }
@ -108,9 +89,10 @@ public class Sheet {
*/ */
@Deprecated @Deprecated
public Sheet(int sheetNo, int readHeadRowNumber, Class clazz) { public Sheet(int sheetNo, int readHeadRowNumber, Class clazz) {
super();
this.sheetNo = sheetNo - 1; this.sheetNo = sheetNo - 1;
this.readHeadRowNumber = readHeadRowNumber; setReadHeadRowNumber(readHeadRowNumber);
this.clazz = clazz; setClazz(clazz);
} }
/** /**
@ -123,11 +105,13 @@ public class Sheet {
*/ */
@Deprecated @Deprecated
public Sheet(int sheetNo, int readHeadRowNumber, Class clazz, String sheetName, List<List<String>> head) { public Sheet(int sheetNo, int readHeadRowNumber, Class clazz, String sheetName, List<List<String>> head) {
super();
this.sheetNo = sheetNo - 1; this.sheetNo = sheetNo - 1;
this.clazz = clazz;
this.readHeadRowNumber = readHeadRowNumber;
this.sheetName = sheetName; this.sheetName = sheetName;
this.head = head;
setReadHeadRowNumber(readHeadRowNumber);
setClazz(clazz);
setHead(head);
} }
public Integer getSheetNo() { public Integer getSheetNo() {
@ -146,62 +130,6 @@ public class Sheet {
this.sheetName = sheetName; this.sheetName = sheetName;
} }
public Integer getReadHeadRowNumber() {
return readHeadRowNumber;
}
public void setReadHeadRowNumber(Integer readHeadRowNumber) {
this.readHeadRowNumber = readHeadRowNumber;
}
public Integer getWriteRelativeHeadRowIndex() {
return writeRelativeHeadRowIndex;
}
public void setWriteRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) {
this.writeRelativeHeadRowIndex = writeRelativeHeadRowIndex;
}
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 Map<Class, Converter> getCustomConverterMap() {
return customConverterMap;
}
public void setCustomConverterMap(Map<Class, Converter> customConverterMap) {
this.customConverterMap = customConverterMap;
}
public Boolean getNeedHead() {
return needHead;
}
public void setNeedHead(Boolean needHead) {
this.needHead = needHead;
}
public List<WriteHandler> getCustomWriteHandlerList() {
return customWriteHandlerList;
}
public void setCustomWriteHandlerList(List<WriteHandler> customWriteHandlerList) {
this.customWriteHandlerList = customWriteHandlerList;
}
public Map<Integer, Integer> getColumnWidthMap() { public Map<Integer, Integer> getColumnWidthMap() {
return columnWidthMap; return columnWidthMap;
} }
@ -225,7 +153,7 @@ public class Sheet {
*/ */
@Deprecated @Deprecated
public void setStartRow(int writeRelativeHeadRowIndex) { public void setStartRow(int writeRelativeHeadRowIndex) {
this.writeRelativeHeadRowIndex = writeRelativeHeadRowIndex; setWriteRelativeHeadRowIndex(writeRelativeHeadRowIndex);
} }
/** /**
@ -235,7 +163,7 @@ public class Sheet {
*/ */
@Deprecated @Deprecated
public void setHeadLineMun(int readHeadRowNumber) { public void setHeadLineMun(int readHeadRowNumber) {
this.readHeadRowNumber = readHeadRowNumber; setReadHeadRowNumber(readHeadRowNumber);
} }
@Override @Override

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

@ -1,46 +1,17 @@
package com.alibaba.excel.metadata; package com.alibaba.excel.metadata;
import java.util.List; import com.alibaba.excel.write.style.RowCellStyleStrategy;
import java.util.Map;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.write.handler.WriteHandler;
/** /**
* table * table
* *
* @author jipengfei * @author jipengfei
*/ */
public class Table { public class Table extends BasicParameter {
/** /**
* Starting from 0 * Starting from 0
*/ */
private Integer tableNo; private Integer tableNo;
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*/
private Integer writeRelativeHeadRowIndex;
/**
* You can only choose one of the {@link Table#head} and {@link Table#clazz}
*/
private List<List<String>> head;
/**
* You can only choose one of the {@link Table#head} and {@link Table#clazz}
*/
private Class clazz;
/**
* Custom type conversions override the default
*/
private Map<Class, Converter> customConverterMap;
/**
* Need Head
*/
private Boolean needHead;
/**
* Custom type handler override the default
*/
private List<WriteHandler> customWriteHandlerList;
/** /**
* *
* @deprecated please use{@link RowCellStyleStrategy} * @deprecated please use{@link RowCellStyleStrategy}
@ -48,7 +19,12 @@ public class Table {
@Deprecated @Deprecated
private TableStyle tableStyle; private TableStyle tableStyle;
public Table() {
super();
}
public Table(Integer tableNo) { public Table(Integer tableNo) {
super();
this.tableNo = tableNo; this.tableNo = tableNo;
} }
@ -60,54 +36,6 @@ public class Table {
this.tableNo = tableNo; this.tableNo = tableNo;
} }
public Integer getWriteRelativeHeadRowIndex() {
return writeRelativeHeadRowIndex;
}
public void setWriteRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) {
this.writeRelativeHeadRowIndex = writeRelativeHeadRowIndex;
}
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 Map<Class, Converter> getCustomConverterMap() {
return customConverterMap;
}
public void setCustomConverterMap(Map<Class, Converter> customConverterMap) {
this.customConverterMap = customConverterMap;
}
public Boolean getNeedHead() {
return needHead;
}
public void setNeedHead(Boolean needHead) {
this.needHead = needHead;
}
public List<WriteHandler> getCustomWriteHandlerList() {
return customWriteHandlerList;
}
public void setCustomWriteHandlerList(List<WriteHandler> customWriteHandlerList) {
this.customWriteHandlerList = customWriteHandlerList;
}
public TableStyle getTableStyle() { public TableStyle getTableStyle() {
return tableStyle; return tableStyle;
} }

103
src/main/java/com/alibaba/excel/metadata/Workbook.java

@ -2,12 +2,7 @@ package com.alibaba.excel.metadata;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
@ -16,7 +11,7 @@ import com.alibaba.excel.write.handler.WriteHandler;
* *
* @author zhuangjiaju * @author zhuangjiaju
**/ **/
public class Workbook { public class Workbook extends BasicParameter {
/** /**
* Excel type * Excel type
*/ */
@ -30,37 +25,9 @@ public class Workbook {
*/ */
private InputStream templateInputStream; private InputStream templateInputStream;
/** /**
* Count the number of added heads when read sheet. * Default true
*
* <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; private Boolean autoCloseStream;
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*/
private Integer writeRelativeHeadRowIndex;
/**
* You can only choose one of the {@link Workbook#head} and {@link Workbook#clazz}
*/
private List<List<String>> head;
/**
* You can only choose one of the {@link Workbook#head} and {@link Workbook#clazz}
*/
private Class clazz;
/**
* Need Head
*/
private Boolean needHead;
/**
* Custom type conversions override the default
*/
private Map<Class, Converter> customConverterMap = new HashMap<Class, Converter>();
/**
* Custom type handler override the default
*/
private List<WriteHandler> customWriteHandlerList = new ArrayList<WriteHandler>();
/** /**
* Write handler * Write handler
* *
@ -93,62 +60,6 @@ public class Workbook {
this.templateInputStream = templateInputStream; this.templateInputStream = templateInputStream;
} }
public Integer getReadHeadRowNumber() {
return readHeadRowNumber;
}
public void setReadHeadRowNumber(Integer readHeadRowNumber) {
this.readHeadRowNumber = readHeadRowNumber;
}
public Integer getWriteRelativeHeadRowIndex() {
return writeRelativeHeadRowIndex;
}
public void setWriteRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) {
this.writeRelativeHeadRowIndex = writeRelativeHeadRowIndex;
}
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 getNeedHead() {
return needHead;
}
public void setNeedHead(Boolean needHead) {
this.needHead = needHead;
}
public Map<Class, Converter> getCustomConverterMap() {
return customConverterMap;
}
public void setCustomConverterMap(Map<Class, Converter> customConverterMap) {
this.customConverterMap = customConverterMap;
}
public List<WriteHandler> getCustomWriteHandlerList() {
return customWriteHandlerList;
}
public void setCustomWriteHandlerList(List<WriteHandler> customWriteHandlerList) {
this.customWriteHandlerList = customWriteHandlerList;
}
public com.alibaba.excel.event.WriteHandler getWriteHandler() { public com.alibaba.excel.event.WriteHandler getWriteHandler() {
return writeHandler; return writeHandler;
} }
@ -156,4 +67,12 @@ public class Workbook {
public void setWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) { public void setWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) {
this.writeHandler = writeHandler; this.writeHandler = writeHandler;
} }
public Boolean getAutoCloseStream() {
return autoCloseStream;
}
public void setAutoCloseStream(Boolean autoCloseStream) {
this.autoCloseStream = autoCloseStream;
}
} }

224
src/main/java/com/alibaba/excel/metadata/holder/AbstractConfigurationSelector.java

@ -0,0 +1,224 @@
package com.alibaba.excel.metadata.holder;
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 com.alibaba.excel.converters.Converter;
import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.event.Order;
import com.alibaba.excel.metadata.ExcelHeadProperty;
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;
/**
* sheet holder
*
* @author zhuangjiaju
*/
public abstract class AbstractConfigurationSelector implements ConfigurationSelector {
/**
* Need Head
*/
private Boolean needHead;
/**
* Write handler for workbook
*/
private Map<Class<? extends WriteHandler>, List<WriteHandler>> writeHandlerMap;
/**
* Converter for workbook
*/
private Map<Class, Converter> converterMap;
/**
* 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;
/**
* You can only choose one of the {@link AbstractConfigurationSelector#head} and
* {@link AbstractConfigurationSelector#clazz}
*/
private List<List<String>> head;
/**
* You can only choose one of the {@link AbstractConfigurationSelector#head} and
* {@link AbstractConfigurationSelector#clazz}
*/
private Class clazz;
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 Map<Class, Converter> getConverterMap() {
return converterMap;
}
public void setConverterMap(Map<Class, Converter> converterMap) {
this.converterMap = converterMap;
}
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;
}
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;
}
@Override
public Map<Class<? extends WriteHandler>, List<WriteHandler>> writeHandlerMap() {
return getWriteHandlerMap();
}
@Override
public Map<Class, Converter> converterMap() {
return getConverterMap();
}
@Override
public boolean needHead() {
return getNeedHead();
}
@Override
public int writeRelativeHeadRowIndex() {
return getWriteRelativeHeadRowIndex();
}
@Override
public ExcelHeadProperty excelHeadProperty() {
return getExcelHeadProperty();
}
@Override
public boolean isNew() {
return getNewInitialization();
}
}

183
src/main/java/com/alibaba/excel/metadata/holder/SheetHolder.java

@ -1,21 +1,26 @@
package com.alibaba.excel.metadata.holder; package com.alibaba.excel.metadata.holder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.ExcelHeadProperty; import com.alibaba.excel.metadata.CellStyle;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.style.RowCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractHeadColumnWidthStyleStrategy;
/** /**
* sheet holder * sheet holder
* *
* @author zhuangjiaju * @author zhuangjiaju
*/ */
public class SheetHolder implements ConfigurationSelector { public class SheetHolder extends AbstractConfigurationSelector {
/*** /***
* poi sheet * poi sheet
*/ */
@ -36,35 +41,84 @@ public class SheetHolder implements ConfigurationSelector {
* has been initialized table * has been initialized table
*/ */
private Map<Integer, TableHolder> hasBeenInitializedTable; private Map<Integer, TableHolder> hasBeenInitializedTable;
/**
* Need Head
*/
private Boolean needHead;
/**
* Write handler for workbook
*/
private List<WriteHandler> writeHandlerList;
/**
* Converter for workbook
*/
private Map<Class, Converter> converterMap;
/** /**
* current param * current param
*/ */
private com.alibaba.excel.metadata.Sheet sheetParam; private com.alibaba.excel.metadata.Sheet sheetParam;
public SheetHolder(com.alibaba.excel.metadata.Sheet sheet, WorkbookHolder workbookHolder) {
super();
this.sheetParam = sheet;
this.parentWorkBook = workbookHolder;
boolean noHead = (sheet.getHead() == null || sheet.getHead().isEmpty()) && sheet.getClazz() == null;
if (noHead) {
// Use parent
setHead(workbookHolder.getHead());
setClazz(workbookHolder.getClazz());
} else {
setHead(sheet.getHead());
setClazz(sheet.getClazz());
}
setNewInitialization(Boolean.TRUE);
if (sheet.getNeedHead() == null) {
setNeedHead(workbookHolder.needHead());
} else {
setNeedHead(sheet.getNeedHead());
}
if (sheet.getWriteRelativeHeadRowIndex() == null) {
setWriteRelativeHeadRowIndex(workbookHolder.writeRelativeHeadRowIndex());
} else {
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());
}
setWriteHandlerMap(sortAndClearUpHandler(handlerList, workbookHolder.getWriteHandlerMap()));
Map<Class, Converter> converterMap = new HashMap<Class, Converter>(workbookHolder.converterMap());
if (sheet.getCustomConverterMap() != null && !sheet.getCustomConverterMap().isEmpty()) {
converterMap.putAll(sheet.getCustomConverterMap());
}
setConverterMap(converterMap);
setHasBeenInitializedTable(new HashMap<Integer, TableHolder>());
}
/** /**
* Excel head property * Compatible with old code
*/
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; @Deprecated
private 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 int 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() { public Sheet getSheet() {
return sheet; return sheet;
@ -106,30 +160,6 @@ public class SheetHolder implements ConfigurationSelector {
this.hasBeenInitializedTable = hasBeenInitializedTable; this.hasBeenInitializedTable = hasBeenInitializedTable;
} }
public Boolean getNeedHead() {
return needHead;
}
public void setNeedHead(Boolean needHead) {
this.needHead = needHead;
}
public List<WriteHandler> getWriteHandlerList() {
return writeHandlerList;
}
public void setWriteHandlerList(List<WriteHandler> writeHandlerList) {
this.writeHandlerList = writeHandlerList;
}
public Map<Class, Converter> getConverterMap() {
return converterMap;
}
public void setConverterMap(Map<Class, Converter> converterMap) {
this.converterMap = converterMap;
}
public com.alibaba.excel.metadata.Sheet getSheetParam() { public com.alibaba.excel.metadata.Sheet getSheetParam() {
return sheetParam; return sheetParam;
} }
@ -137,59 +167,4 @@ public class SheetHolder implements ConfigurationSelector {
public void setSheetParam(com.alibaba.excel.metadata.Sheet sheetParam) { public void setSheetParam(com.alibaba.excel.metadata.Sheet sheetParam) {
this.sheetParam = sheetParam; this.sheetParam = sheetParam;
} }
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;
}
@Override
public List<WriteHandler> writeHandlerList() {
return getWriteHandlerList();
}
@Override
public Map<Class, Converter> converterMap() {
return getConverterMap();
}
@Override
public boolean needHead() {
return getNeedHead();
}
@Override
public int writeRelativeHeadRowIndex() {
return getWriteRelativeHeadRowIndex();
}
@Override
public ExcelHeadProperty excelHeadProperty() {
return getExcelHeadProperty();
}
@Override
public boolean isNew() {
return getNewInitialization();
}
} }

166
src/main/java/com/alibaba/excel/metadata/holder/TableHolder.java

@ -1,19 +1,23 @@
package com.alibaba.excel.metadata.holder; package com.alibaba.excel.metadata.holder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.ExcelHeadProperty; import com.alibaba.excel.metadata.CellStyle;
import com.alibaba.excel.metadata.Table; import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.style.RowCellStyleStrategy;
/** /**
* sheet holder * sheet holder
* *
* @author zhuangjiaju * @author zhuangjiaju
*/ */
public class TableHolder implements ConfigurationSelector { public class TableHolder extends AbstractConfigurationSelector {
/*** /***
* poi sheet * poi sheet
*/ */
@ -22,35 +26,69 @@ public class TableHolder implements ConfigurationSelector {
* tableNo * tableNo
*/ */
private Integer tableNo; private Integer tableNo;
/**
* Need Head
*/
private Boolean needHead;
/**
* Write handler for workbook
*/
private List<WriteHandler> writeHandlerList;
/**
* Converter for workbook
*/
private Map<Class, Converter> converterMap;
/**
* Excel head property
*/
private ExcelHeadProperty excelHeadProperty;
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*/
private Integer writeRelativeHeadRowIndex;
/** /**
* current table param * current table param
*/ */
private com.alibaba.excel.metadata.Table tableParam; private com.alibaba.excel.metadata.Table tableParam;
public TableHolder(com.alibaba.excel.metadata.Table table, SheetHolder sheetHolder) {
super();
this.tableParam = table;
this.parentSheet = sheetHolder;
this.tableNo = table.getTableNo();
boolean noHead = (table.getHead() == null || table.getHead().isEmpty()) && table.getClazz() == null;
if (noHead) {
// Use parent
setHead(sheetHolder.getHead());
setClazz(sheetHolder.getClazz());
} else {
setHead(table.getHead());
setClazz(table.getClazz());
}
setNewInitialization(Boolean.TRUE);
if (table.getNeedHead() == null) {
setNeedHead(sheetHolder.needHead());
} else {
setNeedHead(table.getNeedHead());
}
if (table.getWriteRelativeHeadRowIndex() == null) {
setWriteRelativeHeadRowIndex(sheetHolder.writeRelativeHeadRowIndex());
} else {
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());
}
setWriteHandlerMap(sortAndClearUpHandler(handlerList, sheetHolder.getWriteHandlerMap()));
Map<Class, Converter> converterMap = new HashMap<Class, Converter>(sheetHolder.converterMap());
if (table.getCustomConverterMap() != null && !table.getCustomConverterMap().isEmpty()) {
converterMap.putAll(table.getCustomConverterMap());
}
setConverterMap(converterMap);
}
/** /**
* Record whether it's new or from cache * Compatible with old code
*/ */
private Boolean newInitialization; @Deprecated
private void compatibleOldCode(com.alibaba.excel.metadata.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() { public SheetHolder getParentSheet() {
return parentSheet; return parentSheet;
@ -68,46 +106,6 @@ public class TableHolder implements ConfigurationSelector {
this.tableNo = tableNo; this.tableNo = tableNo;
} }
public Boolean getNeedHead() {
return needHead;
}
public void setNeedHead(Boolean needHead) {
this.needHead = needHead;
}
public List<WriteHandler> getWriteHandlerList() {
return writeHandlerList;
}
public void setWriteHandlerList(List<WriteHandler> writeHandlerList) {
this.writeHandlerList = writeHandlerList;
}
public Map<Class, Converter> getConverterMap() {
return converterMap;
}
public void setConverterMap(Map<Class, Converter> converterMap) {
this.converterMap = converterMap;
}
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 Table getTableParam() { public Table getTableParam() {
return tableParam; return tableParam;
} }
@ -115,42 +113,4 @@ public class TableHolder implements ConfigurationSelector {
public void setTableParam(Table tableParam) { public void setTableParam(Table tableParam) {
this.tableParam = tableParam; this.tableParam = tableParam;
} }
public Boolean getNewInitialization() {
return newInitialization;
}
public void setNewInitialization(Boolean newInitialization) {
this.newInitialization = newInitialization;
}
@Override
public List<WriteHandler> writeHandlerList() {
return getWriteHandlerList();
}
@Override
public Map<Class, Converter> converterMap() {
return getConverterMap();
}
@Override
public boolean needHead() {
return getNeedHead();
}
@Override
public int writeRelativeHeadRowIndex() {
return getWriteRelativeHeadRowIndex();
}
@Override
public ExcelHeadProperty excelHeadProperty() {
return getExcelHeadProperty();
}
@Override
public boolean isNew() {
return getNewInitialization();
}
} }

135
src/main/java/com/alibaba/excel/metadata/holder/WorkbookHolder.java

@ -2,13 +2,16 @@ package com.alibaba.excel.metadata.holder;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.ExcelHeadProperty; import com.alibaba.excel.converters.DefaultConverterBuilder;
import com.alibaba.excel.write.handler.DefaultWriteHandlerBuilder;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
/** /**
@ -16,31 +19,15 @@ import com.alibaba.excel.write.handler.WriteHandler;
* *
* @author zhuangjiaju * @author zhuangjiaju
*/ */
public class WorkbookHolder implements ConfigurationSelector { public class WorkbookHolder extends AbstractConfigurationSelector {
/*** /***
* poi Workbook * poi Workbook
*/ */
private Workbook workbook; private Workbook workbook;
/**
* Need Head
*/
private Boolean needHead;
/**
* Write handler for workbook
*/
private List<WriteHandler> writeHandlerList;
/**
* Converter for workbook
*/
private Map<Class, Converter> converterMap;
/** /**
* prevent duplicate creation of sheet objects * prevent duplicate creation of sheet objects
*/ */
private Map<Integer, SheetHolder> hasBeenInitializedSheet; private Map<Integer, SheetHolder> hasBeenInitializedSheet;
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*/
private Integer writeRelativeHeadRowIndex;
/** /**
* current param * current param
*/ */
@ -53,6 +40,56 @@ public class WorkbookHolder implements ConfigurationSelector {
* Template input stream * Template input stream
*/ */
private InputStream templateInputStream; private InputStream templateInputStream;
/**
* Default true
*/
private Boolean autoCloseStream;
/**
* Write handler
*
* @deprecated please use {@link WriteHandler}
*/
@Deprecated
private com.alibaba.excel.event.WriteHandler writeHandler;
public WorkbookHolder(com.alibaba.excel.metadata.Workbook workbook) {
super();
this.workbookParam = workbook;
this.templateInputStream = workbook.getTemplateInputStream();
this.outputStream = workbook.getOutputStream();
this.templateInputStream = workbook.getTemplateInputStream();
setHead(workbook.getHead());
setClazz(workbook.getClazz());
setNewInitialization(Boolean.TRUE);
if (workbook.getAutoCloseStream() == null) {
setAutoCloseStream(Boolean.TRUE);
} else {
setAutoCloseStream(workbook.getAutoCloseStream());
}
if (workbook.getNeedHead() == null) {
setNeedHead(Boolean.TRUE);
} else {
setNeedHead(workbook.getNeedHead());
}
if (workbook.getWriteRelativeHeadRowIndex() == null) {
setWriteRelativeHeadRowIndex(0);
} else {
setWriteRelativeHeadRowIndex(workbook.getWriteRelativeHeadRowIndex());
}
List<WriteHandler> handlerList = new ArrayList<WriteHandler>();
if (workbook.getCustomWriteHandlerList() != null && !workbook.getCustomWriteHandlerList().isEmpty()) {
handlerList.addAll(workbook.getCustomWriteHandlerList());
}
handlerList.addAll(DefaultWriteHandlerBuilder.loadDefaultHandler());
setWriteHandlerMap(sortAndClearUpHandler(handlerList, null));
Map<Class, Converter> converterMap = DefaultConverterBuilder.loadDefaultWriteConverter();
if (workbook.getCustomConverterMap() != null && !workbook.getCustomConverterMap().isEmpty()) {
converterMap.putAll(workbook.getCustomConverterMap());
}
setConverterMap(converterMap);
setHasBeenInitializedSheet(new HashMap<Integer, SheetHolder>());
}
public Workbook getWorkbook() { public Workbook getWorkbook() {
return workbook; return workbook;
@ -62,30 +99,6 @@ public class WorkbookHolder implements ConfigurationSelector {
this.workbook = workbook; this.workbook = workbook;
} }
public Boolean getNeedHead() {
return needHead;
}
public void setNeedHead(Boolean needHead) {
this.needHead = needHead;
}
public List<WriteHandler> getWriteHandlerList() {
return writeHandlerList;
}
public void setWriteHandlerList(List<WriteHandler> writeHandlerList) {
this.writeHandlerList = writeHandlerList;
}
public Map<Class, Converter> getConverterMap() {
return converterMap;
}
public void setConverterMap(Map<Class, Converter> converterMap) {
this.converterMap = converterMap;
}
public Map<Integer, SheetHolder> getHasBeenInitializedSheet() { public Map<Integer, SheetHolder> getHasBeenInitializedSheet() {
return hasBeenInitializedSheet; return hasBeenInitializedSheet;
} }
@ -94,14 +107,6 @@ public class WorkbookHolder implements ConfigurationSelector {
this.hasBeenInitializedSheet = hasBeenInitializedSheet; this.hasBeenInitializedSheet = hasBeenInitializedSheet;
} }
public Integer getWriteRelativeHeadRowIndex() {
return writeRelativeHeadRowIndex;
}
public void setWriteRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) {
this.writeRelativeHeadRowIndex = writeRelativeHeadRowIndex;
}
public com.alibaba.excel.metadata.Workbook getWorkbookParam() { public com.alibaba.excel.metadata.Workbook getWorkbookParam() {
return workbookParam; return workbookParam;
} }
@ -126,33 +131,19 @@ public class WorkbookHolder implements ConfigurationSelector {
this.templateInputStream = templateInputStream; this.templateInputStream = templateInputStream;
} }
@Override public com.alibaba.excel.event.WriteHandler getWriteHandler() {
public List<WriteHandler> writeHandlerList() { return writeHandler;
return getWriteHandlerList();
}
@Override
public Map<Class, Converter> converterMap() {
return getConverterMap();
}
@Override
public boolean needHead() {
return getNeedHead();
} }
@Override public void setWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) {
public int writeRelativeHeadRowIndex() { this.writeHandler = writeHandler;
return getWriteRelativeHeadRowIndex();
} }
@Override public Boolean getAutoCloseStream() {
public ExcelHeadProperty excelHeadProperty() { return autoCloseStream;
return null;
} }
@Override public void setAutoCloseStream(Boolean autoCloseStream) {
public boolean isNew() { this.autoCloseStream = autoCloseStream;
return true;
} }
} }

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

@ -45,7 +45,7 @@ public class StyleUtil {
* @return * @return
*/ */
public static CellStyle buildHeadCellStyle(Workbook workbook, com.alibaba.excel.metadata.CellStyle cs) { public static CellStyle buildHeadCellStyle(Workbook workbook, com.alibaba.excel.metadata.CellStyle cs) {
CellStyle cellStyle = workbook.createCellStyle(); CellStyle cellStyle = buildDefaultCellStyle(workbook);
if (cs == null) { if (cs == null) {
return cellStyle; return cellStyle;
} }
@ -61,7 +61,7 @@ public class StyleUtil {
*/ */
public static CellStyle buildHeadCellStyle(Workbook workbook, com.alibaba.excel.metadata.Font f, public static CellStyle buildHeadCellStyle(Workbook workbook, com.alibaba.excel.metadata.Font f,
IndexedColors indexedColors) { IndexedColors indexedColors) {
CellStyle cellStyle = workbook.createCellStyle(); CellStyle cellStyle = buildDefaultCellStyle(workbook);
return buildCellStyle(workbook, cellStyle, f, indexedColors); return buildCellStyle(workbook, cellStyle, f, indexedColors);
} }
@ -73,7 +73,7 @@ public class StyleUtil {
* @return * @return
*/ */
public static CellStyle buildContentCellStyle(Workbook workbook, com.alibaba.excel.metadata.CellStyle cs) { public static CellStyle buildContentCellStyle(Workbook workbook, com.alibaba.excel.metadata.CellStyle cs) {
CellStyle cellStyle = buildDefaultCellStyle(workbook); CellStyle cellStyle = workbook.createCellStyle();
if (cs == null) { if (cs == null) {
return cellStyle; return cellStyle;
} }
@ -89,7 +89,7 @@ public class StyleUtil {
*/ */
public static CellStyle buildContentCellStyle(Workbook workbook, com.alibaba.excel.metadata.Font f, public static CellStyle buildContentCellStyle(Workbook workbook, com.alibaba.excel.metadata.Font f,
IndexedColors indexedColors) { IndexedColors indexedColors) {
CellStyle cellStyle = buildDefaultCellStyle(workbook); CellStyle cellStyle = workbook.createCellStyle();
return buildCellStyle(workbook, cellStyle, f, indexedColors); return buildCellStyle(workbook, cellStyle, f, indexedColors);
} }

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

@ -40,6 +40,10 @@ public class WorkBookUtil {
return sheet.createRow(rowNum); return sheet.createRow(rowNum);
} }
public static Cell createCell(Row row, int colNum) {
return row.createCell(colNum);
}
public static Cell createCell(Row row, int colNum, CellStyle cellStyle) { public static Cell createCell(Row row, int colNum, CellStyle cellStyle) {
Cell cell = row.createCell(colNum); Cell cell = row.createCell(colNum);
cell.setCellStyle(cellStyle); cell.setCellStyle(cellStyle);

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

@ -12,12 +12,16 @@ import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.exception.ExcelDataConvertException; import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.ExcelColumnProperty; import com.alibaba.excel.metadata.ExcelColumnProperty;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table; import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.metadata.holder.ConfigurationSelector; import com.alibaba.excel.metadata.holder.ConfigurationSelector;
import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.POITempFile; import com.alibaba.excel.util.POITempFile;
import com.alibaba.excel.util.WorkBookUtil; import com.alibaba.excel.util.WorkBookUtil;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.WriteHandler;
import net.sf.cglib.beans.BeanMap; import net.sf.cglib.beans.BeanMap;
@ -43,9 +47,9 @@ public class ExcelBuilderImpl implements ExcelBuilder {
if (context.currentConfigurationSelector().isNew()) { if (context.currentConfigurationSelector().isNew()) {
rowNum += context.currentConfigurationSelector().writeRelativeHeadRowIndex(); rowNum += context.currentConfigurationSelector().writeRelativeHeadRowIndex();
} }
for (int i = 0; i < data.size(); i++) { for (int relativeRowIndex = 0; relativeRowIndex < data.size(); relativeRowIndex++) {
int n = i + rowNum + 1; int n = relativeRowIndex + rowNum + 1;
addOneRowOfDataToExcel(data.get(i), n); addOneRowOfDataToExcel(data.get(relativeRowIndex), n, relativeRowIndex);
} }
} }
@ -72,40 +76,113 @@ public class ExcelBuilderImpl implements ExcelBuilder {
context.currentSheetHolder().getSheet().addMergedRegion(cra); context.currentSheetHolder().getSheet().addMergedRegion(cra);
} }
private void addOneRowOfDataToExcel(Object oneRowData, int n) { 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.currentSheetHolder().getSheet(), n);
afterRowCreate(row, relativeRowIndex);
if (oneRowData instanceof List) { if (oneRowData instanceof List) {
addBasicTypeToExcel((List)oneRowData, row); addBasicTypeToExcel((List)oneRowData, row, relativeRowIndex);
} else { } else {
addJavaObjectToExcel(oneRowData, row); addJavaObjectToExcel(oneRowData, row, relativeRowIndex);
} }
} }
private void addBasicTypeToExcel(List<Object> oneRowData, Row row) { private void beforeRowCreate(int rowIndex, int relativeRowIndex) {
List<WriteHandler> handlerList =
context.currentConfigurationSelector().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);
}
}
}
private void afterRowCreate(Row row, int relativeRowIndex) {
List<WriteHandler> handlerList =
context.currentConfigurationSelector().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);
}
}
if (null != context.currentWorkbookHolder().getWriteHandler()) {
context.currentWorkbookHolder().getWriteHandler().row(row.getRowNum(), row);
}
}
private void addBasicTypeToExcel(List<Object> oneRowData, Row row, int relativeRowIndex) {
if (CollectionUtils.isEmpty(oneRowData)) { if (CollectionUtils.isEmpty(oneRowData)) {
return; return;
} }
List<Head> headList = context.currentConfigurationSelector().excelHeadProperty().getHeadList();
for (int i = 0; i < oneRowData.size(); i++) { for (int i = 0; i < oneRowData.size(); i++) {
Cell cell = WorkBookUtil.createCell(row, i, null); Head head = i <= headList.size() ? headList.get(i) : null;
beforeCellCreate(row, head, relativeRowIndex);
Cell cell = WorkBookUtil.createCell(row, i);
Object value = oneRowData.get(i); Object value = oneRowData.get(i);
converterAndSet(context.currentConfigurationSelector(), value.getClass(), cell, value, null); converterAndSet(context.currentConfigurationSelector(), value.getClass(), cell, value, null);
afterCellCreate(head, cell, relativeRowIndex);
} }
} }
private void addJavaObjectToExcel(Object oneRowData, Row row) { private void addJavaObjectToExcel(Object oneRowData, Row row, int relativeRowIndex) {
ConfigurationSelector currentConfigurationSelector = context.currentConfigurationSelector(); ConfigurationSelector currentConfigurationSelector = context.currentConfigurationSelector();
int i = 0; int i = 0;
BeanMap beanMap = BeanMap.create(oneRowData); BeanMap beanMap = BeanMap.create(oneRowData);
List<Head> headList = context.currentConfigurationSelector().excelHeadProperty().getHeadList();
for (ExcelColumnProperty excelHeadProperty : currentConfigurationSelector.excelHeadProperty() for (ExcelColumnProperty excelHeadProperty : currentConfigurationSelector.excelHeadProperty()
.getColumnPropertyList()) { .getColumnPropertyList()) {
Cell cell = WorkBookUtil.createCell(row, i, null); Head head = i <= headList.size() ? headList.get(i) : null;
beforeCellCreate(row, head, relativeRowIndex);
Cell cell = WorkBookUtil.createCell(row, i);
Object value = beanMap.get(excelHeadProperty.getField().getName()); Object value = beanMap.get(excelHeadProperty.getField().getName());
converterAndSet(currentConfigurationSelector, excelHeadProperty.getField().getType(), cell, value, converterAndSet(currentConfigurationSelector, excelHeadProperty.getField().getType(), cell, value,
excelHeadProperty); excelHeadProperty);
afterCellCreate(head, cell, relativeRowIndex);
i++; i++;
} }
} }
private void beforeCellCreate(Row row, Head head, int relativeRowIndex) {
List<WriteHandler> handlerList =
context.currentConfigurationSelector().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);
}
}
}
private void afterCellCreate(Head head, Cell cell, int relativeRowIndex) {
List<WriteHandler> handlerList =
context.currentConfigurationSelector().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);
}
}
if (null != context.currentWorkbookHolder().getWriteHandler()) {
context.currentWorkbookHolder().getWriteHandler().cell(cell.getRowIndex(), cell);
}
}
private void converterAndSet(ConfigurationSelector currentConfigurationSelector, Class clazz, Cell cell, private void converterAndSet(ConfigurationSelector currentConfigurationSelector, Class clazz, Cell cell,
Object value, ExcelColumnProperty excelHeadProperty) { Object value, ExcelColumnProperty excelHeadProperty) {
if (value == null) { if (value == null) {
@ -117,7 +194,7 @@ public class ExcelBuilderImpl implements ExcelBuilder {
"Can not find 'Converter' support class " + clazz.getSimpleName() + "."); "Can not find 'Converter' support class " + clazz.getSimpleName() + ".");
} }
CellData cellData = null; CellData cellData;
try { try {
cellData = converter.convertToExcelData(value, excelHeadProperty); cellData = converter.convertToExcelData(value, excelHeadProperty);
} catch (Exception e) { } catch (Exception e) {
@ -130,13 +207,13 @@ public class ExcelBuilderImpl implements ExcelBuilder {
} }
switch (cellData.getType()) { switch (cellData.getType()) {
case STRING: case STRING:
cell.setCellValue(cell.getStringCellValue()); cell.setCellValue(cellData.getStringValue());
return; return;
case BOOLEAN: case BOOLEAN:
cell.setCellValue(cell.getBooleanCellValue()); cell.setCellValue(cellData.getBooleanValue());
return; return;
case NUMBER: case NUMBER:
cell.setCellValue(cell.getNumericCellValue()); cell.setCellValue(cellData.getDoubleValue());
return; return;
default: default:
throw new ExcelDataConvertException("Not supported data:" + value + " return type:" + cell.getCellType() throw new ExcelDataConvertException("Not supported data:" + value + " return type:" + cell.getCellType()

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

@ -10,10 +10,10 @@ import java.net.URI;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.Workbook; import com.alibaba.excel.metadata.Workbook;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
@ -25,102 +25,158 @@ import com.alibaba.excel.write.handler.WriteHandler;
*/ */
public class ExcelWriterBuilder { public class ExcelWriterBuilder {
/** /**
* Excel type * Workbook
*/ */
private ExcelTypeEnum excelType; private Workbook workbook;
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;
}
/** /**
* Final output stream * Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*
* @param writeRelativeHeadRowIndex
* @return
*/ */
private OutputStream outputStream; public ExcelWriterBuilder writeRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) {
workbook.setWriteRelativeHeadRowIndex(writeRelativeHeadRowIndex);
return this;
}
/** /**
* Template input stream * You can only choose one of the {@link ExcelWriterBuilder#head(List)} and
* {@link ExcelWriterBuilder#head(Class)}
*
* @param head
* @return
*/ */
private InputStream templateInputStream; public ExcelWriterBuilder head(List<List<String>> head) {
workbook.setHead(head);
return this;
}
/** /**
* Custom type conversions override the default * You can only choose one of the {@link ExcelWriterBuilder#head(List)} and
* {@link ExcelWriterBuilder#head(Class)}
*
* @param clazz
* @return
*/ */
private Map<Class, Converter> customConverterMap = new HashMap<Class, Converter>(); public ExcelWriterBuilder head(Class clazz) {
workbook.setClazz(clazz);
return this;
}
/** /**
* Need Head * Need Head
*/ */
private Boolean needHead; public ExcelWriterBuilder needHead(Boolean needHead) {
workbook.setNeedHead(needHead);
return this;
}
/** /**
* Custom type handler override the default * Default true
*
* @param autoCloseStream
* @return
*/ */
private List<WriteHandler> customWriteHandlerList = new ArrayList<WriteHandler>(); public ExcelWriterBuilder autoCloseStream(Boolean autoCloseStream) {
workbook.setAutoCloseStream(autoCloseStream);
return this;
}
/** /**
* Write handler * Custom type conversions override the default.
* *
* @deprecated please use {@link WriteHandler} * @param converter
* @return
*/ */
@Deprecated public ExcelWriterBuilder registerConverter(Converter converter) {
private com.alibaba.excel.event.WriteHandler writeHandler; if (workbook.getCustomConverterMap() == null) {
workbook.setCustomConverterMap(new HashMap<Class, Converter>());
}
workbook.getCustomConverterMap().put(converter.supportJavaTypeKey(), converter);
return this;
}
/**
* Custom write handler
*
* @param writeHandler
* @return
*/
public ExcelWriterBuilder registerWriteHandler(WriteHandler writeHandler) {
if (workbook.getCustomWriteHandlerList() == null) {
workbook.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
workbook.getCustomWriteHandlerList().add(writeHandler);
return this;
}
public ExcelWriterBuilder excelType(ExcelTypeEnum excelType) { public ExcelWriterBuilder excelType(ExcelTypeEnum excelType) {
this.excelType = excelType; workbook.setExcelType(excelType);
return this; return this;
} }
public ExcelWriterBuilder outputFile(OutputStream outputStream) { public ExcelWriterBuilder outputFile(OutputStream outputStream) {
this.outputStream = outputStream; workbook.setOutputStream(outputStream);
return this; return this;
} }
public ExcelWriterBuilder outputFile(File outputFile) throws FileNotFoundException { public ExcelWriterBuilder outputFile(File outputFile) {
return outputFile(new FileOutputStream(outputFile)); try {
return outputFile(new FileOutputStream(outputFile));
} catch (FileNotFoundException e) {
throw new ExcelGenerateException("Can not create file", e);
}
} }
public ExcelWriterBuilder outputFile(String outputPathName) throws FileNotFoundException { public ExcelWriterBuilder outputFile(String outputPathName) {
return outputFile(new File(outputPathName)); return outputFile(new File(outputPathName));
} }
public ExcelWriterBuilder outputFile(URI outputUri) throws FileNotFoundException { public ExcelWriterBuilder outputFile(URI outputUri) {
return outputFile(new File(outputUri)); return outputFile(new File(outputUri));
} }
public ExcelWriterBuilder withTemplate(InputStream templateInputStream) { public ExcelWriterBuilder withTemplate(InputStream templateInputStream) {
this.templateInputStream = templateInputStream; workbook.setTemplateInputStream(templateInputStream);
return this; return this;
} }
public ExcelWriterBuilder withTemplate(File templateFile) throws FileNotFoundException { public ExcelWriterBuilder withTemplate(File templateFile) {
return withTemplate(new FileInputStream(templateFile)); try {
return withTemplate(new FileInputStream(templateFile));
} catch (FileNotFoundException e) {
throw new ExcelGenerateException("Can not create file", e);
}
} }
public ExcelWriterBuilder withTemplate(String templatePathName) throws FileNotFoundException { public ExcelWriterBuilder withTemplate(String templatePathName) {
return withTemplate(new File(templatePathName)); return withTemplate(new File(templatePathName));
} }
public ExcelWriterBuilder withTemplate(URI templateUri) throws FileNotFoundException { public ExcelWriterBuilder withTemplate(URI templateUri) {
return withTemplate(new File(templateUri)); return withTemplate(new File(templateUri));
} }
/**
* Custom type conversions override the default.
*
* @param converter
* @return
*/
public ExcelWriterBuilder registerConverter(Converter converter) {
this.customConverterMap.put(converter.supportJavaTypeKey(), converter);
return this;
}
/**
* Default required header
*
* @return
*/
public ExcelWriterBuilder doNotNeedHead() {
this.needHead = Boolean.FALSE;
return this;
}
public ExcelWriterBuilder registerWriteHandler(WriteHandler writeHandler) {
this.customWriteHandlerList.add(writeHandler);
return this;
}
/** /**
* Write handler * Write handler
* *
@ -128,19 +184,11 @@ public class ExcelWriterBuilder {
*/ */
@Deprecated @Deprecated
public ExcelWriterBuilder registerWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) { public ExcelWriterBuilder registerWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) {
this.writeHandler = writeHandler; workbook.setWriteHandler(writeHandler);
return this; return this;
} }
public ExcelWriter build() { public ExcelWriter build() {
Workbook workbook = new Workbook();
workbook.setTemplateInputStream(templateInputStream);
workbook.setOutputStream(outputStream);
workbook.setExcelType(excelType);
workbook.setNeedHead(needHead);
workbook.setCustomConverterMap(customConverterMap);
workbook.setCustomWriteHandlerList(customWriteHandlerList);
workbook.setWriteHandler(writeHandler);
return new ExcelWriter(workbook); return new ExcelWriter(workbook);
} }
} }

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

@ -1,20 +1,11 @@
package com.alibaba.excel.write.builder; package com.alibaba.excel.write.builder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.handler.WriteHandler;
/** /**
@ -24,97 +15,124 @@ import com.alibaba.excel.write.handler.WriteHandler;
*/ */
public class ExcelWriterSheetBuilder { public class ExcelWriterSheetBuilder {
/** /**
* Excel type * Sheet
*/ */
private ExcelTypeEnum excelType; private Sheet sheet;
/**
* Final output stream
*/
private OutputStream outputStream;
/**
* Template input stream
*/
private InputStream templateInputStream;
/**
* Custom type conversions override the default
*/
private Map<Class, Converter> customConverterMap = new HashMap<Class, Converter>();
/**
* Need Head
*/
private Boolean needHead;
/**
* Custom type handler override the default
*/
private List<WriteHandler> customWriteHandlerList = new ArrayList<WriteHandler>();
public ExcelWriterSheetBuilder excelType(ExcelTypeEnum excelType) { public ExcelWriterSheetBuilder() {
this.excelType = excelType; this.sheet = new Sheet();
return this;
} }
public ExcelWriterSheetBuilder outputFile(OutputStream outputStream) { /**
this.outputStream = outputStream; * 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; return this;
} }
public ExcelWriterSheetBuilder outputFile(File outputFile) throws FileNotFoundException { /**
return outputFile(new FileOutputStream(outputFile)); * Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
} *
* @param writeRelativeHeadRowIndex
public ExcelWriterSheetBuilder outputFile(String outputPathName) throws FileNotFoundException { * @return
return outputFile(new File(outputPathName)); */
} public ExcelWriterSheetBuilder writeRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) {
sheet.setWriteRelativeHeadRowIndex(writeRelativeHeadRowIndex);
public ExcelWriterSheetBuilder outputFile(URI outputUri) throws FileNotFoundException {
return outputFile(new File(outputUri));
}
public ExcelWriterSheetBuilder withTemplate(InputStream templateInputStream) {
this.templateInputStream = templateInputStream;
return this; return this;
} }
public ExcelWriterSheetBuilder withTemplate(File templateFile) throws FileNotFoundException { /**
return withTemplate(new FileInputStream(templateFile)); * You can only choose one of the {@link ExcelWriterSheetBuilder#head(List)} and
* {@link ExcelWriterSheetBuilder#head(Class)}
*
* @param head
* @return
*/
public ExcelWriterSheetBuilder head(List<List<String>> head) {
sheet.setHead(head);
return this;
} }
public ExcelWriterSheetBuilder withTemplate(String templatePathName) throws FileNotFoundException { /**
return withTemplate(new File(templatePathName)); * You can only choose one of the {@link ExcelWriterSheetBuilder#head(List)} and
* {@link ExcelWriterSheetBuilder#head(Class)}
*
* @param clazz
* @return
*/
public ExcelWriterSheetBuilder head(Class clazz) {
sheet.setClazz(clazz);
return this;
} }
public ExcelWriterSheetBuilder withTemplate(URI templateUri) throws FileNotFoundException { /**
return withTemplate(new File(templateUri)); * Need Head
*/
public ExcelWriterSheetBuilder needHead(Boolean needHead) {
sheet.setNeedHead(needHead);
return this;
} }
/** /**
* Custom type conversions override the default. * Custom type conversions override the default.
* *
* @param converter * @param converter
* @return * @return
*/ */
public ExcelWriterSheetBuilder registerConverter(Converter converter) { public ExcelWriterSheetBuilder registerConverter(Converter converter) {
this.customConverterMap.put(converter.supportJavaTypeKey(), converter); if (sheet.getCustomConverterMap() == null) {
sheet.setCustomConverterMap(new HashMap<Class, Converter>());
}
sheet.getCustomConverterMap().put(converter.supportJavaTypeKey(), converter);
return this; return this;
} }
/** /**
* Default required header * Custom write handler
*
* @param writeHandler
* @return
*/
public ExcelWriterSheetBuilder registerWriteHandler(WriteHandler writeHandler) {
if (sheet.getCustomWriteHandlerList() == null) {
sheet.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
sheet.getCustomWriteHandlerList().add(writeHandler);
return this;
}
/**
* Starting from 0
* *
* @param sheetNo
* @return * @return
*/ */
public ExcelWriterSheetBuilder doNotNeedHead() { public ExcelWriterSheetBuilder sheetNo(Integer sheetNo) {
this.needHead = Boolean.FALSE; sheet.setSheetNo(sheetNo);
return this; return this;
} }
public ExcelWriterSheetBuilder registerWriteHandler(WriteHandler writeHandler) { /**
this.customWriteHandlerList.add(writeHandler); * sheet name
*
* @param sheetName
* @return
*/
public ExcelWriterSheetBuilder sheetName(String sheetName) {
sheet.setSheetName(sheetName);
return this; return this;
} }
public ExcelWriter build() { public Sheet build() {
return new ExcelWriter(templateInputStream, outputStream, excelType, needHead, customConverterMap, return sheet;
customWriteHandlerList);
} }
} }

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

@ -0,0 +1,127 @@
package com.alibaba.excel.write.builder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.write.handler.WriteHandler;
/**
* Build sheet
*
* @author zhuangjiaju
*/
public class ExcelWriterTableBuilder {
/**
* table
*/
private Table table;
public ExcelWriterTableBuilder() {
this.table = new Table();
}
/**
* 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;
}
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*
* @param writeRelativeHeadRowIndex
* @return
*/
public ExcelWriterTableBuilder writeRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) {
table.setWriteRelativeHeadRowIndex(writeRelativeHeadRowIndex);
return this;
}
/**
* You can only choose one of the {@link ExcelWriterTableBuilder#head(List)} and
* {@link ExcelWriterTableBuilder#head(Class)}
*
* @param head
* @return
*/
public ExcelWriterTableBuilder head(List<List<String>> head) {
table.setHead(head);
return this;
}
/**
* You can only choose one of the {@link ExcelWriterTableBuilder#head(List)} and
* {@link ExcelWriterTableBuilder#head(Class)}
*
* @param clazz
* @return
*/
public ExcelWriterTableBuilder head(Class clazz) {
table.setClazz(clazz);
return this;
}
/**
* Need Head
*/
public ExcelWriterTableBuilder needHead(Boolean needHead) {
table.setNeedHead(needHead);
return this;
}
/**
* Custom type conversions override the default.
*
* @param converter
* @return
*/
public ExcelWriterTableBuilder registerConverter(Converter converter) {
if (table.getCustomConverterMap() == null) {
table.setCustomConverterMap(new HashMap<Class, Converter>());
}
table.getCustomConverterMap().put(converter.supportJavaTypeKey(), converter);
return this;
}
/**
* Custom write handler
*
* @param writeHandler
* @return
*/
public ExcelWriterTableBuilder registerWriteHandler(WriteHandler writeHandler) {
if (table.getCustomWriteHandlerList() == null) {
table.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
table.getCustomWriteHandlerList().add(writeHandler);
return this;
}
/**
* Starting from 0
*
* @param tableNo
* @return
*/
public ExcelWriterTableBuilder tableNo(Integer tableNo) {
table.setTableNo(tableNo);
return this;
}
public Table build() {
return table;
}
}

3
src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerBuilder.java

@ -8,7 +8,6 @@ import org.apache.poi.ss.usermodel.IndexedColors;
import com.alibaba.excel.metadata.CellStyle; import com.alibaba.excel.metadata.CellStyle;
import com.alibaba.excel.metadata.Font; import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.write.style.RowCellStyleStrategy; import com.alibaba.excel.write.style.RowCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
/** /**
* Build default handler * Build default handler
@ -28,10 +27,10 @@ public class DefaultWriteHandlerBuilder {
Font font = new Font(); Font font = new Font();
headCellStyle.setFont(font); headCellStyle.setFont(font);
font.setFontName("宋体"); font.setFontName("宋体");
font.setFontHeightInPoints((short)14);
font.setBold(true); font.setBold(true);
headCellStyle.setIndexedColors(IndexedColors.GREY_25_PERCENT); headCellStyle.setIndexedColors(IndexedColors.GREY_25_PERCENT);
handlerList.add(new RowCellStyleStrategy(headCellStyle, new ArrayList<CellStyle>())); handlerList.add(new RowCellStyleStrategy(headCellStyle, new ArrayList<CellStyle>()));
handlerList.add(new SimpleColumnWidthStyleStrategy(20));
return handlerList; return handlerList;
} }

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

@ -8,11 +8,11 @@ import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.holder.SheetHolder; import com.alibaba.excel.metadata.holder.SheetHolder;
import com.alibaba.excel.metadata.holder.TableHolder; import com.alibaba.excel.metadata.holder.TableHolder;
import com.alibaba.excel.metadata.holder.WorkbookHolder;
import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.WorkbookWriteHandler; import com.alibaba.excel.write.handler.WorkbookWriteHandler;
public abstract class AbstractCellStyleStrategy public abstract class AbstractCellStyleStrategy implements CellWriteHandler, WorkbookWriteHandler, NotRepeatExecutor {
implements CellWriteHandler, WorkbookWriteHandler, NotRepeatExecutor {
@Override @Override
public String uniqueValue() { public String uniqueValue() {
return "CellStyleStrategy"; return "CellStyleStrategy";
@ -22,8 +22,8 @@ public abstract class AbstractCellStyleStrategy
public void beforeWorkbookCreate() {} public void beforeWorkbookCreate() {}
@Override @Override
public void afterWorkbookCreate(Workbook workbook) { public void afterWorkbookCreate(WorkbookHolder workbookHolder) {
initCellStyle(workbook); initCellStyle(workbookHolder.getWorkbook());
} }
@Override @Override

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

@ -17,10 +17,13 @@ public abstract class AbstractHeadColumnWidthStyleStrategy extends AbstractColum
} }
/** /**
* Returns the column width corresponding to each column head * Returns the column width corresponding to each column head.
*
* *
* @param head * @param head
* @return * @return the width in units of 1/256th of a character width . Using the Calibri font as an example, the maximum
* digit width of 11 point font size is 7 pixels (at 96 dpi). If you set a column width to be eight
* characters wide, e.g. you need return 8*256
*/ */
protected abstract int columnWidth(Head head); protected abstract int columnWidth(Head head);
} }

7
src/main/java/com/alibaba/excel/write/style/column/SimpleColumnWidthStyleStrategy.java

@ -13,6 +13,13 @@ import com.alibaba.excel.metadata.Head;
public class SimpleColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy { public class SimpleColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
private int columnWidth; private int columnWidth;
/**
* Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi). * If
* you set a column width to be eight characters wide, e.g. <code>SimpleColumnWidthStyleStrategy( 8*256)</code>,
*
* @param columnWidth
* the width in units of 1/256th of a character width
*/
public SimpleColumnWidthStyleStrategy(int columnWidth) { public SimpleColumnWidthStyleStrategy(int columnWidth) {
this.columnWidth = columnWidth; this.columnWidth = columnWidth;
} }

11
src/test/java/com/alibaba/easyexcel/test/util/FileUtil.java

@ -1,5 +1,6 @@
package com.alibaba.easyexcel.test.util; package com.alibaba.easyexcel.test.util;
import java.io.File;
import java.io.InputStream; import java.io.InputStream;
public class FileUtil { public class FileUtil {
@ -7,8 +8,16 @@ public class FileUtil {
public static InputStream getResourcesFileInputStream(String fileName) { public static InputStream getResourcesFileInputStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName); return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
} }
public static String getPath() { public static String getPath() {
return FileUtil.class.getResource("/").getPath(); return FileUtil.class.getResource("/").getPath();
} }
public static File createNewFile(String pathName) {
File file = new File(getPath() + pathName);
if (file.exists()) {
file.delete();
}
return file;
}
} }

19
src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData.java

@ -0,0 +1,19 @@
package com.alibaba.easyexcel.test.wirte.simple;
import com.alibaba.excel.annotation.ExcelProperty;
/**
* @author zhuangjiaju
*/
public class SimpleData {
@ExcelProperty("字符串")
private String string;
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
}

17
src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData03Test.java

@ -0,0 +1,17 @@
package com.alibaba.easyexcel.test.wirte.simple;
import org.junit.Test;
/**
* Simple data test
*
* @author zhuangjiaju
*/
public class SimpleData03Test {
@Test
public void simple07() {
}
}

38
src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData07Test.java

@ -0,0 +1,38 @@
package com.alibaba.easyexcel.test.wirte.simple;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.alibaba.easyexcel.test.util.FileUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
/**
* Simple data test
*
* @author zhuangjiaju
*/
public class SimpleData07Test {
@Test
public void simple() {
ExcelWriter writer = EasyExcelFactory.writerBuilder().outputFile(FileUtil.createNewFile("simple07.xlsx"))
.head(SimpleData.class).build();
Sheet sheet = EasyExcelFactory.writerSheetBuilder().sheetNo(0).sheetName("simple").build();
writer.write(createData(10), sheet);
writer.finish();
}
private List<SimpleData> createData(int count) {
List<SimpleData> list = new ArrayList<SimpleData>();
for (int i = 0; i < count; i++) {
SimpleData simpleData = new SimpleData();
simpleData.setString("字符体" + i);
list.add(simpleData);
}
return list;
}
}

5
src/test/resources/logback.xml

@ -6,11 +6,8 @@
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${LOG_PATTERN}</pattern> <pattern>${LOG_PATTERN}</pattern>
</encoder> </encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
</filter>
</appender> </appender>
<root level="INFO"> <root level="DEBUG">
<appender-ref ref="STDOUT"/> <appender-ref ref="STDOUT"/>
</root> </root>
</configuration> </configuration>

Loading…
Cancel
Save