From be4b3795a1538ba2197a032a56db523cbf0e6a4e Mon Sep 17 00:00:00 2001 From: zhuangjiaju Date: Fri, 12 Jul 2019 17:23:22 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=B8=80=E4=BA=9B=E6=B5=81?= =?UTF-8?q?=E7=A8=8B=E6=80=A7=E5=BC=82=E5=B8=B8=20=E5=B9=B6=20=E5=B0=86?= =?UTF-8?q?=E5=86=99=20=E6=B5=8B=E8=AF=95=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 6 + .../com/alibaba/excel/EasyExcelFactory.java | 111 ++++--- .../excel/context/WriteContextImpl.java | 301 ++++++------------ .../converters/DefaultConverterBuilder.java | 12 +- .../excel/metadata/BasicParameter.java | 105 ++++++ .../excel/metadata/ExcelHeadProperty.java | 7 +- .../com/alibaba/excel/metadata/Sheet.java | 130 ++------ .../com/alibaba/excel/metadata/Table.java | 86 +---- .../com/alibaba/excel/metadata/Workbook.java | 103 +----- .../holder/AbstractConfigurationSelector.java | 224 +++++++++++++ .../excel/metadata/holder/SheetHolder.java | 183 +++++------ .../excel/metadata/holder/TableHolder.java | 166 ++++------ .../excel/metadata/holder/WorkbookHolder.java | 135 ++++---- .../com/alibaba/excel/util/StyleUtil.java | 8 +- .../com/alibaba/excel/util/WorkBookUtil.java | 4 + .../alibaba/excel/write/ExcelBuilderImpl.java | 105 +++++- .../write/builder/ExcelWriterBuilder.java | 172 ++++++---- .../builder/ExcelWriterSheetBuilder.java | 152 +++++---- .../builder/ExcelWriterTableBuilder.java | 127 ++++++++ .../handler/DefaultWriteHandlerBuilder.java | 3 +- .../style/AbstractCellStyleStrategy.java | 8 +- .../AbstractHeadColumnWidthStyleStrategy.java | 7 +- .../SimpleColumnWidthStyleStrategy.java | 7 + .../alibaba/easyexcel/test/util/FileUtil.java | 11 +- .../test/wirte/simple/SimpleData.java | 19 ++ .../test/wirte/simple/SimpleData03Test.java | 17 + .../test/wirte/simple/SimpleData07Test.java | 38 +++ src/test/resources/logback.xml | 5 +- 28 files changed, 1282 insertions(+), 970 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/metadata/BasicParameter.java create mode 100644 src/main/java/com/alibaba/excel/metadata/holder/AbstractConfigurationSelector.java create mode 100644 src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData03Test.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData07Test.java diff --git a/pom.xml b/pom.xml index 6f4cde9..f85fb7a 100644 --- a/pom.xml +++ b/pom.xml @@ -82,6 +82,12 @@ 1.2.3 test + + com.alibaba + fastjson + 1.2.58 + test + junit junit diff --git a/src/main/java/com/alibaba/excel/EasyExcelFactory.java b/src/main/java/com/alibaba/excel/EasyExcelFactory.java index 7df3750..aa6cfa1 100644 --- a/src/main/java/com/alibaba/excel/EasyExcelFactory.java +++ b/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.support.ExcelTypeEnum; 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 @@ -22,8 +24,10 @@ public class EasyExcelFactory { /** * Quickly read small files,no more than 10,000 lines. * - * @param in the POI filesystem that contains the Workbook stream. - * @param sheet read sheet. + * @param in + * the POI filesystem that contains the Workbook stream. + * @param sheet + * read sheet. * @return analysis result. */ public static List read(InputStream in, Sheet sheet) { @@ -35,8 +39,7 @@ public class EasyExcelFactory { } @Override - public void doAfterAllAnalysed(AnalysisContext context) { - } + public void doAfterAllAnalysed(AnalysisContext context) {} }, false).read(sheet); return rows; } @@ -44,9 +47,12 @@ public class EasyExcelFactory { /** * Parsing large file * - * @param in the POI filesystem that contains the Workbook stream. - * @param sheet read sheet. - * @param listener Callback method after each row is parsed. + * @param in + * the POI filesystem that contains the Workbook stream. + * @param sheet + * read sheet. + * @param listener + * Callback method after each row is parsed. */ public static void readBySax(InputStream in, Sheet sheet, AnalysisEventListener listener) { new ExcelReader(in, null, listener).read(sheet); @@ -55,8 +61,10 @@ public class EasyExcelFactory { /** * Get ExcelReader. * - * @param in the POI filesystem that contains the Workbook stream. - * @param listener Callback method after each row is parsed. + * @param in + * the POI filesystem that contains the Workbook stream. + * @param listener + * Callback method after each row is parsed. * @return ExcelReader. */ public static ExcelReader getReader(InputStream in, AnalysisEventListener listener) { @@ -66,79 +74,86 @@ public class EasyExcelFactory { /** * 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. + * @deprecated please use {@link EasyExcelFactory#writerBuilder()} */ + @Deprecated public static ExcelWriter getWriter(OutputStream outputStream) { - return writerBuilder().outputFile(outputStream).build(); + return writerBuilder().outputFile(outputStream).autoCloseStream(Boolean.FALSE).build(); } /** * Get ExcelWriter * - * @param outputStream the java OutputStream you wish to write the value to. - * @param typeEnum 03 or 07 - * @param needHead Do you need to write the header to the file? - * @return new ExcelWriter + * @param outputStream + * the java OutputStream you wish to write the value to. + * @param typeEnum + * 03 or 07 + * @param needHead + * Do you need to write the header to the file? + * @return new ExcelWriter + * @deprecated please use {@link EasyExcelFactory#writerBuilder()} */ + @Deprecated public static ExcelWriter getWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { - if (needHead) { - return writerBuilder().outputFile(outputStream).excelType(typeEnum).build(); - } else { - return writerBuilder().outputFile(outputStream).excelType(typeEnum).doNotNeedHead().build(); - } + return writerBuilder().outputFile(outputStream).excelType(typeEnum).needHead(needHead) + .autoCloseStream(Boolean.FALSE).build(); } /** * Get ExcelWriter with a template file * - * @param temp Append value after a POI file , Can be null(the template POI filesystem that contains the - * Workbook stream) - * @param outputStream the java OutputStream you wish to write the value to - * @param typeEnum 03 or 07 - * @return new ExcelWriter + * @param temp + * Append value after a POI file , Can be null(the template POI filesystem that contains the Workbook + * stream) + * @param outputStream + * the java OutputStream you wish to write the value to + * @param typeEnum + * 03 or 07 + * @return new ExcelWriter + * @deprecated please use {@link EasyExcelFactory#writerBuilder()} */ + @Deprecated public static ExcelWriter getWriterWithTemp(InputStream temp, OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { - if (needHead) { - return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).build(); - } else { - return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).doNotNeedHead() - .build(); - } + return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).needHead(needHead) + .autoCloseStream(Boolean.FALSE).build(); } /** * Get ExcelWriter with a template file * - * @param temp Append value after a POI file , Can be null(the template POI filesystem that contains the - * Workbook stream) - * @param outputStream the java OutputStream you wish to write the value to - * @param typeEnum 03 or 07 + * @param temp + * Append value after a POI file , Can be null(the template POI filesystem that contains the Workbook + * stream) + * @param outputStream + * the java OutputStream you wish to write the value to + * @param typeEnum + * 03 or 07 * @param needHead - * @param handler User-defined callback - * @return new ExcelWriter + * @param handler + * User-defined callback + * @return new ExcelWriter + * @deprecated please use {@link EasyExcelFactory#writerBuilder()} */ + @Deprecated public static ExcelWriter getWriterWithTempAndHandler(InputStream temp, OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead, WriteHandler handler) { - if (needHead) { - return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum) - .registerWriteHandler(handler).build(); - } else { - return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).doNotNeedHead() - .registerWriteHandler(handler).build(); - } + return writerBuilder().withTemplate(temp).outputFile(outputStream).excelType(typeEnum).needHead(needHead) + .registerWriteHandler(handler).autoCloseStream(Boolean.FALSE).build(); } public static ExcelWriterBuilder writerBuilder() { return new ExcelWriterBuilder(); } - public static ExcelWriterBuilder writerSheetBuilder() { - return new ExcelWriterBuilder(); + public static ExcelWriterSheetBuilder writerSheetBuilder() { + return new ExcelWriterSheetBuilder(); } - public static ExcelWriterBuilder writerTableBuilder() { - return new ExcelWriterBuilder(); + public static ExcelWriterTableBuilder writerTableBuilder() { + return new ExcelWriterTableBuilder(); } } diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java index 252612d..44757ee 100644 --- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java @@ -1,13 +1,7 @@ package com.alibaba.excel.context; import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; @@ -16,27 +10,20 @@ import org.apache.poi.ss.util.CellRangeAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.alibaba.excel.converters.Converter; -import com.alibaba.excel.converters.DefaultConverterBuilder; -import com.alibaba.excel.event.NotRepeatExecutor; -import com.alibaba.excel.event.Order; import com.alibaba.excel.exception.ExcelGenerateException; -import com.alibaba.excel.metadata.CellStyle; import com.alibaba.excel.metadata.ExcelHeadProperty; import com.alibaba.excel.metadata.Head; 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.SheetHolder; import com.alibaba.excel.metadata.holder.TableHolder; import com.alibaba.excel.metadata.holder.WorkbookHolder; 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.WorkbookWriteHandler; 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. @@ -109,72 +96,13 @@ public class WriteContextImpl implements WriteContext { } private void initCurrentWorkbookHolder(com.alibaba.excel.metadata.Workbook workbook) { - currentWorkbookHolder = new WorkbookHolder(); - 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 handlerList = new ArrayList(); - if (workbook.getCustomWriteHandlerList() != null && !workbook.getCustomWriteHandlerList().isEmpty()) { - handlerList.addAll(workbook.getCustomWriteHandlerList()); - } - handlerList.addAll(DefaultWriteHandlerBuilder.loadDefaultHandler()); - currentWorkbookHolder.setWriteHandlerList(sortAndClearUpHandler(handlerList)); - Map converterMap = DefaultConverterBuilder.loadDefaultWriteConverter(); - if (workbook.getCustomConverterMap() != null && !workbook.getCustomConverterMap().isEmpty()) { - converterMap.putAll(workbook.getCustomConverterMap()); - } - currentWorkbookHolder.setConverterMap(converterMap); - currentWorkbookHolder.setHasBeenInitializedSheet(new HashMap()); + currentWorkbookHolder = new WorkbookHolder(workbook); currentConfigurationSelector = currentWorkbookHolder; if (LOGGER.isDebugEnabled()) { LOGGER.debug("CurrentConfigurationSelector is currentWorkbookHolder"); } } - private List sortAndClearUpHandler(List handlerList) { - // sort - Map> orderExcelWriteHandlerMap = new TreeMap>(); - for (WriteHandler handler : handlerList) { - int order = Integer.MIN_VALUE; - if (handler instanceof Order) { - order = ((Order)handler).order(); - } - if (orderExcelWriteHandlerMap.containsKey(order)) { - orderExcelWriteHandlerMap.get(order).add(handler); - } else { - List tempHandlerList = new ArrayList(); - tempHandlerList.add(handler); - orderExcelWriteHandlerMap.put(order, tempHandlerList); - } - } - // clean up - Set alreadyExistedHandlerSet = new HashSet(); - List result = new ArrayList(); - for (Map.Entry> entry : orderExcelWriteHandlerMap.entrySet()) { - for (WriteHandler handler : entry.getValue()) { - if (handler instanceof NotRepeatExecutor) { - String uniqueValue = ((NotRepeatExecutor)handler).uniqueValue(); - if (alreadyExistedHandlerSet.contains(uniqueValue)) { - continue; - } - alreadyExistedHandlerSet.add(uniqueValue); - } - result.add(handler); - } - } - return result; - } - /** * @param sheet */ @@ -191,6 +119,7 @@ public class WriteContextImpl implements WriteContext { LOGGER.debug("Sheet:{} is already existed", sheet.getSheetNo()); } currentSheetHolder = currentWorkbookHolder.getHasBeenInitializedSheet().get(sheet.getSheetNo()); + currentSheetHolder.setNewInitialization(Boolean.FALSE); currentTableHolder = null; currentConfigurationSelector = currentSheetHolder; if (LOGGER.isDebugEnabled()) { @@ -198,7 +127,6 @@ public class WriteContextImpl implements WriteContext { } return; } - initCurrentSheetHolder(sheet); beforeSheetCreate(); // Initialization current sheet @@ -228,36 +156,14 @@ public class WriteContextImpl implements WriteContext { ((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) { - currentSheetHolder = new SheetHolder(); - 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 handlerList = new ArrayList(); - if (sheet.getCustomWriteHandlerList() != null && !sheet.getCustomWriteHandlerList().isEmpty()) { - handlerList.addAll(sheet.getCustomWriteHandlerList()); - } - handlerList.addAll(currentConfigurationSelector.writeHandlerList()); - currentSheetHolder.setWriteHandlerList(sortAndClearUpHandler(handlerList)); - Map converterMap = new HashMap(currentConfigurationSelector.converterMap()); - if (sheet.getCustomConverterMap() != null && !sheet.getCustomConverterMap().isEmpty()) { - converterMap.putAll(sheet.getCustomConverterMap()); - } - currentSheetHolder.setConverterMap(converterMap); - currentSheetHolder.setHasBeenInitializedTable(new HashMap()); + currentSheetHolder = new SheetHolder(sheet, currentWorkbookHolder); currentWorkbookHolder.getHasBeenInitializedSheet().put(sheet.getSheetNo(), currentSheetHolder); currentTableHolder = null; 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 columnWidthMap = sheet.getColumnWidthMap(); - if (sheet.getCustomWriteHandlerList() == null) { - sheet.setCustomWriteHandlerList(new ArrayList()); - } - 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()); - } - 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) { Sheet currentSheet; try { @@ -313,7 +184,8 @@ public class WriteContextImpl implements WriteContext { } currentSheetHolder.setSheet(currentSheet); // Initialization head - currentSheetHolder.setExcelHeadProperty(new ExcelHeadProperty(sheet.getClazz(), sheet.getHead())); + currentSheetHolder + .setExcelHeadProperty(new ExcelHeadProperty(currentSheetHolder.getClazz(), currentSheetHolder.getHead())); // Initialization head initHead(currentSheetHolder.getExcelHeadProperty()); } @@ -322,28 +194,90 @@ public class WriteContextImpl implements WriteContext { if (!currentConfigurationSelector.needHead() || !currentSheetHolder.getExcelHeadProperty().hasHead()) { return; } - int startRow = currentSheetHolder.getSheet().getLastRowNum(); - startRow += currentConfigurationSelector.writeRelativeHeadRowIndex(); + int lastRowNum = currentSheetHolder.getSheet().getLastRowNum(); + int rowIndex = lastRowNum + currentConfigurationSelector.writeRelativeHeadRowIndex(); // Combined head - addMergedRegionToCurrentSheet(excelHeadProperty, startRow); - for (int i = startRow; i < excelHeadProperty.getHeadRowNumber() + startRow; i++) { + addMergedRegionToCurrentSheet(excelHeadProperty, rowIndex); + for (int relativeRowIndex = 0, i = rowIndex; i < excelHeadProperty.getHeadRowNumber() + rowIndex; + i++, relativeRowIndex++) { + beforeRowCreate(rowIndex, relativeRowIndex); 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 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 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()) { - currentSheetHolder.getSheet().addMergedRegion(new CellRangeAddress(cellRangeModel.getFirstRow() + startRow, - cellRangeModel.getLastRow() + startRow, cellRangeModel.getFirstCol(), cellRangeModel.getLastCol())); + currentSheetHolder.getSheet().addMergedRegion(new CellRangeAddress(cellRangeModel.getFirstRow() + rowIndex, + cellRangeModel.getLastRow() + rowIndex, cellRangeModel.getFirstCol(), cellRangeModel.getLastCol())); } } - private void addOneRowOfHeadDataToExcel(Row row, int rowIndex, List headList) { + private void addOneRowOfHeadDataToExcel(Row row, List headList, int relativeRowIndex) { for (int i = 0; i < headList.size(); i++) { Head head = headList.get(i); - // TODO 创建cell + beforeCellCreate(row, headList.get(i), relativeRowIndex); 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 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 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()); } currentTableHolder = currentSheetHolder.getHasBeenInitializedTable().get(table.getTableNo()); + currentTableHolder.setNewInitialization(Boolean.FALSE); currentConfigurationSelector = currentTableHolder; if (LOGGER.isDebugEnabled()) { LOGGER.debug("CurrentConfigurationSelector is currentTableHolder"); @@ -368,65 +303,20 @@ public class WriteContextImpl implements WriteContext { } initCurrentTableHolder(table); // Initialization head - currentTableHolder.setExcelHeadProperty(new ExcelHeadProperty(table.getClazz(), table.getHead())); - + currentTableHolder + .setExcelHeadProperty(new ExcelHeadProperty(currentTableHolder.getClazz(), currentTableHolder.getHead())); initHead(currentTableHolder.getExcelHeadProperty()); } private void initCurrentTableHolder(com.alibaba.excel.metadata.Table table) { - currentTableHolder = new TableHolder(); - currentTableHolder.setTableParam(table); - 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 handlerList = new ArrayList(); - if (table.getCustomWriteHandlerList() != null && !table.getCustomWriteHandlerList().isEmpty()) { - handlerList.addAll(table.getCustomWriteHandlerList()); - } - handlerList.addAll(currentConfigurationSelector.writeHandlerList()); - currentTableHolder.setWriteHandlerList(sortAndClearUpHandler(handlerList)); - Map converterMap = new HashMap(currentConfigurationSelector.converterMap()); - if (table.getCustomConverterMap() != null && !table.getCustomConverterMap().isEmpty()) { - converterMap.putAll(table.getCustomConverterMap()); - } - currentTableHolder.setConverterMap(converterMap); + currentTableHolder = new TableHolder(table, currentSheetHolder); + currentSheetHolder.getHasBeenInitializedTable().put(table.getTableNo(), currentTableHolder); currentConfigurationSelector = currentTableHolder; if (LOGGER.isDebugEnabled()) { 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()); - } - 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 public ConfigurationSelector currentConfigurationSelector() { return currentConfigurationSelector; @@ -452,14 +342,19 @@ public class WriteContextImpl implements WriteContext { try { currentWorkbookHolder.getWorkbook().write(currentWorkbookHolder.getOutputStream()); currentWorkbookHolder.getWorkbook().close(); - if (currentWorkbookHolder.getOutputStream() != null) { - currentWorkbookHolder.getOutputStream().close(); - } - if (currentWorkbookHolder.getTemplateInputStream() != null) { - currentWorkbookHolder.getTemplateInputStream().close(); + if (currentWorkbookHolder.getAutoCloseStream()) { + if (currentWorkbookHolder.getOutputStream() != null) { + currentWorkbookHolder.getOutputStream().close(); + } + if (currentWorkbookHolder.getTemplateInputStream() != null) { + currentWorkbookHolder.getTemplateInputStream().close(); + } } } catch (IOException e) { throw new ExcelGenerateException("Can not close IO", e); } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Finished write."); + } } } diff --git a/src/main/java/com/alibaba/excel/converters/DefaultConverterBuilder.java b/src/main/java/com/alibaba/excel/converters/DefaultConverterBuilder.java index b74752c..37e7240 100644 --- a/src/main/java/com/alibaba/excel/converters/DefaultConverterBuilder.java +++ b/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.date.DateStringConverter; +import com.alibaba.excel.converters.string.StringStringConverter; /** * Build default handler @@ -19,13 +20,16 @@ public class DefaultConverterBuilder { */ public static Map loadDefaultWriteConverter() { Map converterMap = new HashMap(); - DateStringConverter dateStringConverter = new DateStringConverter(); - converterMap.put(dateStringConverter.supportJavaTypeKey(), dateStringConverter); - BigDecimalNumberConverter bigDecimalNumberConverter = new BigDecimalNumberConverter(); - converterMap.put(bigDecimalNumberConverter.supportJavaTypeKey(), bigDecimalNumberConverter); + putConverter(converterMap, new DateStringConverter()); + putConverter(converterMap, new BigDecimalNumberConverter()); + putConverter(converterMap, new StringStringConverter()); return converterMap; } + private static void putConverter(Map converterMap, Converter converter) { + converterMap.put(converter.supportJavaTypeKey(), converter); + } + /** * Load default read converter * diff --git a/src/main/java/com/alibaba/excel/metadata/BasicParameter.java b/src/main/java/com/alibaba/excel/metadata/BasicParameter.java new file mode 100644 index 0000000..acbaef9 --- /dev/null +++ b/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. + * + *
  • 0 - This Sheet has no head ,since the first row are the data + *
  • 1 - This Sheet has one row head , this is the default + *
  • 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> 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 customConverterMap = new HashMap(); + /** + * Custom type handler override the default + */ + private List customWriteHandlerList = new ArrayList(); + + 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> getHead() { + return head; + } + + public void setHead(List> 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 getCustomConverterMap() { + return customConverterMap; + } + + public void setCustomConverterMap(Map customConverterMap) { + this.customConverterMap = customConverterMap; + } + + public List getCustomWriteHandlerList() { + return customWriteHandlerList; + } + + public void setCustomWriteHandlerList(List customWriteHandlerList) { + this.customWriteHandlerList = customWriteHandlerList; + } +} diff --git a/src/main/java/com/alibaba/excel/metadata/ExcelHeadProperty.java b/src/main/java/com/alibaba/excel/metadata/ExcelHeadProperty.java index 2e8fc19..9618189 100644 --- a/src/main/java/com/alibaba/excel/metadata/ExcelHeadProperty.java +++ b/src/main/java/com/alibaba/excel/metadata/ExcelHeadProperty.java @@ -62,12 +62,11 @@ public class ExcelHeadProperty { // convert headClazz to head initColumnProperties(); } - initHeadRowNumber(); } - public static ExcelHeadProperty buildExcelHeadProperty(ExcelHeadProperty excelHeadProperty, - Class clazz, List headOneRow) { + public static ExcelHeadProperty buildExcelHeadProperty(ExcelHeadProperty excelHeadProperty, Class clazz, + List headOneRow) { if (excelHeadProperty == null) { return new ExcelHeadProperty(clazz, new ArrayList>()); } @@ -206,7 +205,7 @@ public class ExcelHeadProperty { } public boolean hasHead() { - return headKind == HeadKindEnum.NONE; + return headKind != HeadKindEnum.NONE; } public int getHeadRowNumber() { diff --git a/src/main/java/com/alibaba/excel/metadata/Sheet.java b/src/main/java/com/alibaba/excel/metadata/Sheet.java index 0df6aec..149ae54 100644 --- a/src/main/java/com/alibaba/excel/metadata/Sheet.java +++ b/src/main/java/com/alibaba/excel/metadata/Sheet.java @@ -4,9 +4,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import com.alibaba.excel.converters.Converter; 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.column.SimpleColumnWidthStyleStrategy; @@ -15,7 +13,7 @@ import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy; * * @author jipengfei */ -public class Sheet { +public class Sheet extends BasicParameter { /** * Starting from 0 */ @@ -24,39 +22,6 @@ public class Sheet { * sheet name */ private String sheetName; - /** - * Count the number of added heads when read sheet. - * - *
  • 0 - This Sheet has no head ,since the first row are the data - *
  • 1 - This Sheet has one row head , this is the default - *
  • 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> 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 customConverterMap; - /** - * Need Head - */ - private Boolean needHead; - /** - * Custom type handler override the default - */ - private List customWriteHandlerList; - /** * column with * @@ -72,7 +37,21 @@ public class Sheet { @Deprecated 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 @@ -83,8 +62,9 @@ public class Sheet { */ @Deprecated public Sheet(int sheetNo, int readHeadRowNumber) { + super(); this.sheetNo = sheetNo - 1; - this.readHeadRowNumber = readHeadRowNumber; + setReadHeadRowNumber(readHeadRowNumber); } /** @@ -95,6 +75,7 @@ public class Sheet { */ @Deprecated public Sheet(int sheetNo) { + super(); this.sheetNo = sheetNo - 1; } @@ -108,9 +89,10 @@ public class Sheet { */ @Deprecated public Sheet(int sheetNo, int readHeadRowNumber, Class clazz) { + super(); this.sheetNo = sheetNo - 1; - this.readHeadRowNumber = readHeadRowNumber; - this.clazz = clazz; + setReadHeadRowNumber(readHeadRowNumber); + setClazz(clazz); } /** @@ -123,11 +105,13 @@ public class Sheet { */ @Deprecated public Sheet(int sheetNo, int readHeadRowNumber, Class clazz, String sheetName, List> head) { + super(); this.sheetNo = sheetNo - 1; - this.clazz = clazz; - this.readHeadRowNumber = readHeadRowNumber; this.sheetName = sheetName; - this.head = head; + + setReadHeadRowNumber(readHeadRowNumber); + setClazz(clazz); + setHead(head); } public Integer getSheetNo() { @@ -146,62 +130,6 @@ public class Sheet { 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> getHead() { - return head; - } - - public void setHead(List> head) { - this.head = head; - } - - public Class getClazz() { - return clazz; - } - - public void setClazz(Class clazz) { - this.clazz = clazz; - } - - public Map getCustomConverterMap() { - return customConverterMap; - } - - public void setCustomConverterMap(Map customConverterMap) { - this.customConverterMap = customConverterMap; - } - - public Boolean getNeedHead() { - return needHead; - } - - public void setNeedHead(Boolean needHead) { - this.needHead = needHead; - } - - public List getCustomWriteHandlerList() { - return customWriteHandlerList; - } - - public void setCustomWriteHandlerList(List customWriteHandlerList) { - this.customWriteHandlerList = customWriteHandlerList; - } - public Map getColumnWidthMap() { return columnWidthMap; } @@ -225,7 +153,7 @@ public class Sheet { */ @Deprecated public void setStartRow(int writeRelativeHeadRowIndex) { - this.writeRelativeHeadRowIndex = writeRelativeHeadRowIndex; + setWriteRelativeHeadRowIndex(writeRelativeHeadRowIndex); } /** @@ -235,7 +163,7 @@ public class Sheet { */ @Deprecated public void setHeadLineMun(int readHeadRowNumber) { - this.readHeadRowNumber = readHeadRowNumber; + setReadHeadRowNumber(readHeadRowNumber); } @Override diff --git a/src/main/java/com/alibaba/excel/metadata/Table.java b/src/main/java/com/alibaba/excel/metadata/Table.java index f0b4a3c..0915b40 100644 --- a/src/main/java/com/alibaba/excel/metadata/Table.java +++ b/src/main/java/com/alibaba/excel/metadata/Table.java @@ -1,46 +1,17 @@ package com.alibaba.excel.metadata; -import java.util.List; -import java.util.Map; - -import com.alibaba.excel.converters.Converter; -import com.alibaba.excel.write.handler.WriteHandler; +import com.alibaba.excel.write.style.RowCellStyleStrategy; /** * table * * @author jipengfei */ -public class Table { +public class Table extends BasicParameter { /** * Starting from 0 */ 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> 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 customConverterMap; - /** - * Need Head - */ - private Boolean needHead; - /** - * Custom type handler override the default - */ - private List customWriteHandlerList; - /** * * @deprecated please use{@link RowCellStyleStrategy} @@ -48,7 +19,12 @@ public class Table { @Deprecated private TableStyle tableStyle; + public Table() { + super(); + } + public Table(Integer tableNo) { + super(); this.tableNo = tableNo; } @@ -60,54 +36,6 @@ public class Table { this.tableNo = tableNo; } - public Integer getWriteRelativeHeadRowIndex() { - return writeRelativeHeadRowIndex; - } - - public void setWriteRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) { - this.writeRelativeHeadRowIndex = writeRelativeHeadRowIndex; - } - - public List> getHead() { - return head; - } - - public void setHead(List> head) { - this.head = head; - } - - public Class getClazz() { - return clazz; - } - - public void setClazz(Class clazz) { - this.clazz = clazz; - } - - public Map getCustomConverterMap() { - return customConverterMap; - } - - public void setCustomConverterMap(Map customConverterMap) { - this.customConverterMap = customConverterMap; - } - - public Boolean getNeedHead() { - return needHead; - } - - public void setNeedHead(Boolean needHead) { - this.needHead = needHead; - } - - public List getCustomWriteHandlerList() { - return customWriteHandlerList; - } - - public void setCustomWriteHandlerList(List customWriteHandlerList) { - this.customWriteHandlerList = customWriteHandlerList; - } - public TableStyle getTableStyle() { return tableStyle; } diff --git a/src/main/java/com/alibaba/excel/metadata/Workbook.java b/src/main/java/com/alibaba/excel/metadata/Workbook.java index 6f53efa..155f6ae 100644 --- a/src/main/java/com/alibaba/excel/metadata/Workbook.java +++ b/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.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.write.handler.WriteHandler; @@ -16,7 +11,7 @@ import com.alibaba.excel.write.handler.WriteHandler; * * @author zhuangjiaju **/ -public class Workbook { +public class Workbook extends BasicParameter { /** * Excel type */ @@ -30,37 +25,9 @@ public class Workbook { */ private InputStream templateInputStream; /** - * Count the number of added heads when read sheet. - * - *
  • 0 - This Sheet has no head ,since the first row are the data - *
  • 1 - This Sheet has one row head , this is the default - *
  • 2 - This Sheet has two row head ,since the third row is the data + * Default true */ - 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 Workbook#head} and {@link Workbook#clazz} - */ - private List> 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 customConverterMap = new HashMap(); - /** - * Custom type handler override the default - */ - private List customWriteHandlerList = new ArrayList(); + private Boolean autoCloseStream; /** * Write handler * @@ -93,62 +60,6 @@ public class Workbook { 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> getHead() { - return head; - } - - public void setHead(List> 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 getCustomConverterMap() { - return customConverterMap; - } - - public void setCustomConverterMap(Map customConverterMap) { - this.customConverterMap = customConverterMap; - } - - public List getCustomWriteHandlerList() { - return customWriteHandlerList; - } - - public void setCustomWriteHandlerList(List customWriteHandlerList) { - this.customWriteHandlerList = customWriteHandlerList; - } - public com.alibaba.excel.event.WriteHandler getWriteHandler() { return writeHandler; } @@ -156,4 +67,12 @@ public class Workbook { public void setWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) { this.writeHandler = writeHandler; } + + public Boolean getAutoCloseStream() { + return autoCloseStream; + } + + public void setAutoCloseStream(Boolean autoCloseStream) { + this.autoCloseStream = autoCloseStream; + } } diff --git a/src/main/java/com/alibaba/excel/metadata/holder/AbstractConfigurationSelector.java b/src/main/java/com/alibaba/excel/metadata/holder/AbstractConfigurationSelector.java new file mode 100644 index 0000000..22abb7c --- /dev/null +++ b/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, List> writeHandlerMap; + /** + * Converter for workbook + */ + private Map 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> 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, List> getWriteHandlerMap() { + return writeHandlerMap; + } + + public void setWriteHandlerMap(Map, List> writeHandlerMap) { + this.writeHandlerMap = writeHandlerMap; + } + + public Map getConverterMap() { + return converterMap; + } + + public void setConverterMap(Map 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> getHead() { + return head; + } + + public void setHead(List> head) { + this.head = head; + } + + public Class getClazz() { + return clazz; + } + + public void setClazz(Class clazz) { + this.clazz = clazz; + } + + protected Map, List> sortAndClearUpHandler( + List handlerList, Map, List> parentHandlerMap) { + // add + if (parentHandlerMap != null) { + for (List parentHandlerList : parentHandlerMap.values()) { + handlerList.addAll(parentHandlerList); + } + } + // sort + Map> orderExcelWriteHandlerMap = new TreeMap>(); + for (WriteHandler handler : handlerList) { + int order = Integer.MIN_VALUE; + if (handler instanceof Order) { + order = ((Order)handler).order(); + } + if (orderExcelWriteHandlerMap.containsKey(order)) { + orderExcelWriteHandlerMap.get(order).add(handler); + } else { + List tempHandlerList = new ArrayList(); + tempHandlerList.add(handler); + orderExcelWriteHandlerMap.put(order, tempHandlerList); + } + } + // clean up + Set alreadyExistedHandlerSet = new HashSet(); + List cleanUpHandlerList = new ArrayList(); + for (Map.Entry> entry : orderExcelWriteHandlerMap.entrySet()) { + for (WriteHandler handler : entry.getValue()) { + if (handler instanceof NotRepeatExecutor) { + String uniqueValue = ((NotRepeatExecutor)handler).uniqueValue(); + if (alreadyExistedHandlerSet.contains(uniqueValue)) { + continue; + } + alreadyExistedHandlerSet.add(uniqueValue); + } + cleanUpHandlerList.add(handler); + } + } + // classify + Map, List> result = + new HashMap, List>(); + result.put(WriteHandler.class, new ArrayList()); + result.put(WorkbookWriteHandler.class, new ArrayList()); + result.put(SheetWriteHandler.class, new ArrayList()); + result.put(RowWriteHandler.class, new ArrayList()); + result.put(CellWriteHandler.class, new ArrayList()); + 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, List> writeHandlerMap() { + return getWriteHandlerMap(); + } + + @Override + public Map 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(); + } + +} diff --git a/src/main/java/com/alibaba/excel/metadata/holder/SheetHolder.java b/src/main/java/com/alibaba/excel/metadata/holder/SheetHolder.java index ae8a9af..a5f5250 100644 --- a/src/main/java/com/alibaba/excel/metadata/holder/SheetHolder.java +++ b/src/main/java/com/alibaba/excel/metadata/holder/SheetHolder.java @@ -1,21 +1,26 @@ package com.alibaba.excel.metadata.holder; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.ss.usermodel.Sheet; import 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.style.RowCellStyleStrategy; +import com.alibaba.excel.write.style.column.AbstractHeadColumnWidthStyleStrategy; /** * sheet holder * * @author zhuangjiaju */ -public class SheetHolder implements ConfigurationSelector { - +public class SheetHolder extends AbstractConfigurationSelector { /*** * poi sheet */ @@ -36,35 +41,84 @@ public class SheetHolder implements ConfigurationSelector { * has been initialized table */ private Map hasBeenInitializedTable; - /** - * Need Head - */ - private Boolean needHead; - /** - * Write handler for workbook - */ - private List writeHandlerList; - /** - * Converter for workbook - */ - private Map converterMap; /** * current param */ 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 handlerList = new ArrayList(); + if (sheet.getCustomWriteHandlerList() != null && !sheet.getCustomWriteHandlerList().isEmpty()) { + handlerList.addAll(sheet.getCustomWriteHandlerList()); + } + setWriteHandlerMap(sortAndClearUpHandler(handlerList, workbookHolder.getWriteHandlerMap())); + Map converterMap = new HashMap(workbookHolder.converterMap()); + if (sheet.getCustomConverterMap() != null && !sheet.getCustomConverterMap().isEmpty()) { + converterMap.putAll(sheet.getCustomConverterMap()); + } + setConverterMap(converterMap); + setHasBeenInitializedTable(new HashMap()); + } + /** - * 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 + * Compatible with old code */ - private Boolean newInitialization; + @Deprecated + private void compatibleOldCode(com.alibaba.excel.metadata.Sheet sheet) { + if (sheet.getColumnWidthMap() != null && !sheet.getColumnWidthMap().isEmpty()) { + final Map columnWidthMap = sheet.getColumnWidthMap(); + if (sheet.getCustomWriteHandlerList() == null) { + sheet.setCustomWriteHandlerList(new ArrayList()); + } + 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()); + } + CellStyle headCellStyle = new CellStyle(); + headCellStyle.setFont(tableStyle.getTableHeadFont()); + headCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor()); + CellStyle contentCellStyle = new CellStyle(); + contentCellStyle.setFont(tableStyle.getTableContentFont()); + contentCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor()); + sheet.getCustomWriteHandlerList().add(new RowCellStyleStrategy(headCellStyle, contentCellStyle)); + } + } public Sheet getSheet() { return sheet; @@ -106,30 +160,6 @@ public class SheetHolder implements ConfigurationSelector { this.hasBeenInitializedTable = hasBeenInitializedTable; } - public Boolean getNeedHead() { - return needHead; - } - - public void setNeedHead(Boolean needHead) { - this.needHead = needHead; - } - - public List getWriteHandlerList() { - return writeHandlerList; - } - - public void setWriteHandlerList(List writeHandlerList) { - this.writeHandlerList = writeHandlerList; - } - - public Map getConverterMap() { - return converterMap; - } - - public void setConverterMap(Map converterMap) { - this.converterMap = converterMap; - } - public com.alibaba.excel.metadata.Sheet getSheetParam() { return sheetParam; } @@ -137,59 +167,4 @@ public class SheetHolder implements ConfigurationSelector { public void setSheetParam(com.alibaba.excel.metadata.Sheet 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 writeHandlerList() { - return getWriteHandlerList(); - } - - @Override - public Map 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(); - } - } diff --git a/src/main/java/com/alibaba/excel/metadata/holder/TableHolder.java b/src/main/java/com/alibaba/excel/metadata/holder/TableHolder.java index 2ccb9f8..6ffb84e 100644 --- a/src/main/java/com/alibaba/excel/metadata/holder/TableHolder.java +++ b/src/main/java/com/alibaba/excel/metadata/holder/TableHolder.java @@ -1,19 +1,23 @@ package com.alibaba.excel.metadata.holder; +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.metadata.ExcelHeadProperty; +import com.alibaba.excel.metadata.CellStyle; import com.alibaba.excel.metadata.Table; +import com.alibaba.excel.metadata.TableStyle; import com.alibaba.excel.write.handler.WriteHandler; +import com.alibaba.excel.write.style.RowCellStyleStrategy; /** * sheet holder * * @author zhuangjiaju */ -public class TableHolder implements ConfigurationSelector { +public class TableHolder extends AbstractConfigurationSelector { /*** * poi sheet */ @@ -22,35 +26,69 @@ public class TableHolder implements ConfigurationSelector { * tableNo */ private Integer tableNo; - /** - * Need Head - */ - private Boolean needHead; - /** - * Write handler for workbook - */ - private List writeHandlerList; - /** - * Converter for workbook - */ - private Map 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 */ 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 handlerList = new ArrayList(); + if (table.getCustomWriteHandlerList() != null && !table.getCustomWriteHandlerList().isEmpty()) { + handlerList.addAll(table.getCustomWriteHandlerList()); + } + setWriteHandlerMap(sortAndClearUpHandler(handlerList, sheetHolder.getWriteHandlerMap())); + Map converterMap = new HashMap(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()); + } + CellStyle headCellStyle = new CellStyle(); + headCellStyle.setFont(tableStyle.getTableHeadFont()); + headCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor()); + CellStyle contentCellStyle = new CellStyle(); + contentCellStyle.setFont(tableStyle.getTableContentFont()); + contentCellStyle.setIndexedColors(tableStyle.getTableContentBackGroundColor()); + table.getCustomWriteHandlerList().add(new RowCellStyleStrategy(headCellStyle, contentCellStyle)); + } + } public SheetHolder getParentSheet() { return parentSheet; @@ -68,46 +106,6 @@ public class TableHolder implements ConfigurationSelector { this.tableNo = tableNo; } - public Boolean getNeedHead() { - return needHead; - } - - public void setNeedHead(Boolean needHead) { - this.needHead = needHead; - } - - public List getWriteHandlerList() { - return writeHandlerList; - } - - public void setWriteHandlerList(List writeHandlerList) { - this.writeHandlerList = writeHandlerList; - } - - public Map getConverterMap() { - return converterMap; - } - - public void setConverterMap(Map 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() { return tableParam; } @@ -115,42 +113,4 @@ public class TableHolder implements ConfigurationSelector { public void setTableParam(Table tableParam) { this.tableParam = tableParam; } - - public Boolean getNewInitialization() { - return newInitialization; - } - - public void setNewInitialization(Boolean newInitialization) { - this.newInitialization = newInitialization; - } - - @Override - public List writeHandlerList() { - return getWriteHandlerList(); - } - - @Override - public Map 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(); - } } diff --git a/src/main/java/com/alibaba/excel/metadata/holder/WorkbookHolder.java b/src/main/java/com/alibaba/excel/metadata/holder/WorkbookHolder.java index fdecf03..433d238 100644 --- a/src/main/java/com/alibaba/excel/metadata/holder/WorkbookHolder.java +++ b/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.OutputStream; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.ss.usermodel.Workbook; import 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; /** @@ -16,31 +19,15 @@ import com.alibaba.excel.write.handler.WriteHandler; * * @author zhuangjiaju */ -public class WorkbookHolder implements ConfigurationSelector { +public class WorkbookHolder extends AbstractConfigurationSelector { /*** * poi Workbook */ private Workbook workbook; - /** - * Need Head - */ - private Boolean needHead; - /** - * Write handler for workbook - */ - private List writeHandlerList; - /** - * Converter for workbook - */ - private Map converterMap; /** * prevent duplicate creation of sheet objects */ private Map hasBeenInitializedSheet; - /** - * Writes the head relative to the existing contents of the sheet. Indexes are zero-based. - */ - private Integer writeRelativeHeadRowIndex; /** * current param */ @@ -53,6 +40,56 @@ public class WorkbookHolder implements ConfigurationSelector { * Template input stream */ 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 handlerList = new ArrayList(); + if (workbook.getCustomWriteHandlerList() != null && !workbook.getCustomWriteHandlerList().isEmpty()) { + handlerList.addAll(workbook.getCustomWriteHandlerList()); + } + handlerList.addAll(DefaultWriteHandlerBuilder.loadDefaultHandler()); + setWriteHandlerMap(sortAndClearUpHandler(handlerList, null)); + Map converterMap = DefaultConverterBuilder.loadDefaultWriteConverter(); + if (workbook.getCustomConverterMap() != null && !workbook.getCustomConverterMap().isEmpty()) { + converterMap.putAll(workbook.getCustomConverterMap()); + } + setConverterMap(converterMap); + setHasBeenInitializedSheet(new HashMap()); + } public Workbook getWorkbook() { return workbook; @@ -62,30 +99,6 @@ public class WorkbookHolder implements ConfigurationSelector { this.workbook = workbook; } - public Boolean getNeedHead() { - return needHead; - } - - public void setNeedHead(Boolean needHead) { - this.needHead = needHead; - } - - public List getWriteHandlerList() { - return writeHandlerList; - } - - public void setWriteHandlerList(List writeHandlerList) { - this.writeHandlerList = writeHandlerList; - } - - public Map getConverterMap() { - return converterMap; - } - - public void setConverterMap(Map converterMap) { - this.converterMap = converterMap; - } - public Map getHasBeenInitializedSheet() { return hasBeenInitializedSheet; } @@ -94,14 +107,6 @@ public class WorkbookHolder implements ConfigurationSelector { this.hasBeenInitializedSheet = hasBeenInitializedSheet; } - public Integer getWriteRelativeHeadRowIndex() { - return writeRelativeHeadRowIndex; - } - - public void setWriteRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) { - this.writeRelativeHeadRowIndex = writeRelativeHeadRowIndex; - } - public com.alibaba.excel.metadata.Workbook getWorkbookParam() { return workbookParam; } @@ -126,33 +131,19 @@ public class WorkbookHolder implements ConfigurationSelector { this.templateInputStream = templateInputStream; } - @Override - public List writeHandlerList() { - return getWriteHandlerList(); - } - - @Override - public Map converterMap() { - return getConverterMap(); - } - - @Override - public boolean needHead() { - return getNeedHead(); + public com.alibaba.excel.event.WriteHandler getWriteHandler() { + return writeHandler; } - @Override - public int writeRelativeHeadRowIndex() { - return getWriteRelativeHeadRowIndex(); + public void setWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) { + this.writeHandler = writeHandler; } - @Override - public ExcelHeadProperty excelHeadProperty() { - return null; + public Boolean getAutoCloseStream() { + return autoCloseStream; } - @Override - public boolean isNew() { - return true; + public void setAutoCloseStream(Boolean autoCloseStream) { + this.autoCloseStream = autoCloseStream; } } diff --git a/src/main/java/com/alibaba/excel/util/StyleUtil.java b/src/main/java/com/alibaba/excel/util/StyleUtil.java index 9a864ac..29ba219 100644 --- a/src/main/java/com/alibaba/excel/util/StyleUtil.java +++ b/src/main/java/com/alibaba/excel/util/StyleUtil.java @@ -45,7 +45,7 @@ public class StyleUtil { * @return */ public static CellStyle buildHeadCellStyle(Workbook workbook, com.alibaba.excel.metadata.CellStyle cs) { - CellStyle cellStyle = workbook.createCellStyle(); + CellStyle cellStyle = buildDefaultCellStyle(workbook); if (cs == null) { return cellStyle; } @@ -61,7 +61,7 @@ public class StyleUtil { */ public static CellStyle buildHeadCellStyle(Workbook workbook, com.alibaba.excel.metadata.Font f, IndexedColors indexedColors) { - CellStyle cellStyle = workbook.createCellStyle(); + CellStyle cellStyle = buildDefaultCellStyle(workbook); return buildCellStyle(workbook, cellStyle, f, indexedColors); } @@ -73,7 +73,7 @@ public class StyleUtil { * @return */ public static CellStyle buildContentCellStyle(Workbook workbook, com.alibaba.excel.metadata.CellStyle cs) { - CellStyle cellStyle = buildDefaultCellStyle(workbook); + CellStyle cellStyle = workbook.createCellStyle(); if (cs == null) { return cellStyle; } @@ -89,7 +89,7 @@ public class StyleUtil { */ public static CellStyle buildContentCellStyle(Workbook workbook, com.alibaba.excel.metadata.Font f, IndexedColors indexedColors) { - CellStyle cellStyle = buildDefaultCellStyle(workbook); + CellStyle cellStyle = workbook.createCellStyle(); return buildCellStyle(workbook, cellStyle, f, indexedColors); } diff --git a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java index 3b9109a..13ad6fd 100644 --- a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java +++ b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java @@ -40,6 +40,10 @@ public class WorkBookUtil { 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) { Cell cell = row.createCell(colNum); cell.setCellStyle(cellStyle); diff --git a/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java b/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java index 5ac5bf4..9d558c5 100644 --- a/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java +++ b/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.metadata.CellData; import com.alibaba.excel.metadata.ExcelColumnProperty; +import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Table; import com.alibaba.excel.metadata.holder.ConfigurationSelector; import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.POITempFile; 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; @@ -43,9 +47,9 @@ public class ExcelBuilderImpl implements ExcelBuilder { if (context.currentConfigurationSelector().isNew()) { rowNum += context.currentConfigurationSelector().writeRelativeHeadRowIndex(); } - for (int i = 0; i < data.size(); i++) { - int n = i + rowNum + 1; - addOneRowOfDataToExcel(data.get(i), n); + for (int relativeRowIndex = 0; relativeRowIndex < data.size(); relativeRowIndex++) { + int n = relativeRowIndex + rowNum + 1; + addOneRowOfDataToExcel(data.get(relativeRowIndex), n, relativeRowIndex); } } @@ -72,40 +76,113 @@ public class ExcelBuilderImpl implements ExcelBuilder { 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); + afterRowCreate(row, relativeRowIndex); if (oneRowData instanceof List) { - addBasicTypeToExcel((List)oneRowData, row); + addBasicTypeToExcel((List)oneRowData, row, relativeRowIndex); } else { - addJavaObjectToExcel(oneRowData, row); + addJavaObjectToExcel(oneRowData, row, relativeRowIndex); } } - private void addBasicTypeToExcel(List oneRowData, Row row) { + private void beforeRowCreate(int rowIndex, int relativeRowIndex) { + List 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 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 oneRowData, Row row, int relativeRowIndex) { if (CollectionUtils.isEmpty(oneRowData)) { return; } + List headList = context.currentConfigurationSelector().excelHeadProperty().getHeadList(); 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); 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(); int i = 0; BeanMap beanMap = BeanMap.create(oneRowData); + List headList = context.currentConfigurationSelector().excelHeadProperty().getHeadList(); for (ExcelColumnProperty excelHeadProperty : currentConfigurationSelector.excelHeadProperty() .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()); converterAndSet(currentConfigurationSelector, excelHeadProperty.getField().getType(), cell, value, excelHeadProperty); + afterCellCreate(head, cell, relativeRowIndex); i++; } } + private void beforeCellCreate(Row row, Head head, int relativeRowIndex) { + List 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 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, Object value, ExcelColumnProperty excelHeadProperty) { if (value == null) { @@ -117,7 +194,7 @@ public class ExcelBuilderImpl implements ExcelBuilder { "Can not find 'Converter' support class " + clazz.getSimpleName() + "."); } - CellData cellData = null; + CellData cellData; try { cellData = converter.convertToExcelData(value, excelHeadProperty); } catch (Exception e) { @@ -130,13 +207,13 @@ public class ExcelBuilderImpl implements ExcelBuilder { } switch (cellData.getType()) { case STRING: - cell.setCellValue(cell.getStringCellValue()); + cell.setCellValue(cellData.getStringValue()); return; case BOOLEAN: - cell.setCellValue(cell.getBooleanCellValue()); + cell.setCellValue(cellData.getBooleanValue()); return; case NUMBER: - cell.setCellValue(cell.getNumericCellValue()); + cell.setCellValue(cellData.getDoubleValue()); return; default: throw new ExcelDataConvertException("Not supported data:" + value + " return type:" + cell.getCellType() diff --git a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java index 4b6ae8c..8e7cf64 100644 --- a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java +++ b/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.HashMap; import java.util.List; -import java.util.Map; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.converters.Converter; +import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.metadata.Workbook; import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.write.handler.WriteHandler; @@ -25,102 +25,158 @@ import com.alibaba.excel.write.handler.WriteHandler; */ 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. + * + *
  • 0 - This Sheet has no head ,since the first row are the data + *
  • 1 - This Sheet has one row head , this is the default + *
  • 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> 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 customConverterMap = new HashMap(); + public ExcelWriterBuilder head(Class clazz) { + workbook.setClazz(clazz); + return this; + } + /** * 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 customWriteHandlerList = new ArrayList(); + 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 - private com.alibaba.excel.event.WriteHandler writeHandler; + public ExcelWriterBuilder registerConverter(Converter converter) { + if (workbook.getCustomConverterMap() == null) { + workbook.setCustomConverterMap(new HashMap()); + } + 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()); + } + workbook.getCustomWriteHandlerList().add(writeHandler); + return this; + } public ExcelWriterBuilder excelType(ExcelTypeEnum excelType) { - this.excelType = excelType; + workbook.setExcelType(excelType); return this; } public ExcelWriterBuilder outputFile(OutputStream outputStream) { - this.outputStream = outputStream; + workbook.setOutputStream(outputStream); return this; } - public ExcelWriterBuilder outputFile(File outputFile) throws FileNotFoundException { - return outputFile(new FileOutputStream(outputFile)); + public ExcelWriterBuilder outputFile(File 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)); } - public ExcelWriterBuilder outputFile(URI outputUri) throws FileNotFoundException { + public ExcelWriterBuilder outputFile(URI outputUri) { return outputFile(new File(outputUri)); } public ExcelWriterBuilder withTemplate(InputStream templateInputStream) { - this.templateInputStream = templateInputStream; + workbook.setTemplateInputStream(templateInputStream); return this; } - public ExcelWriterBuilder withTemplate(File templateFile) throws FileNotFoundException { - return withTemplate(new FileInputStream(templateFile)); + public ExcelWriterBuilder withTemplate(File 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)); } - public ExcelWriterBuilder withTemplate(URI templateUri) throws FileNotFoundException { + public ExcelWriterBuilder withTemplate(URI 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 * @@ -128,19 +184,11 @@ public class ExcelWriterBuilder { */ @Deprecated public ExcelWriterBuilder registerWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) { - this.writeHandler = writeHandler; + workbook.setWriteHandler(writeHandler); return this; } 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); } } diff --git a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java index e99baa1..9ac3e62 100644 --- a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java +++ b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java @@ -1,20 +1,11 @@ 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.HashMap; import java.util.List; -import java.util.Map; -import com.alibaba.excel.ExcelWriter; 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; /** @@ -24,97 +15,124 @@ import com.alibaba.excel.write.handler.WriteHandler; */ public class ExcelWriterSheetBuilder { /** - * Excel type + * Sheet */ - private ExcelTypeEnum excelType; - /** - * Final output stream - */ - private OutputStream outputStream; - /** - * Template input stream - */ - private InputStream templateInputStream; - /** - * Custom type conversions override the default - */ - private Map customConverterMap = new HashMap(); - /** - * Need Head - */ - private Boolean needHead; - /** - * Custom type handler override the default - */ - private List customWriteHandlerList = new ArrayList(); + private Sheet sheet; - public ExcelWriterSheetBuilder excelType(ExcelTypeEnum excelType) { - this.excelType = excelType; - return this; + public ExcelWriterSheetBuilder() { + this.sheet = new Sheet(); } - public ExcelWriterSheetBuilder outputFile(OutputStream outputStream) { - this.outputStream = outputStream; + /** + * Count the number of added heads when read sheet. + * + *
  • 0 - This Sheet has no head ,since the first row are the data + *
  • 1 - This Sheet has one row head , this is the default + *
  • 2 - This Sheet has two row head ,since the third row is the data + * + * @param readHeadRowNumber + * @return + */ + public ExcelWriterSheetBuilder readHeadRowNumber(Integer readHeadRowNumber) { + sheet.setReadHeadRowNumber(readHeadRowNumber); return this; } - public ExcelWriterSheetBuilder outputFile(File outputFile) throws FileNotFoundException { - return outputFile(new FileOutputStream(outputFile)); - } - - public ExcelWriterSheetBuilder outputFile(String outputPathName) throws FileNotFoundException { - return outputFile(new File(outputPathName)); - } - - public ExcelWriterSheetBuilder outputFile(URI outputUri) throws FileNotFoundException { - return outputFile(new File(outputUri)); - } - - public ExcelWriterSheetBuilder withTemplate(InputStream templateInputStream) { - this.templateInputStream = templateInputStream; + /** + * Writes the head relative to the existing contents of the sheet. Indexes are zero-based. + * + * @param writeRelativeHeadRowIndex + * @return + */ + public ExcelWriterSheetBuilder writeRelativeHeadRowIndex(Integer writeRelativeHeadRowIndex) { + sheet.setWriteRelativeHeadRowIndex(writeRelativeHeadRowIndex); 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> 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. - * + * * @param converter * @return */ public ExcelWriterSheetBuilder registerConverter(Converter converter) { - this.customConverterMap.put(converter.supportJavaTypeKey(), converter); + if (sheet.getCustomConverterMap() == null) { + sheet.setCustomConverterMap(new HashMap()); + } + sheet.getCustomConverterMap().put(converter.supportJavaTypeKey(), converter); return this; } /** - * Default required header + * Custom write handler + * + * @param writeHandler + * @return + */ + public ExcelWriterSheetBuilder registerWriteHandler(WriteHandler writeHandler) { + if (sheet.getCustomWriteHandlerList() == null) { + sheet.setCustomWriteHandlerList(new ArrayList()); + } + sheet.getCustomWriteHandlerList().add(writeHandler); + return this; + } + + /** + * Starting from 0 * + * @param sheetNo * @return */ - public ExcelWriterSheetBuilder doNotNeedHead() { - this.needHead = Boolean.FALSE; + public ExcelWriterSheetBuilder sheetNo(Integer sheetNo) { + sheet.setSheetNo(sheetNo); 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; } - public ExcelWriter build() { - return new ExcelWriter(templateInputStream, outputStream, excelType, needHead, customConverterMap, - customWriteHandlerList); + public Sheet build() { + return sheet; } + } diff --git a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java new file mode 100644 index 0000000..faf1392 --- /dev/null +++ b/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. + * + *
  • 0 - This Sheet has no head ,since the first row are the data + *
  • 1 - This Sheet has one row head , this is the default + *
  • 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> 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()); + } + 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()); + } + 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; + } + +} diff --git a/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerBuilder.java b/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerBuilder.java index 74a47c1..6d00d86 100644 --- a/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerBuilder.java +++ b/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.Font; import com.alibaba.excel.write.style.RowCellStyleStrategy; -import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy; /** * Build default handler @@ -28,10 +27,10 @@ public class DefaultWriteHandlerBuilder { Font font = new Font(); headCellStyle.setFont(font); font.setFontName("宋体"); + font.setFontHeightInPoints((short)14); font.setBold(true); headCellStyle.setIndexedColors(IndexedColors.GREY_25_PERCENT); handlerList.add(new RowCellStyleStrategy(headCellStyle, new ArrayList())); - handlerList.add(new SimpleColumnWidthStyleStrategy(20)); return handlerList; } diff --git a/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java index 56f7b7a..6a1fe82 100644 --- a/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java +++ b/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.holder.SheetHolder; 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.WorkbookWriteHandler; -public abstract class AbstractCellStyleStrategy - implements CellWriteHandler, WorkbookWriteHandler, NotRepeatExecutor { +public abstract class AbstractCellStyleStrategy implements CellWriteHandler, WorkbookWriteHandler, NotRepeatExecutor { @Override public String uniqueValue() { return "CellStyleStrategy"; @@ -22,8 +22,8 @@ public abstract class AbstractCellStyleStrategy public void beforeWorkbookCreate() {} @Override - public void afterWorkbookCreate(Workbook workbook) { - initCellStyle(workbook); + public void afterWorkbookCreate(WorkbookHolder workbookHolder) { + initCellStyle(workbookHolder.getWorkbook()); } @Override diff --git a/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java index aec327b..88ac289 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java +++ b/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 - * @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); } diff --git a/src/main/java/com/alibaba/excel/write/style/column/SimpleColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/SimpleColumnWidthStyleStrategy.java index 4b1ec08..969c08b 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/SimpleColumnWidthStyleStrategy.java +++ b/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 { 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. SimpleColumnWidthStyleStrategy( 8*256), + * + * @param columnWidth + * the width in units of 1/256th of a character width + */ public SimpleColumnWidthStyleStrategy(int columnWidth) { this.columnWidth = columnWidth; } diff --git a/src/test/java/com/alibaba/easyexcel/test/util/FileUtil.java b/src/test/java/com/alibaba/easyexcel/test/util/FileUtil.java index 0307821..72e34a5 100644 --- a/src/test/java/com/alibaba/easyexcel/test/util/FileUtil.java +++ b/src/test/java/com/alibaba/easyexcel/test/util/FileUtil.java @@ -1,5 +1,6 @@ package com.alibaba.easyexcel.test.util; +import java.io.File; import java.io.InputStream; public class FileUtil { @@ -7,8 +8,16 @@ public class FileUtil { public static InputStream getResourcesFileInputStream(String fileName) { return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName); } - + public static String 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; + } } diff --git a/src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData.java b/src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData.java new file mode 100644 index 0000000..43d8d54 --- /dev/null +++ b/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; + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData03Test.java b/src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData03Test.java new file mode 100644 index 0000000..95d639e --- /dev/null +++ b/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() { + + } + +} diff --git a/src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData07Test.java b/src/test/java/com/alibaba/easyexcel/test/wirte/simple/SimpleData07Test.java new file mode 100644 index 0000000..994721e --- /dev/null +++ b/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 createData(int count) { + List list = new ArrayList(); + for (int i = 0; i < count; i++) { + SimpleData simpleData = new SimpleData(); + simpleData.setString("字符体" + i); + list.add(simpleData); + } + return list; + } +} diff --git a/src/test/resources/logback.xml b/src/test/resources/logback.xml index 1814024..602049a 100644 --- a/src/test/resources/logback.xml +++ b/src/test/resources/logback.xml @@ -6,11 +6,8 @@ ${LOG_PATTERN} - - INFO - - +