Browse Source

修改完成底层基于新的celldata

pull/2074/head
Jiaju Zhuang 4 years ago
parent
commit
051e5612b4
  1. 1
      easyexcel
  2. 10
      src/main/java/com/alibaba/excel/analysis/v03/handlers/BlankRecordHandler.java
  3. 10
      src/main/java/com/alibaba/excel/analysis/v03/handlers/BoolErrRecordHandler.java
  4. 12
      src/main/java/com/alibaba/excel/analysis/v03/handlers/DummyRecordHandler.java
  5. 10
      src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelRecordHandler.java
  6. 14
      src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelSstRecordHandler.java
  7. 10
      src/main/java/com/alibaba/excel/analysis/v03/handlers/RkRecordHandler.java
  8. 6
      src/main/java/com/alibaba/excel/annotation/write/style/HeadStyle.java
  9. 13
      src/main/java/com/alibaba/excel/constant/OrderConstant.java
  10. 4
      src/main/java/com/alibaba/excel/context/WriteContextImpl.java
  11. 1
      src/main/java/com/alibaba/excel/converters/WriteConverterContext.java
  12. 5
      src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java
  13. 9
      src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java
  14. 15
      src/main/java/com/alibaba/excel/event/Handler.java
  15. 2
      src/main/java/com/alibaba/excel/metadata/AbstractHolder.java
  16. 8
      src/main/java/com/alibaba/excel/metadata/AbstractParameterBuilder.java
  17. 16
      src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java
  18. 10
      src/main/java/com/alibaba/excel/metadata/data/CommentData.java
  19. 25
      src/main/java/com/alibaba/excel/metadata/data/CoordinateData.java
  20. 16
      src/main/java/com/alibaba/excel/metadata/data/HyperlinkData.java
  21. 4
      src/main/java/com/alibaba/excel/metadata/data/ImageData.java
  22. 2
      src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java
  23. 2
      src/main/java/com/alibaba/excel/metadata/data/RichTextStringData.java
  24. 8
      src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java
  25. 45
      src/main/java/com/alibaba/excel/metadata/property/ExcelContentProperty.java
  26. 203
      src/main/java/com/alibaba/excel/metadata/property/StyleProperty.java
  27. 7
      src/main/java/com/alibaba/excel/read/builder/AbstractExcelReaderParameterBuilder.java
  28. 12
      src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java
  29. 22
      src/main/java/com/alibaba/excel/util/ClassUtils.java
  30. 13
      src/main/java/com/alibaba/excel/util/FileTypeUtils.java
  31. 15
      src/main/java/com/alibaba/excel/util/ListUtils.java
  32. 2
      src/main/java/com/alibaba/excel/util/NumberUtils.java
  33. 154
      src/main/java/com/alibaba/excel/util/StyleUtil.java
  34. 6
      src/main/java/com/alibaba/excel/util/WorkBookUtil.java
  35. 94
      src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java
  36. 250
      src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java
  37. 18
      src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java
  38. 8
      src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java
  39. 13
      src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java
  40. 50
      src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java
  41. 17
      src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java
  42. 31
      src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java
  43. 19
      src/main/java/com/alibaba/excel/write/handler/SheetWriteHandler.java
  44. 28
      src/main/java/com/alibaba/excel/write/handler/WorkbookWriteHandler.java
  45. 69
      src/main/java/com/alibaba/excel/write/handler/context/CellWriteHandlerContext.java
  46. 52
      src/main/java/com/alibaba/excel/write/handler/context/RowWriteHandlerContext.java
  47. 30
      src/main/java/com/alibaba/excel/write/handler/context/SheetWriteHandlerContext.java
  48. 25
      src/main/java/com/alibaba/excel/write/handler/context/WorkbookWriteHandlerContext.java
  49. 11
      src/main/java/com/alibaba/excel/write/handler/impl/DefaultRowWriteHandler.java
  50. 76
      src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java
  51. 43
      src/main/java/com/alibaba/excel/write/handler/impl/FillStyleCellWriteHandler.java
  52. 14
      src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java
  53. 25
      src/main/java/com/alibaba/excel/write/metadata/WriteTable.java
  54. 178
      src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java
  55. 75
      src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java
  56. 11
      src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java
  57. 63
      src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java
  58. 93
      src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java
  59. 17
      src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java
  60. 29
      src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java
  61. 8
      src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java
  62. 18
      src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java
  63. 39
      src/main/java/com/alibaba/excel/write/style/row/AbstractRowHeightStyleStrategy.java
  64. 10
      src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java
  65. 22
      src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java
  66. 16
      src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityData.java
  67. 34
      src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataListener.java
  68. 157
      src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java
  69. 142
      src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java
  70. 12
      src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java
  71. 4
      src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java
  72. 14
      src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java
  73. 17
      src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java
  74. 28
      src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java
  75. 11
      src/test/java/com/alibaba/easyexcel/test/demo/read/CustomStringStringConverter.java
  76. 14
      src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java
  77. 29
      src/test/java/com/alibaba/easyexcel/test/demo/write/CustomStringStringConverter.java
  78. 7
      src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatData.java
  79. 20
      src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatTest.java
  80. 18
      src/test/java/com/alibaba/easyexcel/test/temp/read/HeadReadTest.java
  81. 4
      src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java

1
easyexcel

@ -1 +0,0 @@
Subproject commit 4076b897953b18f9e96c278c6929325e89f2be12

10
src/main/java/com/alibaba/excel/analysis/v03/handlers/BlankRecordHandler.java

@ -1,11 +1,11 @@
package com.alibaba.excel.analysis.v03.handlers;
import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.Record;
/**
* Record handler
@ -18,6 +18,6 @@ public class BlankRecordHandler extends AbstractXlsRecordHandler implements Igno
public void processRecord(XlsReadContext xlsReadContext, Record record) {
BlankRecord br = (BlankRecord)record;
xlsReadContext.xlsReadSheetHolder().getCellMap().put((int)br.getColumn(),
CellData.newEmptyInstance(br.getRow(), (int)br.getColumn()));
ReadCellData.newEmptyInstance(br.getRow(), (int)br.getColumn()));
}
}

10
src/main/java/com/alibaba/excel/analysis/v03/handlers/BoolErrRecordHandler.java

@ -1,12 +1,12 @@
package com.alibaba.excel.analysis.v03.handlers;
import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.enums.RowTypeEnum;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.Record;
/**
* Record handler
@ -19,7 +19,7 @@ public class BoolErrRecordHandler extends AbstractXlsRecordHandler implements Ig
public void processRecord(XlsReadContext xlsReadContext, Record record) {
BoolErrRecord ber = (BoolErrRecord)record;
xlsReadContext.xlsReadSheetHolder().getCellMap().put((int)ber.getColumn(),
CellData.newInstance(ber.getBooleanValue(), ber.getRow(), (int)ber.getColumn()));
ReadCellData.newInstance(ber.getBooleanValue(), ber.getRow(), (int)ber.getColumn()));
xlsReadContext.xlsReadSheetHolder().setTempRowType(RowTypeEnum.DATA);
}
}

12
src/main/java/com/alibaba/excel/analysis/v03/handlers/DummyRecordHandler.java

@ -2,18 +2,18 @@ package com.alibaba.excel.analysis.v03.handlers;
import java.util.LinkedHashMap;
import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.enums.RowTypeEnum;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.xls.XlsReadSheetHolder;
import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
import org.apache.poi.hssf.record.Record;
/**
* Record handler
*
@ -35,7 +35,7 @@ public class DummyRecordHandler extends AbstractXlsRecordHandler implements Igno
} else if (record instanceof MissingCellDummyRecord) {
MissingCellDummyRecord mcdr = (MissingCellDummyRecord)record;
xlsReadSheetHolder.getCellMap().put(mcdr.getColumn(),
CellData.newEmptyInstance(mcdr.getRow(), mcdr.getColumn()));
ReadCellData.newEmptyInstance(mcdr.getRow(), mcdr.getColumn()));
}
}
}

10
src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelRecordHandler.java

@ -1,12 +1,12 @@
package com.alibaba.excel.analysis.v03.handlers;
import org.apache.poi.hssf.record.LabelRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.enums.RowTypeEnum;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import org.apache.poi.hssf.record.LabelRecord;
import org.apache.poi.hssf.record.Record;
/**
* Record handler
@ -22,7 +22,7 @@ public class LabelRecordHandler extends AbstractXlsRecordHandler implements Igno
data = data.trim();
}
xlsReadContext.xlsReadSheetHolder().getCellMap().put((int)lrec.getColumn(),
CellData.newInstance(data, lrec.getRow(), (int)lrec.getColumn()));
ReadCellData.newInstance(data, lrec.getRow(), (int)lrec.getColumn()));
xlsReadContext.xlsReadSheetHolder().setTempRowType(RowTypeEnum.DATA);
}
}

14
src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelSstRecordHandler.java

@ -2,15 +2,15 @@ package com.alibaba.excel.analysis.v03.handlers;
import java.util.Map;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.cache.ReadCache;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.enums.RowTypeEnum;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.Record;
/**
* Record handler
@ -25,18 +25,18 @@ public class LabelSstRecordHandler extends AbstractXlsRecordHandler implements I
ReadCache readCache = xlsReadContext.readWorkbookHolder().getReadCache();
Map<Integer, Cell> cellMap = xlsReadContext.xlsReadSheetHolder().getCellMap();
if (readCache == null) {
cellMap.put((int)lsrec.getColumn(), CellData.newEmptyInstance(lsrec.getRow(), (int)lsrec.getColumn()));
cellMap.put((int)lsrec.getColumn(), ReadCellData.newEmptyInstance(lsrec.getRow(), (int)lsrec.getColumn()));
return;
}
String data = readCache.get(lsrec.getSSTIndex());
if (data == null) {
cellMap.put((int)lsrec.getColumn(), CellData.newEmptyInstance(lsrec.getRow(), (int)lsrec.getColumn()));
cellMap.put((int)lsrec.getColumn(), ReadCellData.newEmptyInstance(lsrec.getRow(), (int)lsrec.getColumn()));
return;
}
if (xlsReadContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
data = data.trim();
}
cellMap.put((int)lsrec.getColumn(), CellData.newInstance(data, lsrec.getRow(), (int)lsrec.getColumn()));
cellMap.put((int)lsrec.getColumn(), ReadCellData.newInstance(data, lsrec.getRow(), (int)lsrec.getColumn()));
xlsReadContext.xlsReadSheetHolder().setTempRowType(RowTypeEnum.DATA);
}
}

10
src/main/java/com/alibaba/excel/analysis/v03/handlers/RkRecordHandler.java

@ -1,11 +1,11 @@
package com.alibaba.excel.analysis.v03.handlers;
import org.apache.poi.hssf.record.RKRecord;
import org.apache.poi.hssf.record.Record;
import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import org.apache.poi.hssf.record.RKRecord;
import org.apache.poi.hssf.record.Record;
/**
* Record handler
@ -18,6 +18,6 @@ public class RkRecordHandler extends AbstractXlsRecordHandler implements Ignorab
public void processRecord(XlsReadContext xlsReadContext, Record record) {
RKRecord re = (RKRecord)record;
xlsReadContext.xlsReadSheetHolder().getCellMap().put((int)re.getColumn(),
CellData.newEmptyInstance(re.getRow(), (int)re.getColumn()));
ReadCellData.newEmptyInstance(re.getRow(), (int)re.getColumn()));
}
}

6
src/main/java/com/alibaba/excel/annotation/write/style/HeadStyle.java

@ -53,7 +53,6 @@ public @interface HeadStyle {
/**
* Set whether the text should be wrapped. Setting this flag to <code>true</code> make all content visible within a
* cell by displaying it on multiple lines
*
*/
boolean wrapped() default true;
@ -108,7 +107,6 @@ public @interface HeadStyle {
* Set the color to use for the right border
*
* @see IndexedColors
*
*/
short rightBorderColor() default -1;
@ -116,7 +114,6 @@ public @interface HeadStyle {
* Set the color to use for the top border
*
* @see IndexedColors
*
*/
short topBorderColor() default -1;
@ -124,7 +121,6 @@ public @interface HeadStyle {
* Set the color to use for the bottom border
*
* @see IndexedColors
*
*/
short bottomBorderColor() default -1;
@ -139,7 +135,6 @@ public @interface HeadStyle {
* Set the background fill color.
*
* @see IndexedColors
*
*/
short fillBackgroundColor() default -1;
@ -147,7 +142,6 @@ public @interface HeadStyle {
* Set the foreground fill color <i>Note: Ensure Foreground color is set prior to background color.</i>
*
* @see IndexedColors
*
*/
short fillForegroundColor() default -1;

13
src/main/java/com/alibaba/excel/constant/OrderConstant.java

@ -6,8 +6,19 @@ package com.alibaba.excel.constant;
* @author Jiaju Zhuang
*/
public class OrderConstant {
/**
* Define style.
*/
public static final int DEFINE_STYLE = -50000;
/**
* default order.
*/
public static final int DEFAULT_ORDER = 0;
/**
* Sorting of styles written to cells.
*/
public static final int FILL_DATA_FORMAT = 10000;
public static final int FILL_STYLE = 50000;
}

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

@ -8,8 +8,8 @@ import java.util.UUID;
import com.alibaba.excel.enums.WriteTypeEnum;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.FileUtils;
@ -248,7 +248,7 @@ public class WriteContextImpl implements WriteContext {
Cell cell = row.createCell(columnIndex);
WriteHandlerUtils.afterCellCreate(this, cell, head, relativeRowIndex, Boolean.TRUE);
cell.setCellValue(head.getHeadNameList().get(relativeRowIndex));
WriteHandlerUtils.afterCellDispose(this, (CellData) null, cell, head, relativeRowIndex, Boolean.TRUE);
WriteHandlerUtils.afterCellDispose(this, (WriteCellData<?>) null, cell, head, relativeRowIndex, Boolean.TRUE);
}
}

1
src/main/java/com/alibaba/excel/converters/WriteConverterContext.java

@ -3,6 +3,7 @@ package com.alibaba.excel.converters;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
/**

5
src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java

@ -9,7 +9,6 @@ import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
import com.alibaba.excel.write.metadata.holder.WriteHolder;
/**
* BigDecimal and number converter
@ -36,7 +35,7 @@ public class BigDecimalNumberConverter implements Converter<BigDecimal> {
@Override
public WriteCellData<?> convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty,
WriteHolder currentWriteHolder) {
return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder);
GlobalConfiguration globalConfiguration) {
return NumberUtils.formatToCellData(value, contentProperty);
}
}

9
src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java

@ -6,6 +6,7 @@ import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.WorkBookUtil;
/**
@ -23,11 +24,11 @@ public class DateDateConverter implements Converter<Date> {
public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws Exception {
WriteCellData<?> cellData = new WriteCellData<>(value);
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null
|| contentProperty.getDateTimeFormatProperty().getFormat() == null) {
return cellData;
String format = null;
if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) {
format = contentProperty.getDateTimeFormatProperty().getFormat();
}
WorkBookUtil.fillDataFormat(cellData, contentProperty.getDateTimeFormatProperty().getFormat());
WorkBookUtil.fillDataFormat(cellData, format, DateUtils.defaultDateFormat);
return cellData;
}
}

15
src/main/java/com/alibaba/excel/event/Handler.java

@ -1,8 +1,21 @@
package com.alibaba.excel.event;
import com.alibaba.excel.constant.OrderConstant;
/**
* Intercepts handle some business logic
*
* @author Jiaju Zhuang
**/
public interface Handler {}
public interface Handler extends Order {
/**
* handler order
*
* @return order
*/
@Override
default int order() {
return OrderConstant.DEFAULT_ORDER;
}
}

2
src/main/java/com/alibaba/excel/metadata/AbstractHolder.java

@ -28,7 +28,7 @@ public abstract class AbstractHolder implements ConfigurationHolder {
/**
* You can only choose one of the {@link AbstractHolder#head} and {@link AbstractHolder#clazz}
*/
private Class clazz;
private Class<?> clazz;
/**
* Some global variables
*/

8
src/main/java/com/alibaba/excel/metadata/AbstractParameterBuilder.java

@ -1,10 +1,10 @@
package com.alibaba.excel.metadata;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.util.ListUtils;
/**
* ExcelBuilder
@ -29,7 +29,7 @@ public abstract class AbstractParameterBuilder<T extends AbstractParameterBuilde
* @param clazz
* @return
*/
public T head(Class clazz) {
public T head(Class<?> clazz) {
parameter().setClazz(clazz);
return self();
}
@ -40,9 +40,9 @@ public abstract class AbstractParameterBuilder<T extends AbstractParameterBuilde
* @param converter
* @return
*/
public T registerConverter(Converter converter) {
public T registerConverter(Converter<?> converter) {
if (parameter().getCustomConverterList() == null) {
parameter().setCustomConverterList(new ArrayList<Converter>());
parameter().setCustomConverterList(ListUtils.newArrayList());
}
parameter().getCustomConverterList().add(converter);
return self();

16
src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java

@ -1,6 +1,7 @@
package com.alibaba.excel.metadata.data;
import lombok.Data;
import lombok.Getter;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.util.Internal;
@ -47,6 +48,7 @@ public class ClientAnchorData extends CoordinateData {
*/
private AnchorType anchorType;
@Getter
public enum AnchorType {
/**
* Move and Resize With Anchor Cells (0)
@ -56,7 +58,7 @@ public class ClientAnchorData extends CoordinateData {
* object is anchored to the actual from and to row and column)
* </p>
*/
MOVE_AND_RESIZE(0),
MOVE_AND_RESIZE(ClientAnchor.AnchorType.MOVE_AND_RESIZE),
/**
* Don't Move but do Resize With Anchor Cells (1)
@ -67,7 +69,7 @@ public class ClientAnchorData extends CoordinateData {
* </p>
* Note: Excel has no setting for this combination, nor does the ECMA standard.
*/
DONT_MOVE_DO_RESIZE(1),
DONT_MOVE_DO_RESIZE(ClientAnchor.AnchorType.DONT_MOVE_DO_RESIZE),
/**
* Move With Cells but Do Not Resize (2)
@ -81,7 +83,7 @@ public class ClientAnchorData extends CoordinateData {
* the drawing shall move its to anchors as needed to maintain this same absolute size.
* </p>
*/
MOVE_DONT_RESIZE(2),
MOVE_DONT_RESIZE(ClientAnchor.AnchorType.MOVE_DONT_RESIZE),
/**
* Do Not Move or Resize With Underlying Rows/Columns (3)
@ -96,13 +98,13 @@ public class ClientAnchorData extends CoordinateData {
* to maintain this same absolute position.
* </p>
*/
DONT_MOVE_AND_RESIZE(3);
DONT_MOVE_AND_RESIZE(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
public final short value;
ClientAnchor.AnchorType value;
// disallow non-sequential enum instance creation
private AnchorType(int value) {
this.value = (short)value;
private AnchorType(ClientAnchor.AnchorType value) {
this.value = value;
}
/**

10
src/main/java/com/alibaba/excel/metadata/data/CommentData.java

@ -8,15 +8,7 @@ import lombok.Data;
* @author Jiaju Zhuang
*/
@Data
public class CommentData {
/**
* Row index
*/
private Integer rowIndex;
/**
* Column index
*/
private Integer columnIndex;
public class CommentData extends ClientAnchorData {
/**
* Name of the original comment author
*/

25
src/main/java/com/alibaba/excel/metadata/data/CoordinateData.java

@ -10,19 +10,36 @@ import lombok.Data;
@Data
public class CoordinateData {
/**
* first row index
* first row index.Priority is higher than {@link #relativeFirstRowIndex}.
*/
private Integer firstRowIndex;
/**
* first column index
* first column index.Priority is higher than {@link #relativeFirstColumnIndex}.
*/
private Integer firstColumnIndex;
/**
* last row index
* last row index.Priority is higher than {@link #relativeLastRowIndex}.
*/
private Integer lastRowIndex;
/**
* last column index
* last column index.Priority is higher than {@link #relativeLastColumnIndex}.
*/
private Integer lastColumnIndex;
/**
* relative first row index
*/
private Integer relativeFirstRowIndex;
/**
* relative first column index
*/
private Integer relativeFirstColumnIndex;
/**
* relative last row index
*/
private Integer relativeLastRowIndex;
/**
*relative last column index
*/
private Integer relativeLastColumnIndex;
}

16
src/main/java/com/alibaba/excel/metadata/data/HyperlinkData.java

@ -1,6 +1,7 @@
package com.alibaba.excel.metadata.data;
import lombok.Data;
import lombok.Getter;
/**
* hyperlink
@ -18,35 +19,36 @@ public class HyperlinkData extends CoordinateData {
*/
private HyperlinkType hyperlinkType;
@Getter
public enum HyperlinkType {
/**
* Not a hyperlink
*/
NONE(-1),
NONE(org.apache.poi.common.usermodel.HyperlinkType.NONE),
/**
* Link to an existing file or web page
*/
URL(1),
URL(org.apache.poi.common.usermodel.HyperlinkType.URL),
/**
* Link to a place in this document
*/
DOCUMENT(2),
DOCUMENT(org.apache.poi.common.usermodel.HyperlinkType.DOCUMENT),
/**
* Link to an E-mail address
*/
EMAIL(3),
EMAIL(org.apache.poi.common.usermodel.HyperlinkType.EMAIL),
/**
* Link to a file
*/
FILE(4);
FILE(org.apache.poi.common.usermodel.HyperlinkType.FILE);
public final int value;
org.apache.poi.common.usermodel.HyperlinkType value;
HyperlinkType(int value) {
HyperlinkType(org.apache.poi.common.usermodel.HyperlinkType value) {
this.value = value;
}
}

4
src/main/java/com/alibaba/excel/metadata/data/ImageData.java

@ -1,6 +1,7 @@
package com.alibaba.excel.metadata.data;
import lombok.Data;
import lombok.Getter;
/**
* image
@ -20,6 +21,7 @@ public class ImageData extends ClientAnchorData {
*/
private ImageType imageType;
@Getter
public enum ImageType {
/**
* Extended windows meta file
@ -48,7 +50,7 @@ public class ImageData extends ClientAnchorData {
;
public final int value;
int value;
ImageType(int value) {
this.value = value;

2
src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java

@ -5,6 +5,7 @@ import java.math.BigDecimal;
import com.alibaba.excel.enums.CellDataTypeEnum;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* read cell data
@ -12,6 +13,7 @@ import lombok.Data;
* @author Jiaju Zhuang
*/
@Data
@NoArgsConstructor
public class ReadCellData<T> extends CellData<T> {
/**
* data format.

2
src/main/java/com/alibaba/excel/metadata/data/RichTextStringData.java

@ -10,7 +10,7 @@ import lombok.Data;
import lombok.NoArgsConstructor;
/**
* TODO
* rich text string
*
* @author Jiaju Zhuang
*/

8
src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java

@ -9,6 +9,7 @@ import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* wirte cell data
@ -16,6 +17,7 @@ import lombok.Data;
* @author Jiaju Zhuang
*/
@Data
@NoArgsConstructor
public class WriteCellData<T> extends CellData<T> {
/**
* Support only when writing.{@link CellDataTypeEnum#DATE}
@ -42,11 +44,15 @@ public class WriteCellData<T> extends CellData<T> {
*/
private WriteCellStyle writeCellStyle;
public WriteCellData(String stringValue) {
this(CellDataTypeEnum.STRING, stringValue);
}
public WriteCellData(CellDataTypeEnum type) {
super();
setType(type);
}
public WriteCellData(CellDataTypeEnum type, String stringValue) {
super();
if (type != CellDataTypeEnum.STRING && type != CellDataTypeEnum.ERROR) {

45
src/main/java/com/alibaba/excel/metadata/property/ExcelContentProperty.java

@ -5,9 +5,12 @@ import java.lang.reflect.Field;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.Head;
import lombok.Data;
/**
* @author jipengfei
*/
@Data
public class ExcelContentProperty {
/**
* Java filed
@ -20,47 +23,7 @@ public class ExcelContentProperty {
/**
* Custom defined converters
*/
private Converter converter;
private Converter<?> converter;
private DateTimeFormatProperty dateTimeFormatProperty;
private NumberFormatProperty numberFormatProperty;
public Field getField() {
return field;
}
public void setField(Field field) {
this.field = field;
}
public Head getHead() {
return head;
}
public void setHead(Head head) {
this.head = head;
}
public DateTimeFormatProperty getDateTimeFormatProperty() {
return dateTimeFormatProperty;
}
public void setDateTimeFormatProperty(DateTimeFormatProperty dateTimeFormatProperty) {
this.dateTimeFormatProperty = dateTimeFormatProperty;
}
public NumberFormatProperty getNumberFormatProperty() {
return numberFormatProperty;
}
public void setNumberFormatProperty(NumberFormatProperty numberFormatProperty) {
this.numberFormatProperty = numberFormatProperty;
}
public Converter getConverter() {
return converter;
}
public void setConverter(Converter converter) {
this.converter = converter;
}
}

203
src/main/java/com/alibaba/excel/metadata/property/StyleProperty.java

@ -1,5 +1,11 @@
package com.alibaba.excel.metadata.property;
import com.alibaba.excel.annotation.write.style.ContentStyle;
import com.alibaba.excel.annotation.write.style.HeadStyle;
import com.alibaba.excel.metadata.data.DataFormatData;
import com.alibaba.excel.write.metadata.style.WriteFont;
import lombok.Data;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.ss.usermodel.FillPatternType;
@ -8,20 +14,17 @@ import org.apache.poi.ss.usermodel.IgnoredErrorType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import com.alibaba.excel.annotation.write.style.ContentStyle;
import com.alibaba.excel.annotation.write.style.HeadStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
/**
* Configuration from annotations
*
* @author Jiaju Zhuang
*/
@Data
public class StyleProperty {
/**
* Set the data format (must be a valid format). Built in formats are defined at {@link BuiltinFormats}.
*/
private Short dataFormat;
private DataFormatData dataFormatData;
/**
* Set the font for this style
*/
@ -48,7 +51,6 @@ public class StyleProperty {
/**
* Set whether the text should be wrapped. Setting this flag to <code>true</code> make all content visible within a
* cell by displaying it on multiple lines
*
*/
private Boolean wrapped;
/**
@ -96,7 +98,6 @@ public class StyleProperty {
* Set the color to use for the right border
*
* @see IndexedColors
*
*/
private Short rightBorderColor;
@ -104,14 +105,12 @@ public class StyleProperty {
* Set the color to use for the top border
*
* @see IndexedColors
*
*/
private Short topBorderColor;
/**
* Set the color to use for the bottom border
*
* @see IndexedColors
*
*/
private Short bottomBorderColor;
/**
@ -125,7 +124,6 @@ public class StyleProperty {
* Set the background fill color.
*
* @see IndexedColors
*
*/
private Short fillBackgroundColor;
@ -133,7 +131,6 @@ public class StyleProperty {
* Set the foreground fill color <i>Note: Ensure Foreground color is set prior to background color.</i>
*
* @see IndexedColors
*
*/
private Short fillForegroundColor;
/**
@ -146,7 +143,9 @@ public class StyleProperty {
return null;
}
StyleProperty styleProperty = new StyleProperty();
styleProperty.setDataFormat(headStyle.dataFormat());
DataFormatData dataFormatData = new DataFormatData();
dataFormatData.setIndex(headStyle.dataFormat());
styleProperty.setDataFormatData(dataFormatData);
styleProperty.setHidden(headStyle.hidden());
styleProperty.setLocked(headStyle.locked());
styleProperty.setQuotePrefix(headStyle.quotePrefix());
@ -175,7 +174,9 @@ public class StyleProperty {
return null;
}
StyleProperty styleProperty = new StyleProperty();
styleProperty.setDataFormat(contentStyle.dataFormat());
DataFormatData dataFormatData = new DataFormatData();
dataFormatData.setIndex(contentStyle.dataFormat());
styleProperty.setDataFormatData(dataFormatData);
styleProperty.setHidden(contentStyle.hidden());
styleProperty.setLocked(contentStyle.locked());
styleProperty.setQuotePrefix(contentStyle.quotePrefix());
@ -198,180 +199,4 @@ public class StyleProperty {
styleProperty.setShrinkToFit(contentStyle.shrinkToFit());
return styleProperty;
}
public Short getDataFormat() {
return dataFormat;
}
public void setDataFormat(Short dataFormat) {
this.dataFormat = dataFormat;
}
public WriteFont getWriteFont() {
return writeFont;
}
public void setWriteFont(WriteFont writeFont) {
this.writeFont = writeFont;
}
public Boolean getHidden() {
return hidden;
}
public void setHidden(Boolean hidden) {
this.hidden = hidden;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
public Boolean getQuotePrefix() {
return quotePrefix;
}
public void setQuotePrefix(Boolean quotePrefix) {
this.quotePrefix = quotePrefix;
}
public HorizontalAlignment getHorizontalAlignment() {
return horizontalAlignment;
}
public void setHorizontalAlignment(HorizontalAlignment horizontalAlignment) {
this.horizontalAlignment = horizontalAlignment;
}
public Boolean getWrapped() {
return wrapped;
}
public void setWrapped(Boolean wrapped) {
this.wrapped = wrapped;
}
public VerticalAlignment getVerticalAlignment() {
return verticalAlignment;
}
public void setVerticalAlignment(VerticalAlignment verticalAlignment) {
this.verticalAlignment = verticalAlignment;
}
public Short getRotation() {
return rotation;
}
public void setRotation(Short rotation) {
this.rotation = rotation;
}
public Short getIndent() {
return indent;
}
public void setIndent(Short indent) {
this.indent = indent;
}
public BorderStyle getBorderLeft() {
return borderLeft;
}
public void setBorderLeft(BorderStyle borderLeft) {
this.borderLeft = borderLeft;
}
public BorderStyle getBorderRight() {
return borderRight;
}
public void setBorderRight(BorderStyle borderRight) {
this.borderRight = borderRight;
}
public BorderStyle getBorderTop() {
return borderTop;
}
public void setBorderTop(BorderStyle borderTop) {
this.borderTop = borderTop;
}
public BorderStyle getBorderBottom() {
return borderBottom;
}
public void setBorderBottom(BorderStyle borderBottom) {
this.borderBottom = borderBottom;
}
public Short getLeftBorderColor() {
return leftBorderColor;
}
public void setLeftBorderColor(Short leftBorderColor) {
this.leftBorderColor = leftBorderColor;
}
public Short getRightBorderColor() {
return rightBorderColor;
}
public void setRightBorderColor(Short rightBorderColor) {
this.rightBorderColor = rightBorderColor;
}
public Short getTopBorderColor() {
return topBorderColor;
}
public void setTopBorderColor(Short topBorderColor) {
this.topBorderColor = topBorderColor;
}
public Short getBottomBorderColor() {
return bottomBorderColor;
}
public void setBottomBorderColor(Short bottomBorderColor) {
this.bottomBorderColor = bottomBorderColor;
}
public FillPatternType getFillPatternType() {
return fillPatternType;
}
public void setFillPatternType(FillPatternType fillPatternType) {
this.fillPatternType = fillPatternType;
}
public Short getFillBackgroundColor() {
return fillBackgroundColor;
}
public void setFillBackgroundColor(Short fillBackgroundColor) {
this.fillBackgroundColor = fillBackgroundColor;
}
public Short getFillForegroundColor() {
return fillForegroundColor;
}
public void setFillForegroundColor(Short fillForegroundColor) {
this.fillForegroundColor = fillForegroundColor;
}
public Boolean getShrinkToFit() {
return shrinkToFit;
}
public void setShrinkToFit(Boolean shrinkToFit) {
this.shrinkToFit = shrinkToFit;
}
}

7
src/main/java/com/alibaba/excel/read/builder/AbstractExcelReaderParameterBuilder.java

@ -1,10 +1,9 @@
package com.alibaba.excel.read.builder;
import java.util.ArrayList;
import com.alibaba.excel.metadata.AbstractParameterBuilder;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadBasicParameter;
import com.alibaba.excel.util.ListUtils;
/**
* Build ExcelBuilder
@ -50,9 +49,9 @@ public abstract class AbstractExcelReaderParameterBuilder<T extends AbstractExce
* @param readListener
* @return
*/
public T registerReadListener(ReadListener readListener) {
public T registerReadListener(ReadListener<?> readListener) {
if (parameter().getCustomReadListenerList() == null) {
parameter().setCustomReadListenerList(new ArrayList<ReadListener>());
parameter().setCustomReadListenerList(ListUtils.newArrayList());
}
parameter().getCustomReadListenerList().add(readListener);
return self();

12
src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java

@ -4,16 +4,13 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.enums.RowTypeEnum;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelAnalysisStopException;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
@ -21,6 +18,9 @@ import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty;
import com.alibaba.excel.util.ConverterUtils;
import com.alibaba.excel.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Analysis event
*
@ -82,7 +82,7 @@ public class DefaultAnalysisEventProcessor implements AnalysisEventProcessor {
private void dealData(AnalysisContext analysisContext) {
ReadRowHolder readRowHolder = analysisContext.readRowHolder();
Map<Integer, CellData<?>> cellDataMap = (Map)readRowHolder.getCellMap();
Map<Integer, ReadCellData<?>> cellDataMap = (Map)readRowHolder.getCellMap();
readRowHolder.setCurrentRowAnalysisResult(cellDataMap);
int rowIndex = readRowHolder.getRowIndex();
int currentHeadRowNumber = analysisContext.readSheetHolder().getHeadRowNumber();
@ -111,7 +111,7 @@ public class DefaultAnalysisEventProcessor implements AnalysisEventProcessor {
}
}
private void buildHead(AnalysisContext analysisContext, Map<Integer, CellData<?>> cellDataMap) {
private void buildHead(AnalysisContext analysisContext, Map<Integer, ReadCellData<?>> cellDataMap) {
if (!HeadKindEnum.CLASS.equals(analysisContext.currentReadHolder().excelReadHeadProperty().getHeadKind())) {
return;
}

22
src/main/java/com/alibaba/excel/util/ClassUtils.java

@ -27,10 +27,9 @@ import com.alibaba.excel.write.metadata.holder.WriteHolder;
**/
public class ClassUtils {
private static final Map<Class, SoftReference<FieldCache>> FIELD_CACHE =
new ConcurrentHashMap<Class, SoftReference<FieldCache>>();
private static final Map<Class<?>, SoftReference<FieldCache>> FIELD_CACHE = new ConcurrentHashMap<>();
public static void declaredFields(Class clazz, Map<Integer, Field> sortedAllFiledMap,
public static void declaredFields(Class<?> clazz, Map<Integer, Field> sortedAllFiledMap,
Map<Integer, Field> indexFiledMap, Map<String, Field> ignoreMap, Boolean convertAllFiled,
Boolean needIgnore, Holder holder) {
FieldCache fieldCache = getFieldCache(clazz, convertAllFiled);
@ -69,12 +68,12 @@ public class ClassUtils {
}
}
public static void declaredFields(Class clazz, Map<Integer, Field> sortedAllFiledMap, Boolean convertAllFiled,
public static void declaredFields(Class<?> clazz, Map<Integer, Field> sortedAllFiledMap, Boolean convertAllFiled,
Boolean needIgnore, WriteHolder writeHolder) {
declaredFields(clazz, sortedAllFiledMap, null, null, convertAllFiled, needIgnore, writeHolder);
}
private static FieldCache getFieldCache(Class clazz, Boolean convertAllFiled) {
private static FieldCache getFieldCache(Class<?> clazz, Boolean convertAllFiled) {
if (clazz == null) {
return null;
}
@ -92,12 +91,12 @@ public class ClassUtils {
return FIELD_CACHE.get(clazz).get();
}
private static void declaredFields(Class clazz, Boolean convertAllFiled) {
List<Field> tempFieldList = new ArrayList<Field>();
Class tempClass = clazz;
private static void declaredFields(Class<?> clazz, Boolean convertAllFiled) {
List<Field> tempFieldList = new ArrayList<>();
Class<?> tempClass = clazz;
// When the parent class is null, it indicates that the parent class (Object class) has reached the top
// level.
while (tempClass != null && tempClass != BaseRowModel.class) {
while (tempClass != null) {
Collections.addAll(tempFieldList, tempClass.getDeclaredFields());
// Get the parent class and give it to yourself
tempClass = tempClass.getSuperclass();
@ -107,8 +106,7 @@ public class ClassUtils {
Map<Integer, Field> indexFiledMap = new TreeMap<Integer, Field>();
Map<String, Field> ignoreMap = new HashMap<String, Field>(16);
ExcelIgnoreUnannotated excelIgnoreUnannotated =
(ExcelIgnoreUnannotated) clazz.getAnnotation(ExcelIgnoreUnannotated.class);
ExcelIgnoreUnannotated excelIgnoreUnannotated = clazz.getAnnotation(ExcelIgnoreUnannotated.class);
for (Field field : tempFieldList) {
declaredOneField(field, orderFiledMap, indexFiledMap, ignoreMap, excelIgnoreUnannotated, convertAllFiled);
}
@ -208,7 +206,6 @@ public class ClassUtils {
}
}
/**
* <p>Gets a {@code List} of all interfaces implemented by the given
* class and its superclasses.</p>
@ -233,7 +230,6 @@ public class ClassUtils {
return new ArrayList<>(interfacesFound);
}
/**
* Gets the interfaces for the specified class.
*

13
src/main/java/com/alibaba/excel/util/FileTypeUtils.java

@ -18,12 +18,25 @@ public class FileTypeUtils {
private static final Map<String, ImageType> FILE_TYPE_MAP;
/**
* Default image type
*/
public static ImageType defaultImageType = ImageType.PICTURE_TYPE_PNG;
static {
FILE_TYPE_MAP = new HashMap<>();
FILE_TYPE_MAP.put("ffd8ff", ImageType.PICTURE_TYPE_JPEG);
FILE_TYPE_MAP.put("89504e47", ImageType.PICTURE_TYPE_PNG);
}
public static int getImageTypeFormat(byte[] image) {
ImageType imageType = getImageType(image);
if (imageType != null) {
return imageType.getValue();
}
return defaultImageType.getValue();
}
public static ImageType getImageType(byte[] image) {
if (image == null || image.length <= IMAGE_TYPE_MARK_LENGTH) {
return null;

15
src/main/java/com/alibaba/excel/util/ListUtils.java

@ -2,6 +2,7 @@ package com.alibaba.excel.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
@ -27,6 +28,20 @@ public class ListUtils {
return new ArrayList<>();
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements.
*
*/
public static <E> ArrayList<E> newArrayList(E... elements) {
checkNotNull(elements);
// Avoid integer overflow when a large array is passed in
int capacity = computeArrayListCapacity(elements.length);
ArrayList<E> list = new ArrayList<>(capacity);
Collections.addAll(list, elements);
return list;
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements; a very thin
* shortcut for creating an empty list and then calling {@link Iterators#addAll}.

2
src/main/java/com/alibaba/excel/util/NumberUtils.java

@ -61,7 +61,7 @@ public class NumberUtils {
WriteCellData<?> cellData = new WriteCellData<>(BigDecimal.valueOf(num.doubleValue()));
if (contentProperty != null && contentProperty.getNumberFormatProperty() != null
&& StringUtils.isNotBlank(contentProperty.getNumberFormatProperty().getFormat())) {
WorkBookUtil.fillDataFormat(cellData, contentProperty.getNumberFormatProperty().getFormat());
WorkBookUtil.fillDataFormat(cellData, contentProperty.getNumberFormatProperty().getFormat(), null);
}
return cellData;
}

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

@ -1,86 +1,51 @@
package com.alibaba.excel.util;
import com.alibaba.excel.constant.BuiltinFormats;
import com.alibaba.excel.metadata.data.DataFormatData;
import com.alibaba.excel.metadata.data.HyperlinkData;
import com.alibaba.excel.metadata.data.RichTextStringData;
import com.alibaba.excel.metadata.data.RichTextStringData.IntervalFont;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
/**
* @author jipengfei
*/
public class StyleUtil {
public static short XSSF_DEFAULT_STYLE = 0;
public static short HSSF_DEFAULT_STYLE = 15;
public static int baseCoordinate = 10000;
private StyleUtil() {}
/**
* @param workbook
* @return
*/
public static CellStyle buildDefaultCellStyle(Workbook workbook) {
CellStyle newCellStyle = workbook.createCellStyle();
newCellStyle.setWrapText(true);
newCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
newCellStyle.setAlignment(HorizontalAlignment.CENTER);
newCellStyle.setLocked(true);
newCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
newCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
newCellStyle.setBorderTop(BorderStyle.THIN);
newCellStyle.setBorderBottom(BorderStyle.THIN);
newCellStyle.setBorderLeft(BorderStyle.THIN);
newCellStyle.setBorderRight(BorderStyle.THIN);
return newCellStyle;
}
/**
* Build head cell style
*
* @param workbook
* @param writeCellStyle
* @return
*/
public static CellStyle buildHeadCellStyle(Workbook workbook, WriteCellStyle writeCellStyle) {
CellStyle cellStyle = buildDefaultCellStyle(workbook);
if (writeCellStyle == null) {
return cellStyle;
}
buildCellStyle(workbook, cellStyle, writeCellStyle, true);
return cellStyle;
}
/**
* Build content cell style
* Build cell style
*
* @param workbook
* @param writeCellStyle
* @return
*/
public static CellStyle buildContentCellStyle(Workbook workbook, WriteCellStyle writeCellStyle) {
public static CellStyle buildCellStyle(Workbook workbook, WriteCellStyle writeCellStyle) {
CellStyle cellStyle = workbook.createCellStyle();
if (writeCellStyle == null) {
return cellStyle;
}
buildCellStyle(workbook, cellStyle, writeCellStyle, false);
buildCellStyle(cellStyle, writeCellStyle);
return cellStyle;
}
private static void buildCellStyle(Workbook workbook, CellStyle cellStyle, WriteCellStyle writeCellStyle,
boolean isHead) {
buildFont(workbook, cellStyle, writeCellStyle.getWriteFont(), isHead);
if (writeCellStyle.getDataFormat() != null) {
cellStyle.setDataFormat(writeCellStyle.getDataFormat());
}
private static void buildCellStyle(CellStyle cellStyle, WriteCellStyle writeCellStyle) {
if (writeCellStyle.getHidden() != null) {
cellStyle.setHidden(writeCellStyle.getHidden());
}
@ -143,21 +108,24 @@ public class StyleUtil {
}
}
private static void buildFont(Workbook workbook, CellStyle cellStyle, WriteFont writeFont, boolean isHead) {
Font font = null;
if (isHead) {
font = workbook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short)14);
font.setBold(true);
cellStyle.setFont(font);
public static short buildDataFormat(Workbook workbook, DataFormatData dataFormatData) {
if (dataFormatData == null) {
return BuiltinFormats.GENERAL;
}
if (writeFont == null) {
return;
if (dataFormatData.getIndex() != null && dataFormatData.getIndex() >= 0) {
return dataFormatData.getIndex();
}
if (!isHead) {
font = workbook.createFont();
cellStyle.setFont(font);
if (StringUtils.isNotBlank(dataFormatData.getFormat())) {
DataFormat dataFormatCreate = workbook.createDataFormat();
return dataFormatCreate.getFormat(dataFormatData.getFormat());
}
return BuiltinFormats.GENERAL;
}
public static Font buildFont(Workbook workbook, WriteFont writeFont) {
Font font = workbook.createFont();
if (writeFont == null) {
return font;
}
if (writeFont.getFontName() != null) {
font.setFontName(writeFont.getFontName());
@ -186,15 +154,57 @@ public class StyleUtil {
if (writeFont.getBold() != null) {
font.setBold(writeFont.getBold());
}
return font;
}
public static RichTextString buildRichTextString(WriteWorkbookHolder writeWorkbookHolder,
RichTextStringData richTextStringData) {
if (richTextStringData == null) {
return null;
}
RichTextString richTextString;
if (writeWorkbookHolder.getExcelType() == ExcelTypeEnum.XLSX) {
richTextString = new XSSFRichTextString(richTextStringData.getTextString());
} else {
richTextString = new HSSFRichTextString(richTextStringData.getTextString());
}
if (richTextStringData.getWriteFont() != null) {
richTextString.applyFont(writeWorkbookHolder.createFont(richTextStringData.getWriteFont()));
}
if (CollectionUtils.isNotEmpty(richTextStringData.getIntervalFontList())) {
for (IntervalFont intervalFont : richTextStringData.getIntervalFontList()) {
richTextString.applyFont(intervalFont.getStartIndex(), intervalFont.getEndIndex(),
writeWorkbookHolder.createFont(intervalFont.getWriteFont()));
}
}
return richTextString;
}
public static HyperlinkType getHyperlinkType(HyperlinkData.HyperlinkType hyperlinkType) {
if (hyperlinkType == null) {
return HyperlinkType.NONE;
}
return hyperlinkType.getValue();
}
public static int getCoordinate(Integer coordinate) {
if (coordinate == null) {
return 0;
}
return baseCoordinate * coordinate;
}
public static boolean isDefaultStyle(CellStyle cellStyle) {
if (cellStyle == null) {
return true;
public static int getCellCoordinate(Integer currentCoordinate, Integer absoluteCoordinate,
Integer relativeCoordinate) {
if (absoluteCoordinate != null && absoluteCoordinate > 0) {
return absoluteCoordinate;
}
if (cellStyle instanceof XSSFCellStyle) {
return cellStyle.getIndex() == XSSF_DEFAULT_STYLE;
if (relativeCoordinate != null) {
return currentCoordinate + relativeCoordinate;
}
return cellStyle.getIndex() == HSSF_DEFAULT_STYLE;
return currentCoordinate;
}
}

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

@ -94,7 +94,7 @@ public class WorkBookUtil {
return cell;
}
public static void fillDataFormat(WriteCellData<?> cellData, String format) {
public static void fillDataFormat(WriteCellData<?> cellData, String format, String defaultFormat) {
if (cellData.getWriteCellStyle() == null) {
cellData.setWriteCellStyle(new WriteCellStyle());
}
@ -102,7 +102,11 @@ public class WorkBookUtil {
cellData.getWriteCellStyle().setDataFormatData(new DataFormatData());
}
if (cellData.getWriteCellStyle().getDataFormatData().getFormat() == null) {
if (format == null) {
cellData.getWriteCellStyle().getDataFormatData().setFormat(defaultFormat);
} else {
cellData.getWriteCellStyle().getDataFormatData().setFormat(format);
}
}
}
}

94
src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java

@ -1,17 +1,20 @@
package com.alibaba.excel.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
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.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import com.alibaba.excel.write.handler.context.WorkbookWriteHandlerContext;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
@ -34,9 +37,10 @@ public class WriteHandlerUtils {
if (handlerList == null || handlerList.isEmpty()) {
return;
}
WorkbookWriteHandlerContext context = new WorkbookWriteHandlerContext(writeContext, null);
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof WorkbookWriteHandler) {
((WorkbookWriteHandler)writeHandler).beforeWorkbookCreate();
((WorkbookWriteHandler)writeHandler).beforeWorkbookCreate(context);
}
}
}
@ -50,9 +54,11 @@ public class WriteHandlerUtils {
if (handlerList == null || handlerList.isEmpty()) {
return;
}
WorkbookWriteHandlerContext context = new WorkbookWriteHandlerContext(writeContext,
writeContext.writeWorkbookHolder());
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof WorkbookWriteHandler) {
((WorkbookWriteHandler)writeHandler).afterWorkbookCreate(writeContext.writeWorkbookHolder());
((WorkbookWriteHandler)writeHandler).afterWorkbookCreate(context);
}
}
}
@ -63,9 +69,11 @@ public class WriteHandlerUtils {
if (handlerList == null || handlerList.isEmpty()) {
return;
}
WorkbookWriteHandlerContext context = new WorkbookWriteHandlerContext(writeContext,
writeContext.writeWorkbookHolder());
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof WorkbookWriteHandler) {
((WorkbookWriteHandler)writeHandler).afterWorkbookDispose(writeContext.writeWorkbookHolder());
((WorkbookWriteHandler)writeHandler).afterWorkbookDispose(context);
}
}
}
@ -79,10 +87,11 @@ public class WriteHandlerUtils {
if (handlerList == null || handlerList.isEmpty()) {
return;
}
SheetWriteHandlerContext context = new SheetWriteHandlerContext(writeContext,
writeContext.writeWorkbookHolder(), writeContext.writeSheetHolder());
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof SheetWriteHandler) {
((SheetWriteHandler)writeHandler).beforeSheetCreate(writeContext.writeWorkbookHolder(),
writeContext.writeSheetHolder());
((SheetWriteHandler)writeHandler).beforeSheetCreate(context);
}
}
}
@ -96,16 +105,13 @@ public class WriteHandlerUtils {
if (handlerList == null || handlerList.isEmpty()) {
return;
}
SheetWriteHandlerContext context = new SheetWriteHandlerContext(writeContext,
writeContext.writeWorkbookHolder(), writeContext.writeSheetHolder());
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof SheetWriteHandler) {
((SheetWriteHandler)writeHandler).afterSheetCreate(writeContext.writeWorkbookHolder(),
writeContext.writeSheetHolder());
((SheetWriteHandler)writeHandler).afterSheetCreate(context);
}
}
if (null != writeContext.writeWorkbookHolder().getWriteWorkbook().getWriteHandler()) {
writeContext.writeWorkbookHolder().getWriteWorkbook().getWriteHandler()
.sheet(writeContext.writeSheetHolder().getSheetNo(), writeContext.writeSheetHolder().getSheet());
}
}
public static void beforeCellCreate(WriteContext writeContext, Row row, Head head, Integer columnIndex,
@ -115,10 +121,12 @@ public class WriteHandlerUtils {
if (handlerList == null || handlerList.isEmpty()) {
return;
}
CellWriteHandlerContext context = new CellWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(),
writeContext.writeSheetHolder(), writeContext.writeTableHolder(), row, null, columnIndex, relativeRowIndex,
head, null, isHead);
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof CellWriteHandler) {
((CellWriteHandler)writeHandler).beforeCellCreate(writeContext.writeSheetHolder(),
writeContext.writeTableHolder(), row, head, columnIndex, relativeRowIndex, isHead);
((CellWriteHandler)writeHandler).beforeCellCreate(context);
}
}
}
@ -130,53 +138,56 @@ public class WriteHandlerUtils {
if (handlerList == null || handlerList.isEmpty()) {
return;
}
CellWriteHandlerContext context = new CellWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(),
writeContext.writeSheetHolder(), writeContext.writeTableHolder(), cell.getRow(), cell,
cell.getColumnIndex(), relativeRowIndex, head, null, isHead);
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof CellWriteHandler) {
((CellWriteHandler)writeHandler).afterCellCreate(writeContext.writeSheetHolder(),
writeContext.writeTableHolder(), cell, head, relativeRowIndex, isHead);
((CellWriteHandler)writeHandler).afterCellCreate(context);
}
}
}
public static void afterCellDataConverted(WriteContext writeContext, CellData cellData, Cell cell, Head head,
public static void afterCellDataConverted(WriteContext writeContext, WriteCellData<?> cellData, Cell cell,
Head head,
Integer relativeRowIndex, Boolean isHead) {
List<WriteHandler> handlerList =
writeContext.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
List<WriteCellData<?>> cellDataList = cellData == null ? null : ListUtils.newArrayList(cellData);
CellWriteHandlerContext context = new CellWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(),
writeContext.writeSheetHolder(), writeContext.writeTableHolder(), cell.getRow(), cell,
cell.getColumnIndex(), relativeRowIndex, head, cellDataList, isHead);
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof CellWriteHandler) {
((CellWriteHandler)writeHandler).afterCellDataConverted(writeContext.writeSheetHolder(),
writeContext.writeTableHolder(), cellData, cell, head, relativeRowIndex, isHead);
((CellWriteHandler)writeHandler).afterCellDataConverted(context);
}
}
}
public static void afterCellDispose(WriteContext writeContext, CellData cellData, Cell cell, Head head,
public static void afterCellDispose(WriteContext writeContext, WriteCellData<?> cellData, Cell cell, Head head,
Integer relativeRowIndex, Boolean isHead) {
List<CellData<?>> cellDataList = new ArrayList<>();
if (cellData != null) {
cellDataList.add(cellData);
}
List<WriteCellData<?>> cellDataList = cellData == null ? null : ListUtils.newArrayList(cellData);
afterCellDispose(writeContext, cellDataList, cell, head, relativeRowIndex, isHead);
}
public static void afterCellDispose(WriteContext writeContext, List<CellData<?>> cellDataList, Cell cell, Head head,
public static void afterCellDispose(WriteContext writeContext, List<WriteCellData<?>> cellDataList, Cell cell,
Head head,
Integer relativeRowIndex, Boolean isHead) {
List<WriteHandler> handlerList =
writeContext.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {
return;
}
CellWriteHandlerContext context = new CellWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(),
writeContext.writeSheetHolder(), writeContext.writeTableHolder(), cell.getRow(), cell,
cell.getColumnIndex(), relativeRowIndex, head, cellDataList, isHead);
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof CellWriteHandler) {
((CellWriteHandler)writeHandler).afterCellDispose(writeContext.writeSheetHolder(),
writeContext.writeTableHolder(), cellDataList, cell, head, relativeRowIndex, isHead);
}
((CellWriteHandler)writeHandler).afterCellDispose(context);
}
if (null != writeContext.writeWorkbookHolder().getWriteWorkbook().getWriteHandler()) {
writeContext.writeWorkbookHolder().getWriteWorkbook().getWriteHandler().cell(cell.getRowIndex(), cell);
}
}
@ -186,10 +197,11 @@ public class WriteHandlerUtils {
if (handlerList == null || handlerList.isEmpty()) {
return;
}
RowWriteHandlerContext context = new RowWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(),
writeContext.writeSheetHolder(), writeContext.writeTableHolder(), rowIndex, null, relativeRowIndex, isHead);
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).beforeRowCreate(writeContext.writeSheetHolder(),
writeContext.writeTableHolder(), rowIndex, relativeRowIndex, isHead);
((RowWriteHandler)writeHandler).beforeRowCreate(context);
}
}
}
@ -199,13 +211,14 @@ public class WriteHandlerUtils {
if (handlerList == null || handlerList.isEmpty()) {
return;
}
RowWriteHandlerContext context = new RowWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(),
writeContext.writeSheetHolder(), writeContext.writeTableHolder(), row.getRowNum(), row, relativeRowIndex,
isHead);
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).afterRowCreate(writeContext.writeSheetHolder(),
writeContext.writeTableHolder(), row, relativeRowIndex, isHead);
((RowWriteHandler)writeHandler).afterRowCreate(context);
}
}
}
public static void afterRowDispose(WriteContext writeContext, Row row, Integer relativeRowIndex, Boolean isHead) {
@ -213,14 +226,13 @@ public class WriteHandlerUtils {
if (handlerList == null || handlerList.isEmpty()) {
return;
}
RowWriteHandlerContext context = new RowWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(),
writeContext.writeSheetHolder(), writeContext.writeTableHolder(), row.getRowNum(), row, relativeRowIndex,
isHead);
for (WriteHandler writeHandler : handlerList) {
if (writeHandler instanceof RowWriteHandler) {
((RowWriteHandler)writeHandler).afterRowDispose(writeContext.writeSheetHolder(),
writeContext.writeTableHolder(), row, relativeRowIndex, isHead);
}
((RowWriteHandler)writeHandler).afterRowDispose(context);
}
if (null != writeContext.writeWorkbookHolder().getWriteWorkbook().getWriteHandler()) {
writeContext.writeWorkbookHolder().getWriteWorkbook().getWriteHandler().row(row.getRowNum(), row);
}
}

250
src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java

@ -1,23 +1,39 @@
package com.alibaba.excel.write.executor;
import java.util.List;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKeyBuild;
import com.alibaba.excel.converters.NullableObjectConverter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.CommentData;
import com.alibaba.excel.metadata.data.FormulaData;
import com.alibaba.excel.metadata.data.HyperlinkData;
import com.alibaba.excel.metadata.data.ImageData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.FileTypeUtils;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.util.WriteHandlerUtils;
import com.alibaba.excel.write.metadata.holder.WriteHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
/**
* Excel write Executor
@ -31,22 +47,35 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor {
this.writeContext = writeContext;
}
protected CellData<?> converterAndSet(WriteHolder currentWriteHolder, Class<?> clazz, CellDataTypeEnum targetType,
Cell cell, Object value,
ExcelContentProperty excelContentProperty, Head head, Integer relativeRowIndex) {
protected WriteCellData<?> converterAndSet(WriteHolder currentWriteHolder, Class<?> clazz,
CellDataTypeEnum targetType, Cell cell, Object value, ExcelContentProperty excelContentProperty, Head head,
Integer relativeRowIndex) {
boolean needTrim = value != null && (value instanceof String && currentWriteHolder.globalConfiguration()
.getAutoTrim());
if (needTrim) {
value = ((String)value).trim();
}
CellData<?> cellData = convert(currentWriteHolder, clazz, targetType, cell, value, excelContentProperty);
if (cellData.getFormula() != null && cellData.getFormula()) {
cell.setCellFormula(cellData.getFormulaValue());
}
WriteCellData<?> cellData = convert(currentWriteHolder, clazz, targetType, cell, value, excelContentProperty);
WriteHandlerUtils.afterCellDataConverted(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE);
// Fill in picture information
fillImage(cell, cellData.getImageDataList());
// Fill in comment information
fillComment(cell, cellData.getCommentData());
// Fill in hyper link information
fillHyperLink(cell, cellData.getHyperlinkData());
// Fill in formula information
fillFormula(cell, cellData.getFormulaData());
// Fill in style information
fillStyle(cell, cellData.getWriteCellStyle());
if (cellData.getType() == null) {
cellData.setType(CellDataTypeEnum.EMPTY);
}
WriteHandlerUtils.afterCellDataConverted(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE);
switch (cellData.getType()) {
case STRING:
cell.setCellValue(cellData.getStringValue());
@ -60,8 +89,9 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor {
case DATE:
cell.setCellValue(cellData.getDateValue());
return cellData;
case IMAGE:
setImageValue(cellData, cell);
case RICH_TEXT_STRING:
cell.setCellValue(StyleUtil
.buildRichTextString(writeContext.writeWorkbookHolder(), cellData.getRichTextStringDataValue()));
return cellData;
case EMPTY:
return cellData;
@ -70,13 +100,131 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor {
excelContentProperty, "Not supported data:" + value + " return type:" + cell.getCellType()
+ "at row:" + cell.getRow().getRowNum());
}
}
private void fillStyle(Cell cell, WriteCellStyle writeCellStyle) {
if (writeCellStyle == null) {
return;
}
CellStyle cellStyle = writeContext.writeWorkbookHolder().createCellStyle(writeCellStyle);
cell.setCellStyle(cellStyle);
}
private void fillFormula(Cell cell, FormulaData formulaData) {
if (formulaData == null) {
return;
}
if (formulaData.getFormulaValue() != null) {
cell.setCellFormula(formulaData.getFormulaValue());
}
}
private void fillHyperLink(Cell cell, HyperlinkData hyperlinkData) {
if (hyperlinkData == null) {
return;
}
CreationHelper helper = cell.getSheet().getWorkbook().getCreationHelper();
Hyperlink hyperlink = helper.createHyperlink(StyleUtil.getHyperlinkType(hyperlinkData.getHyperlinkType()));
hyperlink.setAddress(hyperlinkData.getAddress());
hyperlink.setFirstRow(StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), hyperlinkData.getFirstRowIndex(),
hyperlinkData.getRelativeFirstRowIndex()));
hyperlink.setFirstColumn(StyleUtil.getCellCoordinate(cell.getColumnIndex(), hyperlinkData.getFirstColumnIndex(),
hyperlinkData.getRelativeFirstColumnIndex()));
hyperlink.setLastRow(StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), hyperlinkData.getLastRowIndex(),
hyperlinkData.getRelativeLastRowIndex()));
hyperlink.setLastColumn(StyleUtil.getCellCoordinate(cell.getColumnIndex(), hyperlinkData.getLastColumnIndex(),
hyperlinkData.getRelativeLastColumnIndex()));
}
private void fillComment(Cell cell, CommentData commentData) {
if (commentData == null) {
return;
}
ClientAnchor anchor;
if (writeContext.writeWorkbookHolder().getExcelType() == ExcelTypeEnum.XLSX) {
anchor = new XSSFClientAnchor(StyleUtil.getCoordinate(commentData.getLeft()),
StyleUtil.getCoordinate(commentData.getTop()),
StyleUtil.getCoordinate(commentData.getRight()),
StyleUtil.getCoordinate(commentData.getBottom()),
StyleUtil.getCellCoordinate(cell.getColumnIndex(), commentData.getFirstColumnIndex(),
commentData.getRelativeFirstColumnIndex()),
StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), commentData.getFirstRowIndex(),
commentData.getRelativeFirstRowIndex()),
StyleUtil.getCellCoordinate(cell.getColumnIndex(), commentData.getLastColumnIndex(),
commentData.getRelativeLastColumnIndex()),
StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), commentData.getLastRowIndex(),
commentData.getRelativeLastRowIndex()));
} else {
anchor = new HSSFClientAnchor(StyleUtil.getCoordinate(commentData.getLeft()),
StyleUtil.getCoordinate(commentData.getTop()),
StyleUtil.getCoordinate(commentData.getRight()),
StyleUtil.getCoordinate(commentData.getBottom()),
(short)StyleUtil.getCellCoordinate(cell.getColumnIndex(), commentData.getFirstColumnIndex(),
commentData.getRelativeFirstColumnIndex()),
StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), commentData.getFirstRowIndex(),
commentData.getRelativeFirstRowIndex()),
(short)StyleUtil.getCellCoordinate(cell.getColumnIndex(), commentData.getLastColumnIndex(),
commentData.getRelativeLastColumnIndex()),
StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), commentData.getLastRowIndex(),
commentData.getRelativeLastRowIndex()));
}
Comment comment = cell.getSheet().createDrawingPatriarch().createCellComment(anchor);
if (commentData.getRichTextStringData() != null) {
comment.setString(
StyleUtil.buildRichTextString(writeContext.writeWorkbookHolder(), commentData.getRichTextStringData()));
}
if (commentData.getAuthor() != null) {
comment.setAuthor(commentData.getAuthor());
}
}
protected void fillImage(Cell cell, List<ImageData> imageDataList) {
if (CollectionUtils.isEmpty(imageDataList)) {
return;
}
Sheet sheet = cell.getSheet();
Drawing<?> drawing = sheet.getDrawingPatriarch();
if (drawing == null) {
drawing = sheet.createDrawingPatriarch();
}
CreationHelper helper = sheet.getWorkbook().getCreationHelper();
for (ImageData imageData : imageDataList) {
int index = sheet.getWorkbook().addPicture(imageData.getImage(),
FileTypeUtils.getImageTypeFormat(imageData.getImage()));
ClientAnchor anchor = helper.createClientAnchor();
if (imageData.getTop() != null) {
anchor.setDy1(StyleUtil.getCoordinate(imageData.getTop()));
}
if (imageData.getRight() != null) {
anchor.setDx2(StyleUtil.getCoordinate(imageData.getRight()));
}
if (imageData.getBottom() != null) {
anchor.setDy2(StyleUtil.getCoordinate(imageData.getBottom()));
}
if (imageData.getLeft() != null) {
anchor.setDx1(StyleUtil.getCoordinate(imageData.getLeft()));
}
anchor.setRow1(StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), imageData.getFirstRowIndex(),
imageData.getRelativeFirstRowIndex()));
anchor.setCol1(StyleUtil.getCellCoordinate(cell.getColumnIndex(), imageData.getFirstColumnIndex(),
imageData.getRelativeFirstColumnIndex()));
anchor.setRow2(StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), imageData.getLastRowIndex(),
imageData.getRelativeLastRowIndex()));
anchor.setCol2(StyleUtil.getCellCoordinate(cell.getColumnIndex(), imageData.getLastColumnIndex(),
imageData.getRelativeLastColumnIndex()));
if (imageData.getAnchorType() != null) {
anchor.setAnchorType(imageData.getAnchorType().getValue());
}
drawing.createPicture(anchor, index);
}
}
protected CellData<?> convert(WriteHolder currentWriteHolder, Class<?> clazz, CellDataTypeEnum targetType,
protected WriteCellData<?> convert(WriteHolder currentWriteHolder, Class<?> clazz, CellDataTypeEnum targetType,
Cell cell, Object value, ExcelContentProperty excelContentProperty) {
// This means that the user has defined the data.
if (value instanceof CellData) {
CellData<?> cellDataValue = (CellData<?>)value;
if (value instanceof WriteCellData) {
WriteCellData<?> cellDataValue = (WriteCellData<?>)value;
if (cellDataValue.getType() != null) {
return cellDataValue;
} else {
@ -85,21 +233,33 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor {
return cellDataValue;
}
}
CellData<?> cellDataReturn = doConvert(currentWriteHolder, cellDataValue.getData().getClass(), targetType,
cell, cellDataValue.getData(), excelContentProperty);
WriteCellData<?> cellDataReturn = doConvert(currentWriteHolder, cellDataValue.getData().getClass(),
targetType, cell, cellDataValue.getData(), excelContentProperty);
if (cellDataValue.getImageDataList() != null) {
cellDataReturn.setImageDataList(cellDataValue.getImageDataList());
}
if (cellDataValue.getCommentData() != null) {
cellDataReturn.setCommentData(cellDataValue.getCommentData());
}
if (cellDataValue.getHyperlinkData() != null) {
cellDataReturn.setHyperlinkData(cellDataValue.getHyperlinkData());
}
// The formula information is subject to user input
if (cellDataValue.getFormula() != null) {
cellDataReturn.setFormula(cellDataValue.getFormula());
cellDataReturn.setFormulaValue(cellDataValue.getFormulaValue());
if (cellDataValue.getFormulaData() != null) {
cellDataReturn.setFormulaData(cellDataValue.getFormulaData());
}
if (cellDataValue.getWriteCellStyle() != null) {
cellDataReturn.setWriteCellStyle(cellDataValue.getWriteCellStyle());
}
return cellDataReturn;
}
return doConvert(currentWriteHolder, clazz, targetType, cell, value, excelContentProperty);
}
private CellData<?> doConvert(WriteHolder currentWriteHolder, Class<?> clazz, CellDataTypeEnum targetType,
private WriteCellData<?> doConvert(WriteHolder currentWriteHolder, Class<?> clazz, CellDataTypeEnum targetType,
Cell cell, Object value, ExcelContentProperty excelContentProperty) {
Converter converter = null;
Converter<?> converter = null;
if (excelContentProperty != null) {
converter = excelContentProperty.getConverter();
}
@ -108,58 +268,26 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor {
}
if (converter == null) {
throw new ExcelDataConvertException(cell.getRow().getRowNum(), cell.getColumnIndex(),
new CellData<>(CellDataTypeEnum.EMPTY), excelContentProperty,
new WriteCellData<>(CellDataTypeEnum.EMPTY), excelContentProperty,
"Can not find 'Converter' support class " + clazz.getSimpleName() + ".");
}
if (value == null && !(converter instanceof NullableObjectConverter)) {
return new CellData<>(CellDataTypeEnum.EMPTY);
return new WriteCellData<>(CellDataTypeEnum.EMPTY);
}
CellData<?> cellData;
WriteCellData<?> cellData;
try {
cellData = converter.convertToExcelData(value, excelContentProperty, currentWriteHolder);
cellData = ((Converter<Object>)converter).convertToExcelData(
new WriteConverterContext<>(value, excelContentProperty, writeContext));
} catch (Exception e) {
throw new ExcelDataConvertException(cell.getRow().getRowNum(), cell.getColumnIndex(),
new CellData<>(CellDataTypeEnum.EMPTY), excelContentProperty,
new WriteCellData<>(CellDataTypeEnum.EMPTY), excelContentProperty,
"Convert data:" + value + " error,at row:" + cell.getRow().getRowNum(), e);
}
if (cellData == null || cellData.getType() == null) {
throw new ExcelDataConvertException(cell.getRow().getRowNum(), cell.getColumnIndex(),
new CellData<>(CellDataTypeEnum.EMPTY), excelContentProperty,
new WriteCellData<>(CellDataTypeEnum.EMPTY), excelContentProperty,
"Convert data:" + value + " return null,at row:" + cell.getRow().getRowNum());
}
return cellData;
}
private void setImageValue(CellData<?> cellData, Cell cell) {
Sheet sheet = cell.getSheet();
int index = sheet.getWorkbook().addPicture(cellData.getImageValue(), HSSFWorkbook.PICTURE_TYPE_PNG);
Drawing drawing = sheet.getDrawingPatriarch();
if (drawing == null) {
drawing = sheet.createDrawingPatriarch();
}
CreationHelper helper = sheet.getWorkbook().getCreationHelper();
ClientAnchor anchor = helper.createClientAnchor();
if(cellData.getUseImagePositionProperty()) {
anchor.setDx1(cellData.getImagePositionProperty().getDx1());
anchor.setDx2(cellData.getImagePositionProperty().getDx2());
anchor.setDy1(cellData.getImagePositionProperty().getDy1());
anchor.setDy2(cellData.getImagePositionProperty().getDy2());
anchor.setCol1(cellData.getImagePositionProperty().getCol1());
anchor.setCol2(cellData.getImagePositionProperty().getCol2());
anchor.setRow1(cellData.getImagePositionProperty().getRow1());
anchor.setRow2(cellData.getImagePositionProperty().getRow2());
anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
} else {
anchor.setDx1(0);
anchor.setDx2(0);
anchor.setDy1(0);
anchor.setDy2(0);
anchor.setCol1(cell.getColumnIndex());
anchor.setCol2(cell.getColumnIndex() + 1);
anchor.setRow1(cell.getRowIndex());
anchor.setRow2(cell.getRowIndex() + 1);
anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
}
drawing.createPicture(anchor, index);
}
}

18
src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java

@ -10,8 +10,8 @@ import java.util.TreeMap;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.ClassUtils;
import com.alibaba.excel.util.FieldUtils;
@ -106,14 +106,14 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor {
}
}
private void doAddBasicTypeToExcel(RowData oneRowData, Head head, Row row, int relativeRowIndex,
int dataIndex,
private void doAddBasicTypeToExcel(RowData oneRowData, Head head, Row row, int relativeRowIndex, int dataIndex,
int cellIndex) {
WriteHandlerUtils.beforeCellCreate(writeContext, row, head, cellIndex, relativeRowIndex, Boolean.FALSE);
Cell cell = WorkBookUtil.createCell(row, cellIndex);
WriteHandlerUtils.afterCellCreate(writeContext, cell, head, relativeRowIndex, Boolean.FALSE);
Object value = oneRowData.get(dataIndex);
CellData cellData = converterAndSet(writeContext.currentWriteHolder(), value == null ? null : value.getClass(),
WriteCellData<?> cellData = converterAndSet(writeContext.currentWriteHolder(),
value == null ? null : value.getClass(),
null, cell, value, null, head, relativeRowIndex);
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE);
}
@ -123,7 +123,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor {
WriteHolder currentWriteHolder = writeContext.currentWriteHolder();
BeanMap beanMap = BeanMap.create(oneRowData);
Set<String> beanMapHandledSet = new HashSet<String>();
int cellIndex = 0;
int cellIndex;
// If it's a class it needs to be cast by type
if (HeadKindEnum.CLASS.equals(writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadKind())) {
Map<Integer, Head> headMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadMap();
@ -141,7 +141,8 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor {
Cell cell = WorkBookUtil.createCell(row, cellIndex);
WriteHandlerUtils.afterCellCreate(writeContext, cell, head, relativeRowIndex, Boolean.FALSE);
Object value = beanMap.get(name);
CellData<?> cellData = converterAndSet(currentWriteHolder, excelContentProperty.getField().getType(),
WriteCellData<?> cellData = converterAndSet(currentWriteHolder,
excelContentProperty.getField().getType(),
null,
cell, value, excelContentProperty, head, relativeRowIndex);
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE);
@ -167,13 +168,14 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor {
WriteHandlerUtils.beforeCellCreate(writeContext, row, null, cellIndex, relativeRowIndex, Boolean.FALSE);
Cell cell = WorkBookUtil.createCell(row, cellIndex);
WriteHandlerUtils.afterCellCreate(writeContext, cell, null, relativeRowIndex, Boolean.FALSE);
CellData<?> cellData = converterAndSet(currentWriteHolder, value == null ? null : value.getClass(), null, cell,
WriteCellData<?> cellData = converterAndSet(currentWriteHolder, value == null ? null : value.getClass(),
null, cell,
value, null, null, relativeRowIndex);
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, relativeRowIndex, Boolean.FALSE);
}
}
private void initSortedAllFiledMapFieldList(Class clazz, Map<Integer, Field> sortedAllFiledMap) {
private void initSortedAllFiledMapFieldList(Class<?> clazz, Map<Integer, Field> sortedAllFiledMap) {
if (!sortedAllFiledMap.isEmpty()) {
return;
}

8
src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java

@ -14,7 +14,7 @@ import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.util.WriteHandlerUtils;
@ -198,20 +198,20 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor {
continue;
}
Object value = dataMap.get(variable);
CellData<?> cellData = converterAndSet(writeSheetHolder, value == null ? null : value.getClass(), null,
WriteCellData<?> cellData = converterAndSet(writeSheetHolder, value == null ? null : value.getClass(), null,
cell, value, fieldNameContentPropertyMap.get(variable), null, relativeRowIndex);
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, relativeRowIndex, Boolean.FALSE);
} else {
StringBuilder cellValueBuild = new StringBuilder();
int index = 0;
List<CellData<?>> cellDataList = new ArrayList<>();
List<WriteCellData<?>> cellDataList = new ArrayList<>();
for (String variable : analysisCell.getVariableList()) {
cellValueBuild.append(analysisCell.getPrepareDataList().get(index++));
if (!dataMap.containsKey(variable)) {
continue;
}
Object value = dataMap.get(variable);
CellData<?> cellData = convert(writeSheetHolder, value == null ? null : value.getClass(),
WriteCellData<?> cellData = convert(writeSheetHolder, value == null ? null : value.getClass(),
CellDataTypeEnum.STRING, cell, value, fieldNameContentPropertyMap.get(variable));
cellDataList.add(cellData);
CellDataTypeEnum type = cellData.getType();

13
src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java

@ -2,14 +2,14 @@ package com.alibaba.excel.write.handler;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
* Abstract cell write handler
*
@ -33,13 +33,12 @@ public abstract class AbstractCellWriteHandler implements CellWriteHandler {
@Override
public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
CellData cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<CellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
}

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

@ -2,11 +2,13 @@ package com.alibaba.excel.write.handler;
import java.util.List;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
@ -17,6 +19,16 @@ import org.apache.poi.ss.usermodel.Row;
*/
public interface CellWriteHandler extends WriteHandler {
/**
* Called before create the cell
*
* @param context
*/
default void beforeCellCreate(CellWriteHandlerContext context) {
beforeCellCreate(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getRow(),
context.getHeadData(), context.getColumnIndex(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Called before create the cell
*
@ -31,6 +43,16 @@ public interface CellWriteHandler extends WriteHandler {
default void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after the cell is created
*
* @param context
*/
default void afterCellCreate(CellWriteHandlerContext context) {
afterCellCreate(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getCell(),
context.getHeadData(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after the cell is created
*
@ -44,6 +66,18 @@ public interface CellWriteHandler extends WriteHandler {
default void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
Head head, Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after the cell data is converted
*
* @param context
*/
default void afterCellDataConverted(CellWriteHandlerContext context) {
WriteCellData<?> writeCellData = CollectionUtils.isNotEmpty(context.getCellDataList()) ? context
.getCellDataList().get(0) : null;
afterCellDataConverted(context.getWriteSheetHolder(), context.getWriteTableHolder(), writeCellData,
context.getCell(), context.getHeadData(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after the cell data is converted
*
@ -56,7 +90,17 @@ public interface CellWriteHandler extends WriteHandler {
* @param isHead It will always be false when fill data.
*/
default void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
CellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {}
WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after all operations on the cell have been completed
*
* @param context
*/
default void afterCellDispose(CellWriteHandlerContext context) {
afterCellDispose(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getCellDataList(),
context.getCell(), context.getHeadData(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after all operations on the cell have been completed
@ -70,5 +114,5 @@ public interface CellWriteHandler extends WriteHandler {
* @param isHead It will always be false when fill data.
*/
default void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<CellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {}
List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {}
}

17
src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java

@ -5,12 +5,16 @@ import java.util.List;
import com.alibaba.excel.write.handler.impl.DefaultRowWriteHandler;
import com.alibaba.excel.write.handler.impl.DimensionWorkbookWriteHandler;
import com.alibaba.excel.write.handler.impl.FillDataFormatCellWriteHandler;
import com.alibaba.excel.write.handler.impl.FillStyleCellWriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
/**
* Load default handler
@ -24,6 +28,7 @@ public class DefaultWriteHandlerLoader {
static {
DEFAULT_WRITE_HANDLER_LIST.add(new DimensionWorkbookWriteHandler());
DEFAULT_WRITE_HANDLER_LIST.add(new DefaultRowWriteHandler());
DEFAULT_WRITE_HANDLER_LIST.add(new FillStyleCellWriteHandler());
}
/**
@ -35,7 +40,16 @@ public class DefaultWriteHandlerLoader {
List<WriteHandler> handlerList = new ArrayList<>();
if (useDefaultStyle) {
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setWrapped(true);
headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
headWriteCellStyle.setLocked(true);
headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
headWriteCellStyle.setBorderTop(BorderStyle.THIN);
headWriteCellStyle.setBorderBottom(BorderStyle.THIN);
headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
headWriteCellStyle.setBorderRight(BorderStyle.THIN);
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontName("宋体");
headWriteFont.setFontHeightInPoints((short)14);
@ -44,7 +58,6 @@ public class DefaultWriteHandlerLoader {
handlerList.add(new HorizontalCellStyleStrategy(headWriteCellStyle, new ArrayList<>()));
}
handlerList.addAll(DEFAULT_WRITE_HANDLER_LIST);
handlerList.add(new FillDataFormatCellWriteHandler());
return handlerList;
}

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

@ -1,5 +1,6 @@
package com.alibaba.excel.write.handler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
@ -12,6 +13,16 @@ import org.apache.poi.ss.usermodel.Row;
*/
public interface RowWriteHandler extends WriteHandler {
/**
* Called before create the row
*
* @param context
*/
default void beforeRowCreate(RowWriteHandlerContext context) {
beforeRowCreate(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getRowIndex(),
context.getRelativeRowIndex(), context.getHead());
}
/**
* Called before create the row
*
@ -24,6 +35,16 @@ public interface RowWriteHandler extends WriteHandler {
default void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex,
Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after the row is created
*
* @param context
*/
default void afterRowCreate(RowWriteHandlerContext context) {
afterRowCreate(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getRow(),
context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after the row is created
*
@ -36,6 +57,16 @@ public interface RowWriteHandler extends WriteHandler {
default void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after all operations on the row have been completed.This method is not called when fill the data.
*
* @param context
*/
default void afterRowDispose(RowWriteHandlerContext context) {
afterRowDispose(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getRow(),
context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after all operations on the row have been completed.This method is not called when fill the data.
*

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

@ -1,5 +1,6 @@
package com.alibaba.excel.write.handler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
@ -10,6 +11,15 @@ import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
*/
public interface SheetWriteHandler extends WriteHandler {
/**
* Called before create the sheet
*
* @param context
*/
default void beforeSheetCreate(SheetWriteHandlerContext context) {
beforeSheetCreate(context.getWriteWorkbookHolder(), context.getWriteSheetHolder());
}
/**
* Called before create the sheet
*
@ -18,6 +28,15 @@ public interface SheetWriteHandler extends WriteHandler {
*/
default void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {}
/**
* Called after the sheet is created
*
* @param context
*/
default void afterSheetCreate(SheetWriteHandlerContext context) {
afterSheetCreate(context.getWriteWorkbookHolder(), context.getWriteSheetHolder());
}
/**
* Called after the sheet is created
*

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

@ -1,5 +1,6 @@
package com.alibaba.excel.write.handler;
import com.alibaba.excel.write.handler.context.WorkbookWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/**
@ -9,11 +10,29 @@ import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
*/
public interface WorkbookWriteHandler extends WriteHandler {
/**
* Called before create the workbook
*
* @param context
*/
default void beforeWorkbookCreate(WorkbookWriteHandlerContext context) {
beforeWorkbookCreate();
}
/**
* Called before create the workbook
*/
default void beforeWorkbookCreate() {}
/**
* Called after the workbook is created
*
* @param context
*/
default void afterWorkbookCreate(WorkbookWriteHandlerContext context) {
afterWorkbookCreate(context.getWriteWorkbookHolder());
}
/**
* Called after the workbook is created
*
@ -21,6 +40,15 @@ public interface WorkbookWriteHandler extends WriteHandler {
*/
default void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) {}
/**
* Called after all operations on the workbook have been completed
*
* @param context
*/
default void afterWorkbookDispose(WorkbookWriteHandlerContext context) {
afterWorkbookDispose(context.getWriteWorkbookHolder());
}
/**
* Called after all operations on the workbook have been completed
*

69
src/main/java/com/alibaba/excel/write/handler/context/CellWriteHandlerContext.java

@ -0,0 +1,69 @@
package com.alibaba.excel.write.handler.context;
import java.util.List;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
* cell context
*
* @author Jiaju Zhuang
*/
@Data
@AllArgsConstructor
public class CellWriteHandlerContext {
/**
* write context
*/
private WriteContext writeContext;
/**
* workbook
*/
private WriteWorkbookHolder writeWorkbookHolder;
/**
* sheet
*/
private WriteSheetHolder writeSheetHolder;
/**
* table .Nullable.It is null without using table writes.
*/
private WriteTableHolder writeTableHolder;
/**
* row
*/
private Row row;
/**
* cell
*/
private Cell cell;
/**
* index
*/
private Integer columnIndex;
/**
* Nullable.It is null in the case of fill data.
*/
private Integer relativeRowIndex;
/**
* Nullable.It is null in the case of fill data.
*/
private Head headData;
/**
* Nullable.It is null in the case of add header.There may be several when fill the data.
*/
private List<WriteCellData<?>> cellDataList;
/**
* Nullable.It is null in the case of fill data.
*/
private Boolean head;
}

52
src/main/java/com/alibaba/excel/write/handler/context/RowWriteHandlerContext.java

@ -0,0 +1,52 @@
package com.alibaba.excel.write.handler.context;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.poi.ss.usermodel.Row;
/**
* row context
*
* @author Jiaju Zhuang
*/
@Data
@AllArgsConstructor
public class RowWriteHandlerContext {
/**
* write context
*/
private WriteContext writeContext;
/**
* workbook
*/
private WriteWorkbookHolder writeWorkbookHolder;
/**
* sheet
*/
private WriteSheetHolder writeSheetHolder;
/**
* table .Nullable.It is null without using table writes.
*/
private WriteTableHolder writeTableHolder;
/**
* row index
*/
private Integer rowIndex;
/**
* row
*/
private Row row;
/**
* Nullable.It is null in the case of fill data.
*/
private Integer relativeRowIndex;
/**
* Nullable.It is null in the case of fill data.
*/
private Boolean head;
}

30
src/main/java/com/alibaba/excel/write/handler/context/SheetWriteHandlerContext.java

@ -0,0 +1,30 @@
package com.alibaba.excel.write.handler.context;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* sheet context
*
* @author Jiaju Zhuang
*/
@Data
@AllArgsConstructor
public class SheetWriteHandlerContext {
/**
* write context
*/
private WriteContext writeContext;
/**
* workbook
*/
private WriteWorkbookHolder writeWorkbookHolder;
/**
* sheet
*/
private WriteSheetHolder writeSheetHolder;
}

25
src/main/java/com/alibaba/excel/write/handler/context/WorkbookWriteHandlerContext.java

@ -0,0 +1,25 @@
package com.alibaba.excel.write.handler.context;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* workbook context
*
* @author Jiaju Zhuang
*/
@Data
@AllArgsConstructor
public class WorkbookWriteHandlerContext {
/**
* write context
*/
private WriteContext writeContext;
/**
* workbook
*/
private WriteWorkbookHolder writeWorkbookHolder;
}

11
src/main/java/com/alibaba/excel/write/handler/impl/DefaultRowWriteHandler.java

@ -1,11 +1,9 @@
package com.alibaba.excel.write.handler.impl;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
/**
* Default row handler.
@ -14,9 +12,10 @@ import org.apache.poi.ss.usermodel.Row;
*/
@Slf4j
public class DefaultRowWriteHandler implements RowWriteHandler {
@Override
public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {
writeSheetHolder.setLastRowIndex(row.getRowNum());
public void afterRowDispose(RowWriteHandlerContext context) {
context.getWriteSheetHolder().setLastRowIndex(context.getRowIndex());
}
}

76
src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java

@ -1,76 +0,0 @@
package com.alibaba.excel.write.handler.impl;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.alibaba.excel.constant.OrderConstant;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.event.Order;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Workbook;
/**
* fill cell style.
*
* @author Jiaju Zhuang
*/
@Slf4j
public class FillDataFormatCellWriteHandler implements CellWriteHandler, Order {
private final Set<CellStyle> cellStyleSet = new HashSet<>();
private CellStyle defaultDateCellStyle;
@Override
public int order() {
return OrderConstant.FILL_DATA_FORMAT;
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<CellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if (CollectionUtils.isEmpty(cellDataList) || cellDataList.size() > 1) {
return;
}
CellData<?> cellData = cellDataList.get(0);
CellStyle cellStyle = cell.getCellStyle();
if (cellStyle == null || StyleUtil.isDefaultStyle(cellStyle)) {
if (cellData.getType() == CellDataTypeEnum.DATE) {
cell.setCellStyle(getDefaultDateCellStyle(writeSheetHolder));
}
return;
}
if (cellStyleSet.contains(cellStyle)) {
return;
}
if (cellData.getDataFormat() != null && cellData.getDataFormat() >= 0) {
cellStyle.setDataFormat(cellData.getDataFormat());
}
cellStyleSet.add(cellStyle);
}
private CellStyle getDefaultDateCellStyle(WriteSheetHolder writeSheetHolder) {
if (defaultDateCellStyle != null) {
return defaultDateCellStyle;
}
Workbook workbook = writeSheetHolder.getParentWriteWorkbookHolder().getWorkbook();
defaultDateCellStyle = workbook.createCellStyle();
DataFormat dataFormat = workbook.createDataFormat();
defaultDateCellStyle.setDataFormat(dataFormat.getFormat(DateUtils.defaultDateFormat));
return defaultDateCellStyle;
}
}

43
src/main/java/com/alibaba/excel/write/handler/impl/FillStyleCellWriteHandler.java

@ -0,0 +1,43 @@
package com.alibaba.excel.write.handler.impl;
import java.util.List;
import com.alibaba.excel.constant.OrderConstant;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
/**
* fill cell style.
*
* @author Jiaju Zhuang
*/
@Slf4j
public class FillStyleCellWriteHandler implements CellWriteHandler {
@Override
public int order() {
return OrderConstant.FILL_STYLE;
}
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
List<WriteCellData<?>> cellDataList = context.getCellDataList();
if (CollectionUtils.isEmpty(cellDataList) || cellDataList.size() > 1) {
return;
}
WriteCellData<?> cellData = cellDataList.get(0);
WriteCellStyle writeCellStyle = cellData.getWriteCellStyle();
if (writeCellStyle == null) {
return;
}
WriteWorkbookHolder writeWorkbookHolder = context.getWriteWorkbookHolder();
context.getCell().setCellStyle(writeWorkbookHolder.createCellStyle(writeCellStyle));
}
}

14
src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java

@ -1,12 +1,8 @@
package com.alibaba.excel.write.merge;
import java.util.List;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
@ -19,12 +15,12 @@ import org.apache.poi.ss.usermodel.Sheet;
public abstract class AbstractMergeStrategy implements CellWriteHandler {
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<CellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if (isHead) {
public void afterCellDispose(CellWriteHandlerContext context) {
if (context.getHead()) {
return;
}
merge(writeSheetHolder.getSheet(), cell, head, relativeRowIndex);
merge(context.getWriteSheetHolder().getSheet(), context.getCell(), context.getHeadData(),
context.getRelativeRowIndex());
}
/**

25
src/main/java/com/alibaba/excel/write/metadata/WriteTable.java

@ -1,37 +1,16 @@
package com.alibaba.excel.write.metadata;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import lombok.Data;
/**
* table
*
* @author jipengfei
*/
@Data
public class WriteTable extends WriteBasicParameter {
/**
* Starting from 0
*/
private Integer tableNo;
/**
*
* @deprecated please use{@link HorizontalCellStyleStrategy}
*/
@Deprecated
private TableStyle tableStyle;
public Integer getTableNo() {
return tableNo;
}
public void setTableNo(Integer tableNo) {
this.tableNo = tableNo;
}
public TableStyle getTableStyle() {
return tableStyle;
}
public void setTableStyle(TableStyle tableStyle) {
this.tableStyle = tableStyle;
}
}

178
src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java

@ -9,12 +9,6 @@ import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKeyBuild;
import com.alibaba.excel.converters.DefaultConverterLoader;
@ -22,7 +16,6 @@ import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.event.Order;
import com.alibaba.excel.metadata.AbstractHolder;
import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.property.LoopMergeProperty;
import com.alibaba.excel.metadata.property.OnceAbsoluteMergeProperty;
@ -36,16 +29,16 @@ import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import com.alibaba.excel.write.metadata.WriteBasicParameter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.property.ExcelWriteHeadProperty;
import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractHeadColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
/**
* Write holder configuration
*
@ -182,9 +175,6 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ
// Initialization property
this.excelWriteHeadProperty = new ExcelWriteHeadProperty(this, getClazz(), getHead(), convertAllField);
// Compatible with old code
compatibleOldCode(writeBasicParameter);
// Set writeHandlerMap
List<WriteHandler> handlerList = new ArrayList<WriteHandler>();
@ -220,77 +210,6 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ
}
}
/**
* Compatible with old code
*/
@Deprecated
private void compatibleOldCode(WriteBasicParameter writeBasicParameter) {
switch (holderType()) {
case SHEET:
compatibleOldCodeCreateRowCellStyleStrategy(writeBasicParameter,
((WriteSheet) writeBasicParameter).getTableStyle());
compatibleOldCodeCreateHeadColumnWidthStyleStrategy(writeBasicParameter,
((WriteSheet) writeBasicParameter).getColumnWidthMap());
return;
case TABLE:
compatibleOldCodeCreateRowCellStyleStrategy(writeBasicParameter,
((WriteTable) writeBasicParameter).getTableStyle());
return;
default:
}
}
@Deprecated
private void compatibleOldCodeCreateRowCellStyleStrategy(WriteBasicParameter writeBasicParameter,
TableStyle tableStyle) {
if (tableStyle == null) {
return;
}
if (writeBasicParameter.getCustomWriteHandlerList() == null) {
writeBasicParameter.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
writeBasicParameter.getCustomWriteHandlerList()
.add(new HorizontalCellStyleStrategy(
buildWriteCellStyle(tableStyle.getTableHeadFont(), tableStyle.getTableHeadBackGroundColor()),
buildWriteCellStyle(tableStyle.getTableContentFont(), tableStyle.getTableContentBackGroundColor())));
}
@Deprecated
private WriteCellStyle buildWriteCellStyle(Font font, IndexedColors indexedColors) {
WriteCellStyle writeCellStyle = new WriteCellStyle();
if (indexedColors != null) {
writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
writeCellStyle.setFillForegroundColor(indexedColors.getIndex());
}
if (font != null) {
WriteFont writeFont = new WriteFont();
writeFont.setFontName(font.getFontName());
writeFont.setFontHeightInPoints(font.getFontHeightInPoints());
writeFont.setBold(font.isBold());
writeCellStyle.setWriteFont(writeFont);
}
return writeCellStyle;
}
@Deprecated
private void compatibleOldCodeCreateHeadColumnWidthStyleStrategy(WriteBasicParameter writeBasicParameter,
final Map<Integer, Integer> columnWidthMap) {
if (columnWidthMap == null || columnWidthMap.isEmpty()) {
return;
}
if (writeBasicParameter.getCustomWriteHandlerList() == null) {
writeBasicParameter.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
writeBasicParameter.getCustomWriteHandlerList().add(new AbstractHeadColumnWidthStyleStrategy() {
@Override
protected Integer columnWidth(Head head, Integer columnIndex) {
if (columnWidthMap.containsKey(head.getColumnIndex())) {
return columnWidthMap.get(head.getColumnIndex()) / 256;
}
return 20;
}
});
}
protected void initAnnotationConfig(List<WriteHandler> handlerList, WriteBasicParameter writeBasicParameter) {
if (!HeadKindEnum.CLASS.equals(getExcelWriteHeadProperty().getHeadKind())) {
@ -483,95 +402,6 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ
return false;
}
public Boolean getNeedHead() {
return needHead;
}
public void setNeedHead(Boolean needHead) {
this.needHead = needHead;
}
public Map<Class<? extends WriteHandler>, List<WriteHandler>> getWriteHandlerMap() {
return writeHandlerMap;
}
public void setWriteHandlerMap(Map<Class<? extends WriteHandler>, List<WriteHandler>> writeHandlerMap) {
this.writeHandlerMap = writeHandlerMap;
}
public Map<Class<? extends WriteHandler>, List<WriteHandler>> getOwnWriteHandlerMap() {
return ownWriteHandlerMap;
}
public void setOwnWriteHandlerMap(
Map<Class<? extends WriteHandler>, List<WriteHandler>> ownWriteHandlerMap) {
this.ownWriteHandlerMap = ownWriteHandlerMap;
}
public ExcelWriteHeadProperty getExcelWriteHeadProperty() {
return excelWriteHeadProperty;
}
public void setExcelWriteHeadProperty(ExcelWriteHeadProperty excelWriteHeadProperty) {
this.excelWriteHeadProperty = excelWriteHeadProperty;
}
public Integer getRelativeHeadRowIndex() {
return relativeHeadRowIndex;
}
public void setRelativeHeadRowIndex(Integer relativeHeadRowIndex) {
this.relativeHeadRowIndex = relativeHeadRowIndex;
}
public Boolean getUseDefaultStyle() {
return useDefaultStyle;
}
public void setUseDefaultStyle(Boolean useDefaultStyle) {
this.useDefaultStyle = useDefaultStyle;
}
public Boolean getAutomaticMergeHead() {
return automaticMergeHead;
}
public void setAutomaticMergeHead(Boolean automaticMergeHead) {
this.automaticMergeHead = automaticMergeHead;
}
public Collection<Integer> getExcludeColumnIndexes() {
return excludeColumnIndexes;
}
public void setExcludeColumnIndexes(Collection<Integer> excludeColumnIndexes) {
this.excludeColumnIndexes = excludeColumnIndexes;
}
public Collection<String> getExcludeColumnFieldNames() {
return excludeColumnFieldNames;
}
public void setExcludeColumnFieldNames(Collection<String> excludeColumnFieldNames) {
this.excludeColumnFieldNames = excludeColumnFieldNames;
}
public Collection<Integer> getIncludeColumnIndexes() {
return includeColumnIndexes;
}
public void setIncludeColumnIndexes(Collection<Integer> includeColumnIndexes) {
this.includeColumnIndexes = includeColumnIndexes;
}
public Collection<String> getIncludeColumnFieldNames() {
return includeColumnFieldNames;
}
public void setIncludeColumnFieldNames(Collection<String> includeColumnFieldNames) {
this.includeColumnFieldNames = includeColumnFieldNames;
}
@Override
public ExcelWriteHeadProperty excelWriteHeadProperty() {
return getExcelWriteHeadProperty();

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

@ -10,7 +10,6 @@ import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.excel.constant.BuiltinFormats;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.data.DataFormatData;
@ -18,14 +17,15 @@ import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.IoUtils;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.metadata.WriteWorkbook;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
@ -120,10 +120,19 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
* Excel is also written in the event of an exception being thrown.The default false.
*/
private Boolean writeExcelOnException;
/**
* Used to cell style.
*/
private Map<WriteCellStyle, CellStyle> cellStyleMap;
/**
* Used to font.
*/
private Map<WriteFont, Font> fontMap;
/**
* Used to cache data Format.
* Used to data format.
*/
private Map<String, DataFormatData> dataFormatCache;
private Map<DataFormatData, Short> dataFormatMap;
public WriteWorkbookHolder(WriteWorkbook writeWorkbook) {
super(writeWorkbook, null, writeWorkbook.getConvertAllFiled());
@ -178,7 +187,9 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
} else {
this.writeExcelOnException = writeWorkbook.getWriteExcelOnException();
}
this.dataFormatCache = MapUtils.newHashMap();
this.cellStyleMap = MapUtils.newHashMap();
this.fontMap= MapUtils.newHashMap();
this.dataFormatMap=MapUtils.newHashMap();
}
private void copyTemplate() throws IOException {
@ -206,22 +217,52 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
}
/**
* Get a data format.
* create a cell style.
*
* @param writeCellStyle
* @return
*/
public CellStyle createCellStyle(WriteCellStyle writeCellStyle) {
CellStyle cellStyle = cellStyleMap.get(writeCellStyle);
if (cellStyle != null) {
return cellStyle;
}
cellStyle = StyleUtil.buildCellStyle(workbook, writeCellStyle);
cellStyle.setDataFormat(createDataFormat(writeCellStyle.getDataFormatData()));
cellStyle.setFont(createFont(writeCellStyle.getWriteFont()));
cellStyleMap.put(writeCellStyle, cellStyle);
return cellStyle;
}
/**
* create a font.
*
* @param format
* @param writeFont
* @return
*/
public DataFormatData getDataFormat(String format) {
if (StringUtils.isEmpty(format)) {
return BuiltinFormats.GENERAL;
public Font createFont(WriteFont writeFont) {
Font font = fontMap.get(writeFont);
if (font != null) {
return font;
}
DataFormatData dataFormat = dataFormatCache.get(format);
font = StyleUtil.buildFont(workbook, writeFont);
fontMap.put(writeFont, font);
return font;
}
/**
* create a data format.
*
* @param dataFormatData
* @return
*/
public Short createDataFormat(DataFormatData dataFormatData) {
Short dataFormat = dataFormatMap.get(dataFormatData);
if (dataFormat != null) {
return dataFormat;
}
DataFormat dataFormatCreate = workbook.createDataFormat();
dataFormat = dataFormatCreate.getFormat(format);
dataFormatCache.put(format,dataFormat);
dataFormat = StyleUtil.buildDataFormat(workbook, dataFormatData);
dataFormatMap.put(dataFormatData, dataFormat);
return dataFormat;
}

11
src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java

@ -1,7 +1,6 @@
package com.alibaba.excel.write.metadata.style;
import com.alibaba.excel.constant.BuiltinFormats;
import com.alibaba.excel.metadata.DataFormat;
import com.alibaba.excel.metadata.data.DataFormatData;
import com.alibaba.excel.metadata.property.FontProperty;
import com.alibaba.excel.metadata.property.StyleProperty;
@ -53,7 +52,6 @@ public class WriteCellStyle {
/**
* Set whether the text should be wrapped. Setting this flag to <code>true</code> make all content visible within a
* cell by displaying it on multiple lines
*
*/
private Boolean wrapped;
/**
@ -101,7 +99,6 @@ public class WriteCellStyle {
* Set the color to use for the right border
*
* @see IndexedColors
*
*/
private Short rightBorderColor;
@ -109,14 +106,12 @@ public class WriteCellStyle {
* Set the color to use for the top border
*
* @see IndexedColors
*
*/
private Short topBorderColor;
/**
* Set the color to use for the bottom border
*
* @see IndexedColors
*
*/
private Short bottomBorderColor;
/**
@ -130,7 +125,6 @@ public class WriteCellStyle {
* Set the background fill color.
*
* @see IndexedColors
*
*/
private Short fillBackgroundColor;
@ -138,7 +132,6 @@ public class WriteCellStyle {
* Set the foreground fill color <i>Note: Ensure Foreground color is set prior to background color.</i>
*
* @see IndexedColors
*
*/
private Short fillForegroundColor;
/**
@ -152,9 +145,7 @@ public class WriteCellStyle {
}
WriteCellStyle writeCellStyle = new WriteCellStyle();
if (styleProperty != null) {
if (styleProperty.getDataFormat() >= 0) {
writeCellStyle.setDataFormat(styleProperty.getDataFormat());
}
writeCellStyle.setDataFormatData(styleProperty.getDataFormatData());
writeCellStyle.setHidden(styleProperty.getHidden());
writeCellStyle.setLocked(styleProperty.getLocked());
writeCellStyle.setQuotePrefix(styleProperty.getQuotePrefix());

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

@ -1,71 +1,43 @@
package com.alibaba.excel.write.style;
import java.util.List;
import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.constant.OrderConstant;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
/**
* Cell style strategy
*
* @author Jiaju Zhuang
*/
public abstract class AbstractCellStyleStrategy implements CellWriteHandler, WorkbookWriteHandler, NotRepeatExecutor {
boolean hasInitialized = false;
public abstract class AbstractCellStyleStrategy implements CellWriteHandler {
@Override
public String uniqueValue() {
return "CellStyleStrategy";
public int order() {
return OrderConstant.DEFINE_STYLE;
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<CellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if (isHead == null) {
public void afterCellDispose(CellWriteHandlerContext context) {
if (context.getHead() == null) {
return;
}
if (isHead) {
setHeadCellStyle(writeSheetHolder, writeTableHolder, cell, head, relativeRowIndex);
if (context.getHead()) {
setHeadCellStyle(context);
} else {
setContentCellStyle(writeSheetHolder, writeTableHolder, cell, head, relativeRowIndex);
setContentCellStyle(context);
}
}
@Override
public void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) {
initCellStyle(writeWorkbookHolder.getWorkbook());
hasInitialized = true;
}
/**
* Initialization cell style
*
* @param workbook
*/
protected abstract void initCellStyle(Workbook workbook);
/**
* Sets the cell style of header
*
* @param writeSheetHolder
* @param writeTableHolder
* @param cell
* @param head
* @param relativeRowIndex
* @param context
*/
protected void setHeadCellStyle(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
Cell cell, Head head, Integer relativeRowIndex) {
setHeadCellStyle(cell, head, relativeRowIndex);
protected void setHeadCellStyle(CellWriteHandlerContext context) {
setHeadCellStyle(context.getCell(), context.getHeadData(), context.getRelativeRowIndex());
}
/**
@ -82,13 +54,10 @@ public abstract class AbstractCellStyleStrategy implements CellWriteHandler, Wor
/**
* Sets the cell style of content
*
* @param cell
* @param head
* @param relativeRowIndex
* @param context
*/
protected void setContentCellStyle(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
Cell cell, Head head, Integer relativeRowIndex) {
setContentCellStyle(cell, head, relativeRowIndex);
protected void setContentCellStyle(CellWriteHandlerContext context) {
setContentCellStyle(context.getCell(), context.getHeadData(), context.getRelativeRowIndex());
}
/**

93
src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java

@ -1,17 +1,13 @@
package com.alibaba.excel.write.style;
import java.util.Map;
import java.util.List;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.commons.collections4.CollectionUtils;
/**
* Use the same style for the column
@ -20,77 +16,32 @@ import org.apache.poi.ss.usermodel.Workbook;
*/
public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyleStrategy {
private Workbook workbook;
private final Map<Integer, Map<Integer, Map<Integer, CellStyle>>> headCellStyleCache = MapUtils.newHashMap();
private final Map<Integer, Map<Integer, Map<Integer, CellStyle>>> contentCellStyleCache = MapUtils.newHashMap();
@Override
protected void initCellStyle(Workbook workbook) {
this.workbook = workbook;
}
@Override
protected void setHeadCellStyle(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
Head head, Integer relativeRowIndex) {
if (head == null) {
return;
}
Map<Integer, CellStyle> styleMap = getStyleMap(headCellStyleCache, writeSheetHolder, writeTableHolder);
int columnIndex = head.getColumnIndex();
if (styleMap.containsKey(columnIndex)) {
CellStyle cellStyle = styleMap.get(columnIndex);
if (cellStyle != null) {
cell.setCellStyle(cellStyle);
}
protected void setHeadCellStyle(CellWriteHandlerContext context) {
if (!continueProcessing(context)) {
return;
}
WriteCellStyle headCellStyle = headCellStyle(head);
if (headCellStyle == null) {
styleMap.put(columnIndex, StyleUtil.buildHeadCellStyle(workbook, null));
} else {
CellStyle cellStyle = StyleUtil.buildHeadCellStyle(workbook, headCellStyle);
styleMap.put(columnIndex, cellStyle);
cell.setCellStyle(cellStyle);
}
WriteCellData<?> cellData = context.getCellDataList().get(0);
cellData.setWriteCellStyle(headCellStyle(context.getHeadData()));
}
@Override
protected void setContentCellStyle(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
Head head, Integer relativeRowIndex) {
if (head == null) {
protected void setContentCellStyle(CellWriteHandlerContext context) {
if (!continueProcessing(context)) {
return;
}
Map<Integer, CellStyle> styleMap = getStyleMap(contentCellStyleCache, writeSheetHolder, writeTableHolder);
int columnIndex = head.getColumnIndex();
if (styleMap.containsKey(columnIndex)) {
CellStyle cellStyle = styleMap.get(columnIndex);
if (cellStyle != null) {
cell.setCellStyle(cellStyle);
}
return;
}
WriteCellStyle contentCellStyle = contentCellStyle(cell, head, relativeRowIndex);
if (contentCellStyle == null) {
styleMap.put(columnIndex, StyleUtil.buildContentCellStyle(workbook, null));
} else {
CellStyle cellStyle = StyleUtil.buildContentCellStyle(workbook, contentCellStyle);
styleMap.put(columnIndex, cellStyle);
cell.setCellStyle(cellStyle);
}
WriteCellData<?> cellData = context.getCellDataList().get(0);
cellData.setWriteCellStyle(contentCellStyle(context));
}
/**
* Returns the column width corresponding to each column head.
*
* @param cell
* @param head
* @param relativeRowIndex
* @param context
* @return
*/
protected WriteCellStyle contentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
return contentCellStyle(head);
protected WriteCellStyle contentCellStyle(CellWriteHandlerContext context) {
return contentCellStyle(context.getHeadData());
}
/**
@ -113,15 +64,11 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl
+ "'contentCellStyle(Head head)' must be implemented.");
}
private Map<Integer, CellStyle> getStyleMap(Map<Integer, Map<Integer, Map<Integer, CellStyle>>> cellStyleCache,
WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder) {
Map<Integer, Map<Integer, CellStyle>> tableStyleMap = cellStyleCache.computeIfAbsent(
writeSheetHolder.getSheetNo(), key -> MapUtils.newHashMap());
Integer tableNo = 0;
if (writeTableHolder != null) {
tableNo = writeTableHolder.getTableNo();
protected boolean continueProcessing(CellWriteHandlerContext context) {
List<WriteCellData<?>> cellDataList = context.getCellDataList();
if (CollectionUtils.isEmpty(cellDataList) || cellDataList.size() > 1) {
return false;
}
return tableStyleMap.computeIfAbsent(tableNo, key -> MapUtils.newHashMap());
return context.getHeadData() != null;
}
}

17
src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java

@ -4,10 +4,10 @@ import java.util.List;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
/**
* Use the same style for the row
@ -16,8 +16,8 @@ import org.apache.poi.ss.usermodel.Cell;
*/
public class HorizontalCellStyleStrategy extends AbstractVerticalCellStyleStrategy {
private final WriteCellStyle headWriteCellStyle;
private final List<WriteCellStyle> contentWriteCellStyleList;
private WriteCellStyle headWriteCellStyle;
private List<WriteCellStyle> contentWriteCellStyleList;
public HorizontalCellStyleStrategy(WriteCellStyle headWriteCellStyle,
List<WriteCellStyle> contentWriteCellStyleList) {
@ -27,8 +27,9 @@ public class HorizontalCellStyleStrategy extends AbstractVerticalCellStyleStrate
public HorizontalCellStyleStrategy(WriteCellStyle headWriteCellStyle, WriteCellStyle contentWriteCellStyle) {
this.headWriteCellStyle = headWriteCellStyle;
contentWriteCellStyleList = ListUtils.newArrayList();
contentWriteCellStyleList.add(contentWriteCellStyle);
if (contentWriteCellStyle != null) {
this.contentWriteCellStyleList = ListUtils.newArrayList(contentWriteCellStyle);
}
}
@Override
@ -37,11 +38,11 @@ public class HorizontalCellStyleStrategy extends AbstractVerticalCellStyleStrate
}
@Override
protected WriteCellStyle contentCellStyle(Cell cell, Head head, Integer relativeRowIndex) {
protected WriteCellStyle contentCellStyle(CellWriteHandlerContext context) {
if (CollectionUtils.isEmpty(contentWriteCellStyleList)) {
return new WriteCellStyle();
return null;
}
return contentWriteCellStyleList.get(relativeRowIndex % contentWriteCellStyleList.size());
return contentWriteCellStyleList.get(context.getRelativeRowIndex() % contentWriteCellStyleList.size());
}
}

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

@ -2,12 +2,11 @@ package com.alibaba.excel.write.style.column;
import java.util.List;
import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
@ -16,17 +15,21 @@ import org.apache.poi.ss.usermodel.Cell;
*
* @author Jiaju Zhuang
*/
public abstract class AbstractColumnWidthStyleStrategy implements CellWriteHandler,NotRepeatExecutor {
public abstract class AbstractColumnWidthStyleStrategy implements CellWriteHandler {
@Override
public String uniqueValue() {
return "ColumnWidthStyleStrategy";
public void afterCellDispose(CellWriteHandlerContext context) {
setColumnWidth(context);
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<CellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
setColumnWidth(writeSheetHolder, cellDataList, cell, head, relativeRowIndex, isHead);
/**
* Sets the column width when head create
*
* @param context
*/
protected void setColumnWidth(CellWriteHandlerContext context) {
setColumnWidth(context.getWriteSheetHolder(), context.getCellDataList(), context.getCell(),
context.getHeadData(), context.getRelativeRowIndex(), context.getHead());
}
/**
@ -39,7 +42,9 @@ public abstract class AbstractColumnWidthStyleStrategy implements CellWriteHandl
* @param relativeRowIndex
* @param isHead
*/
protected abstract void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData<?>> cellDataList, Cell cell,
Head head, Integer relativeRowIndex, Boolean isHead);
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell,
Head head, Integer relativeRowIndex, Boolean isHead) {
throw new UnsupportedOperationException("Custom styles must override the setColumnWidth method.");
}
}

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

@ -2,12 +2,12 @@ package com.alibaba.excel.write.style.column;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import org.apache.poi.ss.usermodel.Cell;
/**
* Returns the column width according to each column header
*
@ -16,7 +16,7 @@ import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
public abstract class AbstractHeadColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData<?>> cellDataList, Cell cell, Head head,
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head,
Integer relativeRowIndex, Boolean isHead) {
boolean needSetWidth = relativeRowIndex != null && (isHead || relativeRowIndex == 0);
if (!needSetWidth) {

18
src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java

@ -4,14 +4,15 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
/**
* Take the width of the longest column as the width.
* <p>
@ -24,10 +25,11 @@ public class LongestMatchColumnWidthStyleStrategy extends AbstractColumnWidthSty
private static final int MAX_COLUMN_WIDTH = 255;
private Map<Integer, Map<Integer, Integer>> cache = new HashMap<Integer, Map<Integer, Integer>>(8);
private final Map<Integer, Map<Integer, Integer>> cache = MapUtils.newHashMapWithExpectedSize(8);
@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData<?>> cellDataList, Cell cell, Head head,
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell,
Head head,
Integer relativeRowIndex, Boolean isHead) {
boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
if (!needSetWidth) {
@ -52,11 +54,11 @@ public class LongestMatchColumnWidthStyleStrategy extends AbstractColumnWidthSty
}
}
private Integer dataLength(List<CellData<?>> cellDataList, Cell cell, Boolean isHead) {
private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
if (isHead) {
return cell.getStringCellValue().getBytes().length;
}
CellData cellData = cellDataList.get(0);
WriteCellData<?> cellData = cellDataList.get(0);
CellDataTypeEnum type = cellData.getType();
if (type == null) {
return -1;

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

@ -1,46 +1,25 @@
package com.alibaba.excel.write.style.row;
import org.apache.poi.ss.usermodel.Row;
import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import org.apache.poi.ss.usermodel.Row;
/**
* Set the row height strategy
*
* @author Jiaju Zhuang
*/
public abstract class AbstractRowHeightStyleStrategy implements RowWriteHandler, NotRepeatExecutor {
@Override
public String uniqueValue() {
return "RowHighStyleStrategy";
}
@Override
public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex,
Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {
}
public abstract class AbstractRowHeightStyleStrategy implements RowWriteHandler {
@Override
public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {
if (isHead == null) {
public void afterRowDispose(RowWriteHandlerContext context) {
if (context.getHead() == null) {
return;
}
if (isHead) {
setHeadColumnHeight(row, relativeRowIndex);
if (context.getHead()) {
setHeadColumnHeight(context.getRow(), context.getRelativeRowIndex());
} else {
setContentColumnHeight(row, relativeRowIndex);
setContentColumnHeight(context.getRow(), context.getRelativeRowIndex());
}
}

10
src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java

@ -3,14 +3,14 @@ package com.alibaba.easyexcel.test.core.celldata;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jiaju Zhuang
*/
@ -31,7 +31,7 @@ public class CellDataDataListener extends AnalysisEventListener<CellDataData> {
Assert.assertEquals(cellDataData.getDate().getStringValue(), "2020年01月01日");
Assert.assertEquals((long)cellDataData.getInteger1().getData(), 2L);
Assert.assertEquals((long)cellDataData.getInteger2(), 2L);
Assert.assertEquals(cellDataData.getFormulaValue().getFormulaValue(), "B2+C2");
Assert.assertEquals(cellDataData.getFormulaValue().getFormulaData().getFormulaValue(), "B2+C2");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

22
src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java

@ -5,19 +5,20 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.FormulaData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.DateUtils;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
*
* @author Jiaju Zhuang
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ -50,15 +51,16 @@ public class CellDataDataTest {
private List<CellDataData> data() throws Exception {
List<CellDataData> list = new ArrayList<CellDataData>();
CellDataData cellDataData = new CellDataData();
cellDataData.setDate(new CellData<>(DateUtils.parseDate("2020-01-01 01:01:01")));
cellDataData.setDate(new WriteCellData<>(DateUtils.parseDate("2020-01-01 01:01:01")));
CellData<Integer> integer1 = new CellData<Integer>();
integer1.setType(CellDataTypeEnum.NUMBER);
integer1.setNumberValue(BigDecimal.valueOf(2L));
cellDataData.setInteger1(integer1);
cellDataData.setInteger2(2);
CellData formulaValue = new CellData();
formulaValue.setFormula(Boolean.TRUE);
formulaValue.setFormulaValue("B2+C2");
WriteCellData<?> formulaValue = new WriteCellData<>();
FormulaData formulaData = new FormulaData();
formulaValue.setFormulaData(formulaData);
formulaData.setFormulaValue("B2+C2");
cellDataData.setFormulaValue(formulaValue);
list.add(cellDataData);
return list;

16
src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityData.java

@ -1,16 +0,0 @@
package com.alibaba.easyexcel.test.core.compatibility;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author Jiaju Zhuang
*/
@Data
public class CompatibilityData extends BaseRowModel {
@ExcelProperty("字符串标题0")
private String string0;
@ExcelProperty("字符串标题1")
private String string1;
}

34
src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataListener.java

@ -1,34 +0,0 @@
package com.alibaba.easyexcel.test.core.compatibility;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.easyexcel.test.core.annotation.AnnotationDataListener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
/**
* @author Jiaju Zhuang
*/
public class CompatibilityDataListener extends AnalysisEventListener<List<String>> {
private static final Logger LOGGER = LoggerFactory.getLogger(AnnotationDataListener.class);
List<List<String>> list = new ArrayList<List<String>>();
@Override
public void invoke(List<String> data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 10);
List<String> data = list.get(0);
Assert.assertEquals(data.get(0), "字符串00");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

157
src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java

@ -1,157 +0,0 @@
package com.alibaba.easyexcel.test.core.compatibility;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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.IndexedColors;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.parameter.AnalysisParam;
import com.alibaba.excel.parameter.GenerateParam;
/**
*
* @author Jiaju Zhuang
*/
public class CompatibilityDataTest {
private static File file07;
private static File file03;
@BeforeClass
public static void init() {
file07 = TestFileUtil.createNewFile("compatibility07.xlsx");
file03 = TestFileUtil.createNewFile("compatibility03.xls");
}
@Test
public void t01ReadAndWrite07() throws Exception {
readAndWrite(file07);
}
@Test
public void t02ReadAndWrite03() throws Exception {
readAndWrite(file03);
}
private void readAndWrite(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
GenerateParam generateParam = new GenerateParam("", null, out);
generateParam.setSheetName("");
generateParam.setOutputStream(out);
generateParam.setClazz(null);
ExcelWriter writer = new ExcelWriter(generateParam);
// sheet1 width,string head,string data
Sheet sheet1 = new Sheet(1, 3);
sheet1.setSheetName("第一个sheet");
Map columnWidth = new HashMap();
columnWidth.put(0, 10000);
columnWidth.put(1, 50000);
sheet1.setColumnWidthMap(columnWidth);
sheet1.setHead(head());
writer.write1(listData(), sheet1);
// sheet2 style,class head
Sheet sheet2 = new Sheet(2, 3, CompatibilityData.class, "第二个sheet", null);
sheet2.setStartRow(5);
sheet2.setTableStyle(style());
writer.write(data(), sheet2);
writer.merge(8, 8, 0, 1);
// sheet3 table
Sheet sheet3 = new Sheet(3, 0);
sheet3.setSheetName("第三个sheet");
Table table1 = new Table(1);
table1.setHead(head());
writer.write1(listData(), sheet3, table1);
Table table2 = new Table(2);
table2.setClazz(CompatibilityData.class);
writer.write(data(), sheet3, table2);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
List<Object> data = EasyExcel.read(inputStream, new Sheet(1, 1));
Assert.assertEquals(data.size(), 1);
List<String> dataList = (List<String>)data.get(0);
Assert.assertEquals(dataList.get(0), "字符串00");
inputStream.close();
inputStream = new FileInputStream(file);
AnalysisParam param = new AnalysisParam(inputStream, null, new Object());
param.setIn(inputStream);
param.setExcelTypeEnum(null);
param.setCustomContent(null);
ExcelReader excelReader = new ExcelReader(param, new CompatibilityDataListener());
excelReader.read(new Sheet(2, 6));
Assert.assertEquals(excelReader.getSheets().size(), 3);
Assert.assertTrue(excelReader.getAnalysisContext() != null);
inputStream.close();
}
private List<List<String>> head() {
List<List<String>> list = new ArrayList<List<String>>();
List<String> head0 = new ArrayList<String>();
head0.add("字符串标题0");
List<String> head1 = new ArrayList<String>();
head1.add("字符串标题1");
list.add(head0);
list.add(head1);
return list;
}
private List<List<Object>> listData() {
List<List<Object>> list = new ArrayList<List<Object>>();
List<Object> data0 = new ArrayList<Object>();
data0.add("字符串00");
data0.add(11);
list.add(data0);
return list;
}
private List<CompatibilityData> data() {
List<CompatibilityData> list = new ArrayList<CompatibilityData>();
for (int i = 0; i < 10; i++) {
CompatibilityData data = new CompatibilityData();
data.setString0("字符串0" + i);
data.setString1("字符串1" + i);
list.add(data);
}
return list;
}
public TableStyle style() {
TableStyle tableStyle = new TableStyle();
Font headFont = new Font();
headFont.setBold(true);
headFont.setFontHeightInPoints((short)22);
headFont.setFontName("楷体");
tableStyle.setTableHeadFont(headFont);
tableStyle.setTableHeadBackGroundColor(IndexedColors.BLUE);
Font contentFont = new Font();
contentFont.setBold(true);
contentFont.setFontHeightInPoints((short)22);
contentFont.setFontName("黑体");
tableStyle.setTableContentFont(contentFont);
tableStyle.setTableContentBackGroundColor(IndexedColors.GREEN);
return tableStyle;
}
}

142
src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java

@ -1,142 +0,0 @@
package com.alibaba.easyexcel.test.core.compatibility;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
/**
*
* @author Jiaju Zhuang
*/
public class CompatibilityParameterDataTest {
private static File file;
@BeforeClass
public static void init() {
file = TestFileUtil.createNewFile("compatibilityParameter.xlsx");
}
@Test
public void t01ReadAndWrite() throws Exception {
readAndWrite1(file);
readAndWrite2(file);
readAndWrite3(file);
readAndWrite4(file);
readAndWrite5(file);
readAndWrite6(file);
}
private void readAndWrite1(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = EasyExcel.getWriter(out);
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(data(), sheet1);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
EasyExcel.readBySax(inputStream, new Sheet(1, 0), new CompatibilityDataListener());
inputStream.close();
}
private void readAndWrite2(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = EasyExcel.getWriter(out, null, false);
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(data(), sheet1);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
EasyExcel.readBySax(inputStream, new Sheet(1, 0), new CompatibilityDataListener());
inputStream.close();
}
private void readAndWrite3(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = new ExcelWriter(out, null);
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(data(), sheet1);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
ExcelReader excelReader = new ExcelReader(inputStream, null, null, new CompatibilityDataListener());
excelReader.read(new Sheet(1, 0));
inputStream.close();
}
private void readAndWrite4(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = new ExcelWriter(null, out, null, null);
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(data(), sheet1, null);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
ExcelReader excelReader = new ExcelReader(inputStream, null, new CompatibilityDataListener());
excelReader.read(new Sheet(1, 0));
inputStream.close();
}
private void readAndWrite5(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = EasyExcel.getWriterWithTemp(null, out, null, false);
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(data(), sheet1, null);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
ExcelReader excelReader = EasyExcel.getReader(inputStream, new CompatibilityDataListener());
excelReader.read(new Sheet(1, 0));
inputStream.close();
}
private void readAndWrite6(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = EasyExcel.getWriterWithTempAndHandler(null, out, null, false, null);
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(data(), sheet1, null);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
ExcelReader excelReader = EasyExcel.getReader(inputStream, new CompatibilityDataListener());
excelReader.read(new Sheet(1, 0));
inputStream.close();
}
private List<CompatibilityData> data() {
List<CompatibilityData> list = new ArrayList<CompatibilityData>();
for (int i = 0; i < 10; i++) {
CompatibilityData data = new CompatibilityData();
data.setString0("字符串0" + i);
data.setString1("字符串1" + i);
list.add(data);
}
return list;
}
}

12
src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java

@ -1,12 +0,0 @@
package com.alibaba.easyexcel.test.core.compatibility;
import lombok.Data;
/**
* @author Jiaju Zhuang
*/
@Data
public class CompatibilityReadData extends BaseRowModel {
private String string0;
private String string1;
}

4
src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java

@ -4,7 +4,7 @@ import java.math.BigDecimal;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import lombok.Data;
@ -34,5 +34,5 @@ public class ConverterData {
@ExcelProperty("字符串")
private String string;
@ExcelProperty("自定义")
private CellData<?> cellData;
private WriteCellData<?> cellData;
}

14
src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java

@ -6,17 +6,17 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.FileUtils;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
*
* @author Jiaju Zhuang
@ -110,7 +110,7 @@ public class ConverterDataTest {
converterData.setDoubleData(1.0);
converterData.setFloatData((float)1.0);
converterData.setString("测试");
converterData.setCellData(new CellData("自定义"));
converterData.setCellData(new WriteCellData<>("自定义"));
list.add(converterData);
return list;
}

17
src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java

@ -2,12 +2,8 @@ package com.alibaba.easyexcel.test.core.handler;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.junit.Assert;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler;
@ -16,9 +12,11 @@ import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.junit.Assert;
/**
*
*
* @author JiaJu Zhuang
**/
public class WriteHandler implements WorkbookWriteHandler, SheetWriteHandler, RowWriteHandler, CellWriteHandler {
@ -36,7 +34,6 @@ public class WriteHandler implements WorkbookWriteHandler, SheetWriteHandler, Ro
private long afterWorkbookCreate = 0L;
private long afterWorkbookDispose = 0L;
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
@ -80,7 +77,7 @@ public class WriteHandler implements WorkbookWriteHandler, SheetWriteHandler, Ro
@Override
public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
CellData cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
Assert.assertEquals(1L, beforeCellCreate);
Assert.assertEquals(1L, afterCellCreate);
Assert.assertEquals(0L, afterCellDataConverted);
@ -98,7 +95,7 @@ public class WriteHandler implements WorkbookWriteHandler, SheetWriteHandler, Ro
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<CellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if (isHead) {
Assert.assertEquals(1L, beforeCellCreate);
Assert.assertEquals(1L, afterCellCreate);

28
src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java

@ -4,20 +4,10 @@ import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.DataFormatData;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
@ -27,8 +17,18 @@ import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
*
* @author Jiaju Zhuang
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ -60,7 +60,9 @@ public class StyleDataTest {
protected WriteCellStyle headCellStyle(Head head) {
WriteCellStyle writeCellStyle = new WriteCellStyle();
writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
writeCellStyle.setDataFormat((short)0);
DataFormatData dataFormatData = new DataFormatData();
dataFormatData.setIndex((short)0);
writeCellStyle.setDataFormatData(dataFormatData);
writeCellStyle.setHidden(false);
writeCellStyle.setLocked(true);
writeCellStyle.setQuotePrefix(true);

11
src/test/java/com/alibaba/easyexcel/test/demo/read/CustomStringStringConverter.java

@ -2,8 +2,9 @@ package com.alibaba.easyexcel.test.demo.read;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
@ -13,7 +14,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
*/
public class CustomStringStringConverter implements Converter<String> {
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return String.class;
}
@ -34,7 +35,7 @@ public class CustomStringStringConverter implements Converter<String> {
* @return
*/
@Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return "自定义:" + cellData.getStringValue();
}
@ -51,9 +52,9 @@ public class CustomStringStringConverter implements Converter<String> {
* @return
*/
@Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return new CellData(value);
return new WriteCellData<>(value);
}
}

14
src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java

@ -2,6 +2,12 @@ package com.alibaba.easyexcel.test.demo.write;
import java.util.List;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
@ -9,12 +15,6 @@ import org.apache.poi.ss.usermodel.Hyperlink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
/**
* 自定义拦截器对第一行第一列的头超链接到:https://github.com/alibaba/easyexcel
*
@ -26,7 +26,7 @@ public class CustomCellWriteHandler implements CellWriteHandler {
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<CellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
// 这里可以对cell进行任何操作
LOGGER.info("第{}行,第{}列写入完成。", cell.getRowIndex(), cell.getColumnIndex());
if (isHead && cell.getColumnIndex() == 0) {

29
src/test/java/com/alibaba/easyexcel/test/demo/write/CustomStringStringConverter.java

@ -2,8 +2,9 @@ package com.alibaba.easyexcel.test.demo.write;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
@ -13,7 +14,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
*/
public class CustomStringStringConverter implements Converter<String> {
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return String.class;
}
@ -25,16 +26,13 @@ public class CustomStringStringConverter implements Converter<String> {
/**
* 这里是读的时候会调用 不用管
*
* @param cellData
* NotNull
* @param contentProperty
* Nullable
* @param globalConfiguration
* NotNull
* @param cellData NotNull
* @param contentProperty Nullable
* @param globalConfiguration NotNull
* @return
*/
@Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return cellData.getStringValue();
}
@ -42,18 +40,15 @@ public class CustomStringStringConverter implements Converter<String> {
/**
* 这里是写的时候会调用 不用管
*
* @param value
* NotNull
* @param contentProperty
* Nullable
* @param globalConfiguration
* NotNull
* @param value NotNull
* @param contentProperty Nullable
* @param globalConfiguration NotNull
* @return
*/
@Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return new CellData("自定义:" + value);
return new WriteCellData<>("自定义:" + value);
}
}

7
src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatData.java

@ -1,6 +1,7 @@
package com.alibaba.easyexcel.test.temp.dataformat;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import lombok.Data;
@ -11,6 +12,6 @@ import lombok.Data;
**/
@Data
public class DataFormatData {
private CellData<String> date;
private CellData<String> num;
private ReadCellData<String> date;
private ReadCellData<String> num;
}

20
src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatTest.java

@ -9,6 +9,12 @@ import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import com.alibaba.easyexcel.test.core.dataformat.DateFormatData;
import com.alibaba.easyexcel.test.temp.Lock2Test;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
@ -21,12 +27,6 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.easyexcel.test.core.dataformat.DateFormatData;
import com.alibaba.easyexcel.test.temp.Lock2Test;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
/**
* 格式测试
*
@ -44,9 +44,9 @@ public class DataFormatTest {
EasyExcel.read(file, DataFormatData.class, null).sheet().headRowNumber(0).doReadSync();
LOGGER.info("数据:{}", list.size());
for (DataFormatData data : list) {
Short dataFormat = data.getDate().getDataFormat();
Short dataFormat = data.getDate().getDataFormatData().getIndex();
String dataFormatString = data.getDate().getDataFormatString();
String dataFormatString = data.getDate().getFormulaData().getFormulaValue();
if (dataFormat == null || dataFormatString == null) {
@ -67,9 +67,9 @@ public class DataFormatTest {
EasyExcel.read(file, DataFormatData.class, null).sheet().headRowNumber(0).doReadSync();
LOGGER.info("数据:{}", list.size());
for (DataFormatData data : list) {
Short dataFormat = data.getDate().getDataFormat();
Short dataFormat = data.getDate().getDataFormatData().getIndex();
String dataFormatString = data.getDate().getDataFormatString();
String dataFormatString = data.getDate().getFormulaData().getFormulaValue();
if (dataFormat == null || dataFormatString == null) {

18
src/test/java/com/alibaba/easyexcel/test/temp/read/HeadReadTest.java

@ -1,19 +1,16 @@
package com.alibaba.easyexcel.test.temp.read;
import java.io.File;
import java.io.FileInputStream;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.cache.Ehcache;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.cache.Ehcache;
import com.alibaba.excel.support.ExcelTypeEnum;
/**
* 临时测试
*
@ -22,13 +19,6 @@ import com.alibaba.excel.support.ExcelTypeEnum;
@Ignore
public class HeadReadTest {
private static final Logger LOGGER = LoggerFactory.getLogger(HeadReadTest.class);
@Test
public void testread() throws Exception {
FileInputStream fileInputStream = new FileInputStream("D://test/t1.xlsx");
ExcelReader excelReader = new ExcelReader(fileInputStream, ExcelTypeEnum.XLSX, null, new TestListener());
excelReader.read();
}
@Test
public void test() throws Exception {

4
src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java

@ -1,7 +1,7 @@
package com.alibaba.easyexcel.test.temp.simple;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
@ -21,7 +21,7 @@ public class WriteCellHandler implements CellWriteHandler {
@Override
public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
CellData cellData, Cell cell, Head head, Integer integer, Boolean isHead) {
WriteCellData<?> cellData, Cell cell, Head head, Integer integer, Boolean isHead) {
if (!isHead) {
CreationHelper createHelper = writeSheetHolder.getSheet().getWorkbook().getCreationHelper();

Loading…
Cancel
Save