From 59f90ba782f3fe2f0be5edcc6bb173d2dbb1f3d5 Mon Sep 17 00:00:00 2001 From: dota17 Date: Fri, 27 Mar 2020 17:55:03 +0800 Subject: [PATCH 001/129] Add new feature: use annotation to set image position --- .../annotation/write/style/ImagePosition.java | 61 ++++++++ .../BoxingByteArrayImageConverter.java | 10 +- .../bytearray/ByteArrayImageConverter.java | 14 +- .../converters/file/FileImageConverter.java | 10 +- .../InputStreamImageConverter.java | 10 +- .../string/StringImageConverter.java | 10 +- .../com/alibaba/excel/metadata/CellData.java | 45 +++++- .../property/ImagePositionProperty.java | 132 ++++++++++++++++++ .../executor/AbstractExcelWriteExecutor.java | 30 ++-- .../demo/write/ImageDataWithAnnotation.java | 42 ++++++ .../easyexcel/test/demo/write/WriteTest.java | 35 ++++- 11 files changed, 379 insertions(+), 20 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/annotation/write/style/ImagePosition.java create mode 100644 src/main/java/com/alibaba/excel/metadata/property/ImagePositionProperty.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDataWithAnnotation.java diff --git a/src/main/java/com/alibaba/excel/annotation/write/style/ImagePosition.java b/src/main/java/com/alibaba/excel/annotation/write/style/ImagePosition.java new file mode 100644 index 00000000..8a401122 --- /dev/null +++ b/src/main/java/com/alibaba/excel/annotation/write/style/ImagePosition.java @@ -0,0 +1,61 @@ +package com.alibaba.excel.annotation.write.style; + + +import org.apache.poi.ss.usermodel.ClientAnchor; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.annotation.Retention; + +/** + * This annotation is used to set the position of a picture. + * See {@link ClientAnchor} + */ + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +@Inherited +public @interface ImagePosition { + + /** + * The x coordinate within the first cell. + */ + int dx1(); + + /** + * The y coordinate within the first cell. + */ + int dy1(); + + /** + * The x coordinate within the second cell. + */ + int dx2(); + + /** + * The y coordinate within the second cell + */ + int dy2(); + + /** + * 0-based column of the first cell. + */ + short col1(); + + /** + * 0-based row of the first cell. + */ + int row1(); + + /** + * 0-based column of the second cell. + */ + short col2(); + + /** + * 0-based row of the second cell. + */ + int row2(); +} diff --git a/src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java b/src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java index c083601b..2840df73 100644 --- a/src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java @@ -1,5 +1,8 @@ package com.alibaba.excel.converters.bytearray; +import java.lang.annotation.Annotation; + +import com.alibaba.excel.annotation.write.style.ImagePosition; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; @@ -35,7 +38,12 @@ public class BoxingByteArrayImageConverter implements Converter { for (int i = 0; i < value.length; i++) { byteValue[i] = value[i]; } - return new CellData(byteValue); + ImagePosition imagePosition = contentProperty.getField().getAnnotation(ImagePosition.class); + if (imagePosition != null) { + return new CellData(byteValue, imagePosition); + } else { + return new CellData(byteValue); + } } } diff --git a/src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java b/src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java index 991999d1..b186c374 100644 --- a/src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java @@ -1,5 +1,8 @@ package com.alibaba.excel.converters.bytearray; +import java.lang.annotation.Annotation; + +import com.alibaba.excel.annotation.write.style.ImagePosition; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; @@ -24,14 +27,19 @@ public class ByteArrayImageConverter implements Converter { @Override public byte[] convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { + GlobalConfiguration globalConfiguration) { throw new UnsupportedOperationException("Cannot convert images to byte arrays"); } @Override public CellData convertToExcelData(byte[] value, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - return new CellData(value); + GlobalConfiguration globalConfiguration) { + ImagePosition imagePosition = contentProperty.getField().getAnnotation(ImagePosition.class); + if (imagePosition != null) { + return new CellData(value, imagePosition); + } else { + return new CellData(value); + } } } diff --git a/src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java b/src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java index 10522154..2e974378 100644 --- a/src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java @@ -2,7 +2,7 @@ package com.alibaba.excel.converters.file; import java.io.File; import java.io.IOException; - +import com.alibaba.excel.annotation.write.style.ImagePosition; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; @@ -35,7 +35,11 @@ public class FileImageConverter implements Converter { @Override public CellData convertToExcelData(File value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { - return new CellData(FileUtils.readFileToByteArray(value)); + ImagePosition imagePosition = contentProperty.getField().getAnnotation(ImagePosition.class); + if (imagePosition != null) { + return new CellData(FileUtils.readFileToByteArray(value), imagePosition); + } else { + return new CellData(FileUtils.readFileToByteArray(value)); + } } - } diff --git a/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java b/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java index abc2fe68..1e752a54 100644 --- a/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java @@ -2,12 +2,15 @@ package com.alibaba.excel.converters.inputstream; import java.io.IOException; import java.io.InputStream; +import java.lang.annotation.Annotation; +import com.alibaba.excel.annotation.write.style.ImagePosition; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; +import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.util.IoUtils; /** @@ -35,7 +38,12 @@ public class InputStreamImageConverter implements Converter { @Override public CellData convertToExcelData(InputStream value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { - return new CellData(IoUtils.toByteArray(value)); + ImagePosition imagePosition = contentProperty.getField().getAnnotation(ImagePosition.class); + if (imagePosition != null) { + return new CellData(IoUtils.toByteArray(value), imagePosition); + } else { + return new CellData(IoUtils.toByteArray(value)); + } } } diff --git a/src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java b/src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java index 931d4fa9..c15d9a0e 100644 --- a/src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java @@ -2,13 +2,16 @@ package com.alibaba.excel.converters.string; import java.io.File; import java.io.IOException; +import java.lang.annotation.Annotation; +import com.alibaba.excel.annotation.write.style.ImagePosition; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.util.FileUtils; +import com.alibaba.excel.util.IoUtils; /** * String and image converter @@ -35,7 +38,12 @@ public class StringImageConverter implements Converter { @Override public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { - return new CellData(FileUtils.readFileToByteArray(new File(value))); + ImagePosition imagePosition = contentProperty.getField().getAnnotation(ImagePosition.class); + if (imagePosition != null) { + return new CellData(FileUtils.readFileToByteArray(new File(value)), imagePosition); + } else { + return new CellData(FileUtils.readFileToByteArray(new File(value))); + } } } diff --git a/src/main/java/com/alibaba/excel/metadata/CellData.java b/src/main/java/com/alibaba/excel/metadata/CellData.java index 2124e103..cdce6ad2 100644 --- a/src/main/java/com/alibaba/excel/metadata/CellData.java +++ b/src/main/java/com/alibaba/excel/metadata/CellData.java @@ -1,8 +1,9 @@ package com.alibaba.excel.metadata; import java.math.BigDecimal; - +import com.alibaba.excel.annotation.write.style.ImagePosition; import com.alibaba.excel.enums.CellDataTypeEnum; +import com.alibaba.excel.metadata.property.ImagePositionProperty; import com.alibaba.excel.util.StringUtils; /** @@ -29,6 +30,16 @@ public class CellData extends AbstractCell { private Boolean formula; private String formulaValue; private byte[] imageValue; + + /** + * Keep the information of image position in annotation. + */ + private ImagePositionProperty imagePositionProperty; + + /** + * It will be set true when using annotation to set the image's position. + */ + private Boolean useImagePositionProperty = false; /** * The number formatting.Currently only supported when reading */ @@ -50,6 +61,8 @@ public class CellData extends AbstractCell { this.formula = other.formula; this.formulaValue = other.formulaValue; this.imageValue = other.imageValue; + this.imagePositionProperty = other.imagePositionProperty; + this.useImagePositionProperty = other.useImagePositionProperty; this.dataFormat = other.dataFormat; this.dataFormatString = other.dataFormatString; this.data = other.data; @@ -101,6 +114,20 @@ public class CellData extends AbstractCell { this.formula = Boolean.FALSE; } + public CellData(byte[] imageValue, ImagePosition imagePosition) { + if (imageValue == null) { + throw new IllegalArgumentException("ImageValue can not be null"); + } + if (imagePosition == null) { + throw new IllegalArgumentException("ImagePosition can not be null"); + } + this.type = CellDataTypeEnum.IMAGE; + this.imageValue = imageValue; + this.imagePositionProperty = ImagePositionProperty.build(imagePosition); + this.useImagePositionProperty = true; + this.formula = Boolean.FALSE; + } + public CellData(Boolean booleanValue) { if (booleanValue == null) { throw new IllegalArgumentException("BooleanValue can not be null"); @@ -174,6 +201,22 @@ public class CellData extends AbstractCell { this.imageValue = imageValue; } + public ImagePositionProperty getImagePositionProperty() { + return imagePositionProperty; + } + + public void setImagePositionProperty(ImagePositionProperty imagePositionProperty) { + this.imagePositionProperty = imagePositionProperty; + } + + public Boolean getUseImagePositionProperty() { + return useImagePositionProperty; + } + + public void setUseImagePositionProperty(Boolean useImagePositionProperty) { + this.useImagePositionProperty = useImagePositionProperty; + } + public Integer getDataFormat() { return dataFormat; } diff --git a/src/main/java/com/alibaba/excel/metadata/property/ImagePositionProperty.java b/src/main/java/com/alibaba/excel/metadata/property/ImagePositionProperty.java new file mode 100644 index 00000000..b5eff3af --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/property/ImagePositionProperty.java @@ -0,0 +1,132 @@ +package com.alibaba.excel.metadata.property; + +import com.alibaba.excel.annotation.write.style.ImagePosition; + +/** + * Keep the information of image position from an annotation. + */ +public class ImagePositionProperty { + + /** + * The x coordinate within the first cell. + */ + private int dx1; + + /** + * The y coordinate within the first cell. + */ + private int dy1; + + /** + * The x coordinate within the second cell. + */ + private int dx2; + + /** + * The y coordinate within the second cell + */ + private int dy2; + + /** + * 0-based column of the first cell. + */ + private short col1; + + /** + * 0-based row of the first cell. + */ + private int row1; + + /** + * 0-based column of the second cell. + */ + private short col2; + + /** + * 0-based row of the second cell. + */ + private int row2; + + public static ImagePositionProperty build(ImagePosition imagePosition) { + if (imagePosition == null) { + return null; + } + return new ImagePositionProperty(imagePosition.dx1(), imagePosition.dy1(), imagePosition.dx2(), + imagePosition.dy2(), imagePosition.col1(), imagePosition.row1(), imagePosition.col2(), imagePosition.row2()); + } + + public ImagePositionProperty(int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2) { + this.dx1 = dx1; + this.dy1 = dy1; + this.dx2 = dx2; + this.dy2 = dy2; + this.col1 = col1; + this.row1 = row1; + this.col2 = col2; + this.row2 = row2; + } + + public int getDx1() { + return dx1; + } + + public void setDx1(int dx1) { + this.dx1 = dx1; + } + + public int getDy1() { + return dy1; + } + + public void setDy1(int dy1) { + this.dy1 = dy1; + } + + public int getDx2() { + return dx2; + } + + public void setDx2(int dx2) { + this.dx2 = dx2; + } + + public int getDy2() { + return dy2; + } + + public void setDy2(int dy2) { + this.dy2 = dy2; + } + + public short getCol1() { + return col1; + } + + public void setCol1(short col1) { + this.col1 = col1; + } + + public int getRow1() { + return row1; + } + + public void setRow1(int row1) { + this.row1 = row1; + } + + public short getCol2() { + return col2; + } + + public void setCol2(short col2) { + this.col2 = col2; + } + + public int getRow2() { + return row2; + } + + public void setRow2(int row2) { + this.row2 = row2; + } +} diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index 4eb115c5..eb094d7f 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -136,15 +136,27 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { } CreationHelper helper = sheet.getWorkbook().getCreationHelper(); ClientAnchor anchor = helper.createClientAnchor(); - 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); + 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); } } diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDataWithAnnotation.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDataWithAnnotation.java new file mode 100644 index 00000000..d76715f6 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDataWithAnnotation.java @@ -0,0 +1,42 @@ +package com.alibaba.easyexcel.test.demo.write; + +import java.io.File; +import java.io.InputStream; +import java.net.URL; + +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.annotation.write.style.ColumnWidth; +import com.alibaba.excel.annotation.write.style.ContentRowHeight; +import com.alibaba.excel.annotation.write.style.ImagePosition; +import com.alibaba.excel.converters.string.StringImageConverter; + +import lombok.Data; + +/** + * 图片导出类 + * + */ +@Data +@ContentRowHeight(100) +@ColumnWidth(100 / 8) +public class ImageDataWithAnnotation { + @ImagePosition(dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0, col1 = 0, row1 = 3, col2 = 1, row2 = 4) + private File file; + @ImagePosition(dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0, col1 = 0, row1 = 1, col2 = 2, row2 = 2) + private InputStream inputStream; + /** + * 如果string类型 必须指定转换器,string默认转换成string + */ + @ExcelProperty(converter = StringImageConverter.class) + @ImagePosition(dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0, col1 = 2, row1 = 1, col2 = 3, row2 = 3) + private String string; + @ImagePosition(dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0, col1 = 3, row1 = 1, col2 = 4, row2 = 5) + private byte[] byteArray; + /** + * 根据url导出 + * + * @since 2.1.1 + */ + @ImagePosition(dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0, col1 = 4, row1 = 1, col2 = 5, row2 = 2) + private URL url; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java index c54ceb7f..49621979 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java @@ -225,7 +225,7 @@ public class WriteTest { inputStream = FileUtils.openInputStream(new File(imagePath)); imageData.setInputStream(inputStream); imageData.setUrl(new URL( - "https://raw.githubusercontent.com/alibaba/easyexcel/master/src/test/resources/converter/img.jpg")); + "https://raw.githubusercontent.com/alibaba/easyexcel/master/src/test/resources/converter/img.jpg")); EasyExcel.write(fileName, ImageData.class).sheet().doWrite(list); } finally { if (inputStream != null) { @@ -234,6 +234,39 @@ public class WriteTest { } } + /** + * 使用注解设置图片位置,然后导出 + *

+ * 1. 创建excel对应的实体对象 参照{@link ImageData} + *

+ * 2. 直接写即可 + */ + @Test + public void imageWriteWithAnnotation() throws Exception { + String fileName = TestFileUtil.getPath() + "imageWriteWithAnnotation" + System.currentTimeMillis() + ".xlsx"; + // 如果使用流 记得关闭 + InputStream inputStream = null; + try { + List list = new ArrayList(); + ImageDataWithAnnotation imageData = new ImageDataWithAnnotation(); + list.add(imageData); + String imagePath = TestFileUtil.getPath() + "converter" + File.separator + "img.jpg"; + // 放入五种类型的图片 实际使用只要选一种即可 + imageData.setByteArray(FileUtils.readFileToByteArray(new File(imagePath))); + imageData.setFile(new File(imagePath)); + imageData.setString(imagePath); + inputStream = FileUtils.openInputStream(new File(imagePath)); + imageData.setInputStream(inputStream); + imageData.setUrl(new URL( + "https://raw.githubusercontent.com/alibaba/easyexcel/master/src/test/resources/converter/img.jpg")); + EasyExcel.write(fileName, ImageDataWithAnnotation.class).sheet().doWrite(list); + } finally { + if (inputStream != null) { + inputStream.close(); + } + } + } + /** * 根据模板写入 *

From 8074ac28f992b593674793cbd03e5b95f77209a7 Mon Sep 17 00:00:00 2001 From: dota17 Date: Fri, 10 Apr 2020 17:32:10 +0800 Subject: [PATCH 002/129] Make columns sort by parameter order and modified some typos --- .../metadata/property/ExcelHeadProperty.java | 101 +++++++++++++++--- .../AbstractExcelWriterParameterBuilder.java | 4 +- .../write/metadata/WriteBasicParameter.java | 20 ++-- .../metadata/holder/AbstractWriteHolder.java | 40 +++---- 4 files changed, 117 insertions(+), 48 deletions(-) diff --git a/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java b/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java index 34109adc..c3454755 100644 --- a/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java +++ b/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java @@ -2,6 +2,7 @@ package com.alibaba.excel.metadata.property; import java.lang.reflect.Field; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -24,6 +25,8 @@ import com.alibaba.excel.util.ClassUtils; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.write.metadata.holder.AbstractWriteHolder; +import javafx.util.Pair; + /** * Define the header attribute of excel * @@ -61,7 +64,7 @@ public class ExcelHeadProperty { */ private Map ignoreMap; - public ExcelHeadProperty(Holder holder, Class headClazz, List> head, Boolean convertAllFiled) { + public ExcelHeadProperty(Holder holder, Class headClazz, List> head, Boolean convertAllField) { this.headClazz = headClazz; headMap = new TreeMap(); contentPropertyMap = new TreeMap(); @@ -73,7 +76,7 @@ public class ExcelHeadProperty { int headIndex = 0; for (int i = 0; i < head.size(); i++) { if (holder instanceof AbstractWriteHolder) { - if (((AbstractWriteHolder)holder).ignore(null, i)) { + if (((AbstractWriteHolder) holder).ignore(null, i)) { continue; } } @@ -84,7 +87,7 @@ public class ExcelHeadProperty { headKind = HeadKindEnum.STRING; } // convert headClazz to head - initColumnProperties(holder, convertAllFiled); + initColumnProperties(holder, convertAllField); initHeadRowNumber(); if (LOGGER.isDebugEnabled()) { @@ -112,32 +115,98 @@ public class ExcelHeadProperty { } } - private void initColumnProperties(Holder holder, Boolean convertAllFiled) { + private void initColumnProperties(Holder holder, Boolean convertAllField) { if (headClazz == null) { return; } // Declared fields List defaultFieldList = new ArrayList(); - Map customFiledMap = new TreeMap(); - ClassUtils.declaredFields(headClazz, defaultFieldList, customFiledMap, ignoreMap, convertAllFiled); + Map customFieldMap = new TreeMap(); + ClassUtils.declaredFields(headClazz, defaultFieldList, customFieldMap, ignoreMap, convertAllField); + List> exportFieldBoolPairsList = new ArrayList>(); int index = 0; + while (customFieldMap.containsKey(index)) { + Field field = customFieldMap.get(index); + Pair fieldBooleanPair = new Pair(field, Boolean.TRUE); + exportFieldBoolPairsList.add(fieldBooleanPair); + index++; + } for (Field field : defaultFieldList) { - while (customFiledMap.containsKey(index)) { - Field customFiled = customFiledMap.get(index); - customFiledMap.remove(index); - if (!initOneColumnProperty(holder, index, customFiled, Boolean.TRUE)) { - index++; + Pair fieldBoolPair = new Pair(field, Boolean.FALSE); + exportFieldBoolPairsList.add(fieldBoolPair); + } + + sortExportColumnFields(holder, exportFieldBoolPairsList); + initColumnProperties(holder, exportFieldBoolPairsList); + + for (Map.Entry entry : customFieldMap.entrySet()) { + initOneColumnProperty(holder, entry.getKey(), entry.getValue(), Boolean.TRUE); + } + headKind = HeadKindEnum.CLASS; + } + + /** + * Give the field and flag pair list and arrange them in the specified order according to the user's settings. + * The field is what the user want to export to excel, the flag indicates whether the order of the field in excel is + * specified. + * + * @param holder Write holder which keeps the parameters of a sheet. + * @param exportFieldBoolPairList Keep all the fields and the flag(which indicate whether the field order is specified) + * of the head class except the ignored. It will be modified after this function is called. + */ + private void sortExportColumnFields(Holder holder, List> exportFieldBoolPairList) { + if (holder instanceof AbstractWriteHolder) { + Collection includeColumnFieldNames = ((AbstractWriteHolder) holder).getIncludeColumnFieldNames(); + if (includeColumnFieldNames != null) { + Map> exportFieldMap = new TreeMap>(); + List includeColumnFieldNameList = new ArrayList(includeColumnFieldNames); + for (Pair fieldBoolPair : exportFieldBoolPairList) { + if (includeColumnFieldNameList.contains(fieldBoolPair.getKey().getName())) { + exportFieldMap.put(fieldBoolPair.getKey().getName(), fieldBoolPair); + } } + exportFieldBoolPairList.clear(); + for (String fieldName : includeColumnFieldNameList) { + exportFieldBoolPairList.add(exportFieldMap.get(fieldName)); + } + return; + } + + Collection includeColumnIndexes = ((AbstractWriteHolder) holder).getIncludeColumnIndexes(); + if (includeColumnIndexes != null) { + List> tempFieldsList = new ArrayList>(); + for (Integer includeColumnIndex : includeColumnIndexes) { + tempFieldsList.add(exportFieldBoolPairList.get(includeColumnIndex)); + } + exportFieldBoolPairList.clear(); + exportFieldBoolPairList.addAll(tempFieldsList); + return; } - if (!initOneColumnProperty(holder, index, field, Boolean.FALSE)) { + + int index = 0; + for (Pair fieldBoolPair : exportFieldBoolPairList) { + if (((AbstractWriteHolder) holder).ignore(fieldBoolPair.getKey().getName(), index)) { + exportFieldBoolPairList.remove(fieldBoolPair); + } index++; } } - for (Map.Entry entry : customFiledMap.entrySet()) { - initOneColumnProperty(holder, entry.getKey(), entry.getValue(), Boolean.TRUE); + } + + /** + * Initialize column properties. + * + * @param holder Write holder which keeps the parameters of a sheet. + * @param exportFieldBoolPairList Keep the fields which will be exported to excel and the flag which indicate whether + * the field order in excel is specified. + */ + private void initColumnProperties(Holder holder, List> exportFieldBoolPairList) { + int index = 0; + for (Pair fieldBoolPair : exportFieldBoolPairList) { + initOneColumnProperty(holder, index, fieldBoolPair.getKey(), fieldBoolPair.getValue()); + index++; } - headKind = HeadKindEnum.CLASS; } /** @@ -151,7 +220,7 @@ public class ExcelHeadProperty { */ private boolean initOneColumnProperty(Holder holder, int index, Field field, Boolean forceIndex) { if (holder instanceof AbstractWriteHolder) { - if (((AbstractWriteHolder)holder).ignore(field.getName(), index)) { + if (((AbstractWriteHolder) holder).ignore(field.getName(), index)) { return true; } } diff --git a/src/main/java/com/alibaba/excel/write/builder/AbstractExcelWriterParameterBuilder.java b/src/main/java/com/alibaba/excel/write/builder/AbstractExcelWriterParameterBuilder.java index d44c0ad0..751ae5cd 100644 --- a/src/main/java/com/alibaba/excel/write/builder/AbstractExcelWriterParameterBuilder.java +++ b/src/main/java/com/alibaba/excel/write/builder/AbstractExcelWriterParameterBuilder.java @@ -81,7 +81,7 @@ public abstract class AbstractExcelWriterParameterBuilder excludeColumnFiledNames) { - parameter().setExcludeColumnFiledNames(excludeColumnFiledNames); + parameter().setExcludeColumnFieldNames(excludeColumnFiledNames); return self(); } @@ -97,7 +97,7 @@ public abstract class AbstractExcelWriterParameterBuilder includeColumnFiledNames) { - parameter().setIncludeColumnFiledNames(includeColumnFiledNames); + parameter().setIncludeColumnFieldNames(includeColumnFiledNames); return self(); } diff --git a/src/main/java/com/alibaba/excel/write/metadata/WriteBasicParameter.java b/src/main/java/com/alibaba/excel/write/metadata/WriteBasicParameter.java index b582576e..e6d2b9f0 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/WriteBasicParameter.java +++ b/src/main/java/com/alibaba/excel/write/metadata/WriteBasicParameter.java @@ -40,7 +40,7 @@ public class WriteBasicParameter extends BasicParameter { /** * Ignore the custom columns. */ - private Collection excludeColumnFiledNames; + private Collection excludeColumnFieldNames; /** * Only output the custom columns. */ @@ -48,7 +48,7 @@ public class WriteBasicParameter extends BasicParameter { /** * Only output the custom columns. */ - private Collection includeColumnFiledNames; + private Collection includeColumnFieldNames; public Integer getRelativeHeadRowIndex() { return relativeHeadRowIndex; @@ -98,12 +98,12 @@ public class WriteBasicParameter extends BasicParameter { this.excludeColumnIndexes = excludeColumnIndexes; } - public Collection getExcludeColumnFiledNames() { - return excludeColumnFiledNames; + public Collection getExcludeColumnFieldNames() { + return excludeColumnFieldNames; } - public void setExcludeColumnFiledNames(Collection excludeColumnFiledNames) { - this.excludeColumnFiledNames = excludeColumnFiledNames; + public void setExcludeColumnFieldNames(Collection excludeColumnFieldNames) { + this.excludeColumnFieldNames = excludeColumnFieldNames; } public Collection getIncludeColumnIndexes() { @@ -114,12 +114,12 @@ public class WriteBasicParameter extends BasicParameter { this.includeColumnIndexes = includeColumnIndexes; } - public Collection getIncludeColumnFiledNames() { - return includeColumnFiledNames; + public Collection getIncludeColumnFieldNames() { + return includeColumnFieldNames; } - public void setIncludeColumnFiledNames(Collection includeColumnFiledNames) { - this.includeColumnFiledNames = includeColumnFiledNames; + public void setIncludeColumnFieldNames(Collection includeColumnFieldNames) { + this.includeColumnFieldNames = includeColumnFieldNames; } } diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java index 00f2ef74..aa7cbc35 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java @@ -82,7 +82,7 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ /** * Ignore the custom columns. */ - private Collection excludeColumnFiledNames; + private Collection excludeColumnFieldNames; /** * Only output the custom columns. */ @@ -90,10 +90,10 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ /** * Only output the custom columns. */ - private Collection includeColumnFiledNames; + private Collection includeColumnFieldNames; public AbstractWriteHolder(WriteBasicParameter writeBasicParameter, AbstractWriteHolder parentAbstractWriteHolder, - Boolean convertAllFiled) { + Boolean convertAllField) { super(writeBasicParameter, parentAbstractWriteHolder); if (writeBasicParameter.getUse1904windowing() == null) { if (parentAbstractWriteHolder == null) { @@ -146,20 +146,20 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ this.automaticMergeHead = writeBasicParameter.getAutomaticMergeHead(); } - if (writeBasicParameter.getExcludeColumnFiledNames() == null && parentAbstractWriteHolder != null) { - this.excludeColumnFiledNames = parentAbstractWriteHolder.getExcludeColumnFiledNames(); + if (writeBasicParameter.getExcludeColumnFieldNames() == null && parentAbstractWriteHolder != null) { + this.excludeColumnFieldNames = parentAbstractWriteHolder.getExcludeColumnFieldNames(); } else { - this.excludeColumnFiledNames = writeBasicParameter.getExcludeColumnFiledNames(); + this.excludeColumnFieldNames = writeBasicParameter.getExcludeColumnFieldNames(); } if (writeBasicParameter.getExcludeColumnIndexes() == null && parentAbstractWriteHolder != null) { this.excludeColumnIndexes = parentAbstractWriteHolder.getExcludeColumnIndexes(); } else { this.excludeColumnIndexes = writeBasicParameter.getExcludeColumnIndexes(); } - if (writeBasicParameter.getIncludeColumnFiledNames() == null && parentAbstractWriteHolder != null) { - this.includeColumnFiledNames = parentAbstractWriteHolder.getIncludeColumnFiledNames(); + if (writeBasicParameter.getIncludeColumnFieldNames() == null && parentAbstractWriteHolder != null) { + this.includeColumnFieldNames = parentAbstractWriteHolder.getIncludeColumnFieldNames(); } else { - this.includeColumnFiledNames = writeBasicParameter.getIncludeColumnFiledNames(); + this.includeColumnFieldNames = writeBasicParameter.getIncludeColumnFieldNames(); } if (writeBasicParameter.getIncludeColumnIndexes() == null && parentAbstractWriteHolder != null) { this.includeColumnIndexes = parentAbstractWriteHolder.getIncludeColumnIndexes(); @@ -168,7 +168,7 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ } // Initialization property - this.excelWriteHeadProperty = new ExcelWriteHeadProperty(this, getClazz(), getHead(), convertAllFiled); + this.excelWriteHeadProperty = new ExcelWriteHeadProperty(this, getClazz(), getHead(), convertAllField); // Compatible with old code compatibleOldCode(writeBasicParameter); @@ -446,10 +446,10 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ @Override public boolean ignore(String fieldName, Integer columnIndex) { if (fieldName != null) { - if (includeColumnFiledNames != null && !includeColumnFiledNames.contains(fieldName)) { + if (includeColumnFieldNames != null && !includeColumnFieldNames.contains(fieldName)) { return true; } - if (excludeColumnFiledNames != null && excludeColumnFiledNames.contains(fieldName)) { + if (excludeColumnFieldNames != null && excludeColumnFieldNames.contains(fieldName)) { return true; } } @@ -520,12 +520,12 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ this.excludeColumnIndexes = excludeColumnIndexes; } - public Collection getExcludeColumnFiledNames() { - return excludeColumnFiledNames; + public Collection getExcludeColumnFieldNames() { + return excludeColumnFieldNames; } - public void setExcludeColumnFiledNames(Collection excludeColumnFiledNames) { - this.excludeColumnFiledNames = excludeColumnFiledNames; + public void setExcludeColumnFieldNames(Collection excludeColumnFieldNames) { + this.excludeColumnFieldNames = excludeColumnFieldNames; } public Collection getIncludeColumnIndexes() { @@ -536,12 +536,12 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ this.includeColumnIndexes = includeColumnIndexes; } - public Collection getIncludeColumnFiledNames() { - return includeColumnFiledNames; + public Collection getIncludeColumnFieldNames() { + return includeColumnFieldNames; } - public void setIncludeColumnFiledNames(Collection includeColumnFiledNames) { - this.includeColumnFiledNames = includeColumnFiledNames; + public void setIncludeColumnFieldNames(Collection includeColumnFieldNames) { + this.includeColumnFieldNames = includeColumnFieldNames; } @Override From b1014f1c2182a164773c224e157de1c4345565da Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 16 May 2020 14:45:54 +0800 Subject: [PATCH 003/129] Add author --- easyexcel | 1 + .../excel/metadata/property/ImagePositionProperty.java | 7 +++++-- 2 files changed, 6 insertions(+), 2 deletions(-) create mode 160000 easyexcel diff --git a/easyexcel b/easyexcel new file mode 160000 index 00000000..4076b897 --- /dev/null +++ b/easyexcel @@ -0,0 +1 @@ +Subproject commit 4076b897953b18f9e96c278c6929325e89f2be12 diff --git a/src/main/java/com/alibaba/excel/metadata/property/ImagePositionProperty.java b/src/main/java/com/alibaba/excel/metadata/property/ImagePositionProperty.java index b5eff3af..5bd6fb30 100644 --- a/src/main/java/com/alibaba/excel/metadata/property/ImagePositionProperty.java +++ b/src/main/java/com/alibaba/excel/metadata/property/ImagePositionProperty.java @@ -3,7 +3,9 @@ package com.alibaba.excel.metadata.property; import com.alibaba.excel.annotation.write.style.ImagePosition; /** - * Keep the information of image position from an annotation. + * Keep the image position information from an annotation. + * + * @author Pengliang Zhao */ public class ImagePositionProperty { @@ -52,7 +54,8 @@ public class ImagePositionProperty { return null; } return new ImagePositionProperty(imagePosition.dx1(), imagePosition.dy1(), imagePosition.dx2(), - imagePosition.dy2(), imagePosition.col1(), imagePosition.row1(), imagePosition.col2(), imagePosition.row2()); + imagePosition.dy2(), imagePosition.col1(), imagePosition.row1(), imagePosition.col2(), + imagePosition.row2()); } public ImagePositionProperty(int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2) { From f15b5ce12fce718496e51511cc5afa6c4540fc0e Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 16 May 2020 17:20:13 +0800 Subject: [PATCH 004/129] Use Entry to replace Pair --- .../metadata/property/ExcelHeadProperty.java | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java b/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java index c3454755..2565d563 100644 --- a/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java +++ b/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java @@ -1,6 +1,7 @@ package com.alibaba.excel.metadata.property; import java.lang.reflect.Field; +import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -124,16 +125,16 @@ public class ExcelHeadProperty { Map customFieldMap = new TreeMap(); ClassUtils.declaredFields(headClazz, defaultFieldList, customFieldMap, ignoreMap, convertAllField); - List> exportFieldBoolPairsList = new ArrayList>(); + List> exportFieldBoolPairsList = new ArrayList>(); int index = 0; while (customFieldMap.containsKey(index)) { Field field = customFieldMap.get(index); - Pair fieldBooleanPair = new Pair(field, Boolean.TRUE); + Map.Entry fieldBooleanPair = new AbstractMap.SimpleEntry(field, Boolean.TRUE); exportFieldBoolPairsList.add(fieldBooleanPair); index++; } for (Field field : defaultFieldList) { - Pair fieldBoolPair = new Pair(field, Boolean.FALSE); + Map.Entry fieldBoolPair = new AbstractMap.SimpleEntry(field, Boolean.FALSE); exportFieldBoolPairsList.add(fieldBoolPair); } @@ -155,13 +156,13 @@ public class ExcelHeadProperty { * @param exportFieldBoolPairList Keep all the fields and the flag(which indicate whether the field order is specified) * of the head class except the ignored. It will be modified after this function is called. */ - private void sortExportColumnFields(Holder holder, List> exportFieldBoolPairList) { + private void sortExportColumnFields(Holder holder, List> exportFieldBoolPairList) { if (holder instanceof AbstractWriteHolder) { Collection includeColumnFieldNames = ((AbstractWriteHolder) holder).getIncludeColumnFieldNames(); if (includeColumnFieldNames != null) { - Map> exportFieldMap = new TreeMap>(); + Map> exportFieldMap = new TreeMap>(); List includeColumnFieldNameList = new ArrayList(includeColumnFieldNames); - for (Pair fieldBoolPair : exportFieldBoolPairList) { + for (Map.Entry fieldBoolPair : exportFieldBoolPairList) { if (includeColumnFieldNameList.contains(fieldBoolPair.getKey().getName())) { exportFieldMap.put(fieldBoolPair.getKey().getName(), fieldBoolPair); } @@ -175,7 +176,7 @@ public class ExcelHeadProperty { Collection includeColumnIndexes = ((AbstractWriteHolder) holder).getIncludeColumnIndexes(); if (includeColumnIndexes != null) { - List> tempFieldsList = new ArrayList>(); + List> tempFieldsList = new ArrayList>(); for (Integer includeColumnIndex : includeColumnIndexes) { tempFieldsList.add(exportFieldBoolPairList.get(includeColumnIndex)); } @@ -185,7 +186,7 @@ public class ExcelHeadProperty { } int index = 0; - for (Pair fieldBoolPair : exportFieldBoolPairList) { + for (Map.Entry fieldBoolPair : exportFieldBoolPairList) { if (((AbstractWriteHolder) holder).ignore(fieldBoolPair.getKey().getName(), index)) { exportFieldBoolPairList.remove(fieldBoolPair); } @@ -201,9 +202,9 @@ public class ExcelHeadProperty { * @param exportFieldBoolPairList Keep the fields which will be exported to excel and the flag which indicate whether * the field order in excel is specified. */ - private void initColumnProperties(Holder holder, List> exportFieldBoolPairList) { + private void initColumnProperties(Holder holder, List> exportFieldBoolPairList) { int index = 0; - for (Pair fieldBoolPair : exportFieldBoolPairList) { + for (Map.Entry fieldBoolPair : exportFieldBoolPairList) { initOneColumnProperty(holder, index, fieldBoolPair.getKey(), fieldBoolPair.getValue()); index++; } From 76158a66619940bcd480950e7e62d4d2449e7df5 Mon Sep 17 00:00:00 2001 From: dota17 Date: Sat, 16 May 2020 17:26:41 +0800 Subject: [PATCH 005/129] Remove javafx.util --- .../metadata/property/ExcelHeadProperty.java | 38 ++++++++++--------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java b/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java index 2565d563..e846befc 100644 --- a/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java +++ b/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java @@ -26,8 +26,6 @@ import com.alibaba.excel.util.ClassUtils; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.write.metadata.holder.AbstractWriteHolder; -import javafx.util.Pair; - /** * Define the header attribute of excel * @@ -77,7 +75,7 @@ public class ExcelHeadProperty { int headIndex = 0; for (int i = 0; i < head.size(); i++) { if (holder instanceof AbstractWriteHolder) { - if (((AbstractWriteHolder) holder).ignore(null, i)) { + if (((AbstractWriteHolder)holder).ignore(null, i)) { continue; } } @@ -129,7 +127,8 @@ public class ExcelHeadProperty { int index = 0; while (customFieldMap.containsKey(index)) { Field field = customFieldMap.get(index); - Map.Entry fieldBooleanPair = new AbstractMap.SimpleEntry(field, Boolean.TRUE); + Map.Entry fieldBooleanPair = + new AbstractMap.SimpleEntry(field, Boolean.TRUE); exportFieldBoolPairsList.add(fieldBooleanPair); index++; } @@ -148,19 +147,22 @@ public class ExcelHeadProperty { } /** - * Give the field and flag pair list and arrange them in the specified order according to the user's settings. - * The field is what the user want to export to excel, the flag indicates whether the order of the field in excel is + * Give the field and flag pair list and arrange them in the specified order according to the user's settings. The + * field is what the user want to export to excel, the flag indicates whether the order of the field in excel is * specified. * - * @param holder Write holder which keeps the parameters of a sheet. - * @param exportFieldBoolPairList Keep all the fields and the flag(which indicate whether the field order is specified) - * of the head class except the ignored. It will be modified after this function is called. + * @param holder + * Write holder which keeps the parameters of a sheet. + * @param exportFieldBoolPairList + * Keep all the fields and the flag(which indicate whether the field order is specified) of the head + * class except the ignored. It will be modified after this function is called. */ private void sortExportColumnFields(Holder holder, List> exportFieldBoolPairList) { if (holder instanceof AbstractWriteHolder) { - Collection includeColumnFieldNames = ((AbstractWriteHolder) holder).getIncludeColumnFieldNames(); + Collection includeColumnFieldNames = ((AbstractWriteHolder)holder).getIncludeColumnFieldNames(); if (includeColumnFieldNames != null) { - Map> exportFieldMap = new TreeMap>(); + Map> exportFieldMap = + new TreeMap>(); List includeColumnFieldNameList = new ArrayList(includeColumnFieldNames); for (Map.Entry fieldBoolPair : exportFieldBoolPairList) { if (includeColumnFieldNameList.contains(fieldBoolPair.getKey().getName())) { @@ -174,7 +176,7 @@ public class ExcelHeadProperty { return; } - Collection includeColumnIndexes = ((AbstractWriteHolder) holder).getIncludeColumnIndexes(); + Collection includeColumnIndexes = ((AbstractWriteHolder)holder).getIncludeColumnIndexes(); if (includeColumnIndexes != null) { List> tempFieldsList = new ArrayList>(); for (Integer includeColumnIndex : includeColumnIndexes) { @@ -187,7 +189,7 @@ public class ExcelHeadProperty { int index = 0; for (Map.Entry fieldBoolPair : exportFieldBoolPairList) { - if (((AbstractWriteHolder) holder).ignore(fieldBoolPair.getKey().getName(), index)) { + if (((AbstractWriteHolder)holder).ignore(fieldBoolPair.getKey().getName(), index)) { exportFieldBoolPairList.remove(fieldBoolPair); } index++; @@ -198,9 +200,11 @@ public class ExcelHeadProperty { /** * Initialize column properties. * - * @param holder Write holder which keeps the parameters of a sheet. - * @param exportFieldBoolPairList Keep the fields which will be exported to excel and the flag which indicate whether - * the field order in excel is specified. + * @param holder + * Write holder which keeps the parameters of a sheet. + * @param exportFieldBoolPairList + * Keep the fields which will be exported to excel and the flag which indicate whether the field order in + * excel is specified. */ private void initColumnProperties(Holder holder, List> exportFieldBoolPairList) { int index = 0; @@ -221,7 +225,7 @@ public class ExcelHeadProperty { */ private boolean initOneColumnProperty(Holder holder, int index, Field field, Boolean forceIndex) { if (holder instanceof AbstractWriteHolder) { - if (((AbstractWriteHolder) holder).ignore(field.getName(), index)) { + if (((AbstractWriteHolder)holder).ignore(field.getName(), index)) { return true; } } From 99722a954bda60c07ea44a1ff1cadbe7ec6d08cd Mon Sep 17 00:00:00 2001 From: dota17 Date: Tue, 19 May 2020 10:17:44 +0800 Subject: [PATCH 006/129] Greatly Improve metadata.property coverage --- easyexcel | 1 + .../test/core/style/LoopMergeData.java | 17 ++++ .../core/style/OnceAbsoluteMergeData.java | 19 +++++ .../SimpleVerticalCellStyleStrategy.java | 52 ++++++++++++ .../test/core/style/StyleDataTest.java | 80 +++++++++++++++++++ .../test/core/style/StyleOtherData.java | 20 +++++ 6 files changed, 189 insertions(+) create mode 160000 easyexcel create mode 100644 src/test/java/com/alibaba/easyexcel/test/core/style/LoopMergeData.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/core/style/OnceAbsoluteMergeData.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/core/style/SimpleVerticalCellStyleStrategy.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/core/style/StyleOtherData.java diff --git a/easyexcel b/easyexcel new file mode 160000 index 00000000..4076b897 --- /dev/null +++ b/easyexcel @@ -0,0 +1 @@ +Subproject commit 4076b897953b18f9e96c278c6929325e89f2be12 diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/LoopMergeData.java b/src/test/java/com/alibaba/easyexcel/test/core/style/LoopMergeData.java new file mode 100644 index 00000000..77c5363f --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/core/style/LoopMergeData.java @@ -0,0 +1,17 @@ +package com.alibaba.easyexcel.test.core.style; + +import com.alibaba.excel.annotation.ExcelProperty; +import lombok.Data; + +/** + * @author Pengliang Zhao + */ +@Data +public class LoopMergeData { + @ExcelProperty(value = "洗漱种类", index = 0) + private String category; + @ExcelProperty(value = "毛巾名称", index = 1) + private String towel; + @ExcelProperty(value = "毛巾尺寸", index = 2) + private String size; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/OnceAbsoluteMergeData.java b/src/test/java/com/alibaba/easyexcel/test/core/style/OnceAbsoluteMergeData.java new file mode 100644 index 00000000..09de338c --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/core/style/OnceAbsoluteMergeData.java @@ -0,0 +1,19 @@ +package com.alibaba.easyexcel.test.core.style; + +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.annotation.write.style.OnceAbsoluteMerge; +import lombok.Data; + +/** + * @author Pengliang Zhao + */ +@Data +@OnceAbsoluteMerge(firstRowIndex = (short)0, lastRowIndex = (short)2, firstColumnIndex = (short)0, lastColumnIndex = (short)2) +public class OnceAbsoluteMergeData { + @ExcelProperty(value = "洗漱种类", index = 0) + private String category; + @ExcelProperty(value = "毛巾名称", index = 1) + private String towel; + @ExcelProperty(value = "毛巾尺寸", index = 2) + private String size; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/SimpleVerticalCellStyleStrategy.java b/src/test/java/com/alibaba/easyexcel/test/core/style/SimpleVerticalCellStyleStrategy.java new file mode 100644 index 00000000..c99de9d5 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/core/style/SimpleVerticalCellStyleStrategy.java @@ -0,0 +1,52 @@ +package com.alibaba.easyexcel.test.core.style; + +import org.apache.poi.ss.usermodel.FillPatternType; +import org.apache.poi.ss.usermodel.Font; +import org.apache.poi.ss.usermodel.IndexedColors; + +import com.alibaba.excel.annotation.write.style.ContentFontStyle; +import com.alibaba.excel.annotation.write.style.ContentStyle; +import com.alibaba.excel.metadata.Head; +import com.alibaba.excel.metadata.property.FontProperty; +import com.alibaba.excel.metadata.property.StyleProperty; +import com.alibaba.excel.write.metadata.style.WriteCellStyle; +import com.alibaba.excel.write.metadata.style.WriteFont; +import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy; + +/** + * @author Pengliang Zhao + */ +public class SimpleVerticalCellStyleStrategy extends AbstractVerticalCellStyleStrategy { + private StyleProperty styleProperty = StyleProperty.build(StyleOtherData.class.getAnnotation(ContentStyle.class)); + private FontProperty fontProperty = FontProperty.build(StyleOtherData.class.getAnnotation(ContentFontStyle.class)); + + @Override + protected WriteCellStyle headCellStyle(Head head) { + WriteCellStyle writeCellStyle = WriteCellStyle.build(styleProperty, fontProperty); + if(head.getColumnIndex() == 0) { + writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); + WriteFont writeFont = new WriteFont(); + writeFont.setItalic(true); + writeFont.setStrikeout(true); + writeFont.setTypeOffset(Font.SS_NONE); + writeFont.setUnderline(Font.U_DOUBLE); + writeFont.setBold(true); + writeFont.setCharset((int)Font.DEFAULT_CHARSET); + } else { + writeCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex()); + } + return writeCellStyle; + } + + @Override + protected WriteCellStyle contentCellStyle(Head head) { + WriteCellStyle writeCellStyle = new WriteCellStyle(); + writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); + if (head.getColumnIndex() == 0) { + writeCellStyle.setFillForegroundColor(IndexedColors.DARK_GREEN.getIndex()); + } else { + writeCellStyle.setFillForegroundColor(IndexedColors.PINK.getIndex()); + } + return writeCellStyle; + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java index 4e170944..8b984e6e 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java @@ -17,13 +17,17 @@ import org.junit.runners.MethodSorters; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.annotation.write.style.OnceAbsoluteMerge; import com.alibaba.excel.metadata.Head; +import com.alibaba.excel.metadata.property.LoopMergeProperty; +import com.alibaba.excel.metadata.property.OnceAbsoluteMergeProperty; import com.alibaba.excel.write.merge.LoopMergeStrategy; import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy; import com.alibaba.excel.write.metadata.style.WriteCellStyle; import com.alibaba.excel.write.metadata.style.WriteFont; import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy; +import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy; import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy; import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy; @@ -36,11 +40,19 @@ public class StyleDataTest { private static File file07; private static File file03; + private static File file04; + private static File file05; + private static File file06; + private static File file08; @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("style07.xlsx"); file03 = TestFileUtil.createNewFile("style03.xls"); + file04 = TestFileUtil.createNewFile("simpleVerticalCellStyleStrategy01.xls"); + file05 = TestFileUtil.createNewFile("longestMatchColumnWidthStyleStrategy01.xls"); + file06 = TestFileUtil.createNewFile("loopMergeStrategy01.xls"); + file08 = TestFileUtil.createNewFile("onceAbsoluteMergeStrategy01.xls"); } @Test @@ -117,6 +129,37 @@ public class StyleDataTest { .doWrite(data10()); } + @Test + public void t05AbstractVerticalCellStyleStrategy03() { + AbstractVerticalCellStyleStrategy verticalCellStyleStrategy = new SimpleVerticalCellStyleStrategy(); + EasyExcel.write(file04, StyleOtherData.class).registerWriteHandler(verticalCellStyleStrategy).sheet() + .doWrite(data1()); + } + + @Test + public void t06longestMatchColumnWidthStyleStrategy() { + EasyExcel.write(file05, StyleData.class) + .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("模板").doWrite(data()); + } + + @Test + public void t07loopMergeStrategy() { + LoopMergeProperty loopMergeProperty = new LoopMergeProperty(1,2); + loopMergeProperty.setEachRow(2); + loopMergeProperty.setColumnExtend(1); + EasyExcel.write(file06, LoopMergeData.class) + .registerWriteHandler(new LoopMergeStrategy(loopMergeProperty, 1)) + .sheet("模板").doWrite(data2()); + } + + @Test + public void to8onceAbsoluteMergeStrategy() { + OnceAbsoluteMerge onceAbsoluteMerge = OnceAbsoluteMergeData.class.getAnnotation(OnceAbsoluteMerge.class); + OnceAbsoluteMergeProperty onceAbsoluteMergeProperty = OnceAbsoluteMergeProperty.build(onceAbsoluteMerge); + OnceAbsoluteMergeStrategy onceAbsoluteMergeStrategy = new OnceAbsoluteMergeStrategy(onceAbsoluteMergeProperty); + EasyExcel.write(file08, OnceAbsoluteMergeData.class) + .registerWriteHandler(onceAbsoluteMergeStrategy).sheet("模板").doWrite(data3()); + } private void readAndWrite(File file) { SimpleColumnWidthStyleStrategy simpleColumnWidthStyleStrategy = new SimpleColumnWidthStyleStrategy(50); SimpleRowHeightStyleStrategy simpleRowHeightStyleStrategy = @@ -156,6 +199,43 @@ public class StyleDataTest { return list; } + private List data1() { + List list = new ArrayList(); + StyleOtherData data = new StyleOtherData(); + data.setString("字符串0"); + data.setString1("字符串01"); + StyleOtherData data1 = new StyleOtherData(); + data1.setString("字符串1"); + data1.setString1("字符串11"); + list.add(data); + list.add(data1); + return list; + } + + private List data2() { + List list = new ArrayList(); + for (int i = 0; i <= 5; i++) { + LoopMergeData loopMergeData = new LoopMergeData(); + loopMergeData.setCategory("洗漱用品"); + loopMergeData.setTowel("毛巾"); + loopMergeData.setSize("10" + 1 + "#"); + list.add(loopMergeData); + } + return list; + } + + private List data3() { + List list = new ArrayList(); + for (int i = 0; i <= 5; i++) { + OnceAbsoluteMergeData onceAbsoluteMergeData = new OnceAbsoluteMergeData(); + onceAbsoluteMergeData.setCategory("洗漱用品"); + onceAbsoluteMergeData.setTowel("毛巾"); + onceAbsoluteMergeData.setSize("10" + 1 + "#"); + list.add(onceAbsoluteMergeData); + } + return list; + } + private List data10() { List list = new ArrayList(); for (int i = 0; i < 10; i++) { diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleOtherData.java b/src/test/java/com/alibaba/easyexcel/test/core/style/StyleOtherData.java new file mode 100644 index 00000000..8c0383d2 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/core/style/StyleOtherData.java @@ -0,0 +1,20 @@ +package com.alibaba.easyexcel.test.core.style; + +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.annotation.write.style.ContentFontStyle; +import com.alibaba.excel.annotation.write.style.ContentStyle; +import lombok.Data; + +/** + * @author Pengliang Zhao + */ +@Data +public class StyleOtherData { + @ContentStyle(dataFormat = (short)1, rotation = (short)1, indent = (short)1, leftBorderColor = (short)1, rightBorderColor = (short)1, + topBorderColor = (short)1, bottomBorderColor = (short)1, fillForegroundColor = (short)1, fillBackgroundColor = (short)1) + @ContentFontStyle(fontHeightInPoints = (short)1, color = (short)1, typeOffset = (short)1, charset = (short)1) + @ExcelProperty("字符串") + private String string; + @ExcelProperty("字符串1") + private String string1; +} From 8368d37338e76ac519ddf89d63d9f45e0478628e Mon Sep 17 00:00:00 2001 From: dota17 Date: Tue, 19 May 2020 19:30:36 +0800 Subject: [PATCH 007/129] Improved the code --- ...therData.java => AnnotationStyleData.java} | 7 +++-- .../SimpleVerticalCellStyleStrategy.java | 6 ++-- .../test/core/style/StyleDataTest.java | 30 +++++++++---------- 3 files changed, 22 insertions(+), 21 deletions(-) rename src/test/java/com/alibaba/easyexcel/test/core/style/{StyleOtherData.java => AnnotationStyleData.java} (70%) diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleOtherData.java b/src/test/java/com/alibaba/easyexcel/test/core/style/AnnotationStyleData.java similarity index 70% rename from src/test/java/com/alibaba/easyexcel/test/core/style/StyleOtherData.java rename to src/test/java/com/alibaba/easyexcel/test/core/style/AnnotationStyleData.java index 8c0383d2..dd5dac60 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleOtherData.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/style/AnnotationStyleData.java @@ -9,9 +9,10 @@ import lombok.Data; * @author Pengliang Zhao */ @Data -public class StyleOtherData { - @ContentStyle(dataFormat = (short)1, rotation = (short)1, indent = (short)1, leftBorderColor = (short)1, rightBorderColor = (short)1, - topBorderColor = (short)1, bottomBorderColor = (short)1, fillForegroundColor = (short)1, fillBackgroundColor = (short)1) +public class AnnotationStyleData { + @ContentStyle(dataFormat = (short)1, rotation = (short)1, indent = (short)1, leftBorderColor = (short)1, + rightBorderColor = (short)1, topBorderColor = (short)1, bottomBorderColor = (short)1, + fillForegroundColor = (short)1, fillBackgroundColor = (short)1) @ContentFontStyle(fontHeightInPoints = (short)1, color = (short)1, typeOffset = (short)1, charset = (short)1) @ExcelProperty("字符串") private String string; diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/SimpleVerticalCellStyleStrategy.java b/src/test/java/com/alibaba/easyexcel/test/core/style/SimpleVerticalCellStyleStrategy.java index c99de9d5..9f4d3ac2 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/style/SimpleVerticalCellStyleStrategy.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/style/SimpleVerticalCellStyleStrategy.java @@ -17,13 +17,13 @@ import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy; * @author Pengliang Zhao */ public class SimpleVerticalCellStyleStrategy extends AbstractVerticalCellStyleStrategy { - private StyleProperty styleProperty = StyleProperty.build(StyleOtherData.class.getAnnotation(ContentStyle.class)); - private FontProperty fontProperty = FontProperty.build(StyleOtherData.class.getAnnotation(ContentFontStyle.class)); + private StyleProperty styleProperty = StyleProperty.build(AnnotationStyleData.class.getAnnotation(ContentStyle.class)); + private FontProperty fontProperty = FontProperty.build(AnnotationStyleData.class.getAnnotation(ContentFontStyle.class)); @Override protected WriteCellStyle headCellStyle(Head head) { WriteCellStyle writeCellStyle = WriteCellStyle.build(styleProperty, fontProperty); - if(head.getColumnIndex() == 0) { + if (head.getColumnIndex() == 0) { writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); WriteFont writeFont = new WriteFont(); writeFont.setItalic(true); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java index 8b984e6e..dc61c933 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java @@ -132,23 +132,22 @@ public class StyleDataTest { @Test public void t05AbstractVerticalCellStyleStrategy03() { AbstractVerticalCellStyleStrategy verticalCellStyleStrategy = new SimpleVerticalCellStyleStrategy(); - EasyExcel.write(file04, StyleOtherData.class).registerWriteHandler(verticalCellStyleStrategy).sheet() + EasyExcel.write(file04, AnnotationStyleData.class).registerWriteHandler(verticalCellStyleStrategy).sheet() .doWrite(data1()); } @Test - public void t06longestMatchColumnWidthStyleStrategy() { - EasyExcel.write(file05, StyleData.class) - .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("模板").doWrite(data()); + public void t06longestMatchColumnWidthStyleStrategy() { + EasyExcel.write(file05, StyleData.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) + .sheet("模板").doWrite(data()); } @Test public void t07loopMergeStrategy() { - LoopMergeProperty loopMergeProperty = new LoopMergeProperty(1,2); + LoopMergeProperty loopMergeProperty = new LoopMergeProperty(1, 2); loopMergeProperty.setEachRow(2); loopMergeProperty.setColumnExtend(1); - EasyExcel.write(file06, LoopMergeData.class) - .registerWriteHandler(new LoopMergeStrategy(loopMergeProperty, 1)) + EasyExcel.write(file06, LoopMergeData.class).registerWriteHandler(new LoopMergeStrategy(loopMergeProperty, 1)) .sheet("模板").doWrite(data2()); } @@ -157,9 +156,10 @@ public class StyleDataTest { OnceAbsoluteMerge onceAbsoluteMerge = OnceAbsoluteMergeData.class.getAnnotation(OnceAbsoluteMerge.class); OnceAbsoluteMergeProperty onceAbsoluteMergeProperty = OnceAbsoluteMergeProperty.build(onceAbsoluteMerge); OnceAbsoluteMergeStrategy onceAbsoluteMergeStrategy = new OnceAbsoluteMergeStrategy(onceAbsoluteMergeProperty); - EasyExcel.write(file08, OnceAbsoluteMergeData.class) - .registerWriteHandler(onceAbsoluteMergeStrategy).sheet("模板").doWrite(data3()); + EasyExcel.write(file08, OnceAbsoluteMergeData.class).registerWriteHandler(onceAbsoluteMergeStrategy).sheet("模板") + .doWrite(data3()); } + private void readAndWrite(File file) { SimpleColumnWidthStyleStrategy simpleColumnWidthStyleStrategy = new SimpleColumnWidthStyleStrategy(50); SimpleRowHeightStyleStrategy simpleRowHeightStyleStrategy = @@ -199,12 +199,12 @@ public class StyleDataTest { return list; } - private List data1() { - List list = new ArrayList(); - StyleOtherData data = new StyleOtherData(); + private List data1() { + List list = new ArrayList(); + AnnotationStyleData data = new AnnotationStyleData(); data.setString("字符串0"); data.setString1("字符串01"); - StyleOtherData data1 = new StyleOtherData(); + AnnotationStyleData data1 = new AnnotationStyleData(); data1.setString("字符串1"); data1.setString1("字符串11"); list.add(data); @@ -218,7 +218,7 @@ public class StyleDataTest { LoopMergeData loopMergeData = new LoopMergeData(); loopMergeData.setCategory("洗漱用品"); loopMergeData.setTowel("毛巾"); - loopMergeData.setSize("10" + 1 + "#"); + loopMergeData.setSize("10" + i + "#"); list.add(loopMergeData); } return list; @@ -230,7 +230,7 @@ public class StyleDataTest { OnceAbsoluteMergeData onceAbsoluteMergeData = new OnceAbsoluteMergeData(); onceAbsoluteMergeData.setCategory("洗漱用品"); onceAbsoluteMergeData.setTowel("毛巾"); - onceAbsoluteMergeData.setSize("10" + 1 + "#"); + onceAbsoluteMergeData.setSize("10" + i + "#"); list.add(onceAbsoluteMergeData); } return list; From 1a6bb95a17138b9ab92eb3326e78eb2f841386fc Mon Sep 17 00:00:00 2001 From: Zebulon Feng <1294700694@qq.com> Date: Wed, 24 Jun 2020 10:31:52 +0800 Subject: [PATCH 008/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=94=99=E5=88=AB?= =?UTF-8?q?=E5=AD=97=EF=BC=8C=E4=BF=AE=E6=94=B9=E5=8F=A5=E5=AD=90=E4=BD=BF?= =?UTF-8?q?=E5=85=B6=E9=80=9A=E9=A1=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 89bae018..9812ee28 100644 --- a/README.md +++ b/README.md @@ -15,10 +15,10 @@ EasyExcel #### 因为公司不方便用QQ,所以建议加钉钉群 # JAVA解析Excel工具EasyExcel -Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,能够原本一个3M的excel用POI sax依然需要100M左右内存降低到几M,并且再大的excel不会出现内存溢出,03版依赖POI的sax模式。在上层做了模型转换的封装,让使用者更加简单方便 +Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,使用easyexcel解析可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便 ## 64M内存1分钟内读取75M(46W行25列)的Excel -当然还有急速模式能更快,但是内存占用会在100M多一点 +当然还有极速模式能更快,但是内存占用会在100M多一点 ![img](img/readme/large.png) ## 相关文档 From a65c4de055fc57e258aeb81c8f3d36d05f7375a1 Mon Sep 17 00:00:00 2001 From: Zebulon Feng <1294700694@qq.com> Date: Wed, 24 Jun 2020 10:46:57 +0800 Subject: [PATCH 009/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=94=99=E5=88=AB?= =?UTF-8?q?=E5=AD=97=EF=BC=8C=E4=BF=AE=E6=94=B9=E5=8F=A5=E5=AD=90=E4=BD=BF?= =?UTF-8?q?=E5=85=B6=E9=80=9A=E9=A1=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9812ee28..31da8c8b 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ EasyExcel #### 因为公司不方便用QQ,所以建议加钉钉群 # JAVA解析Excel工具EasyExcel -Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,使用easyexcel解析可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便 +Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,改用easyexcel可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便 ## 64M内存1分钟内读取75M(46W行25列)的Excel 当然还有极速模式能更快,但是内存占用会在100M多一点 From 5de67db8cd90379d64a31c47d22aecc9dd6a306d Mon Sep 17 00:00:00 2001 From: fanfanyimeng <522050061@qq.com> Date: Wed, 22 Jul 2020 13:45:57 +0800 Subject: [PATCH 010/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=83=A8=E5=88=86?= =?UTF-8?q?=E6=83=85=E5=86=B5=E8=87=AA=E5=8A=A8=E5=8E=BB=E9=99=A4=E7=A9=BA?= =?UTF-8?q?=E6=A0=BC=E6=97=A0=E6=95=88=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 当不是从sharedStrings.xml取到的string时,代码未执行去除空格。 --- .../analysis/v07/handlers/AbstractCellValueTagHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java index 3521e46a..6f2fbae8 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java @@ -44,7 +44,7 @@ public abstract class AbstractCellValueTagHandler extends AbstractXlsxTagHandler if (tempCellData.getStringValue() != null && xlsxReadContext.currentReadHolder().globalConfiguration().getAutoTrim()) { - tempCellData.setStringValue(tempCellData.getStringValue()); + tempCellData.setStringValue(tempCellData.getStringValue().trim()); } tempCellData.checkEmpty(); From 4629a2842865565f9b8673beff22030b81ae6220 Mon Sep 17 00:00:00 2001 From: "ian.zhang" Date: Fri, 11 Sep 2020 11:58:21 +0800 Subject: [PATCH 011/129] Fix the contentType issue Raise the PR to fix the sample issue by incorrect content type. By given sample, we will get a xls type excel even set excelType(ExcelTypeEnum.XLSX), which will open with an alert even the file encoding is based on xlsx. "The file format and extension of 'xxx' don't match. The file could be corrupted of unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?" The root cause is from incorrect content type. it will be fine if set the content type based on xlsx as below response.setContentType("vnd.openxmlformats-officedocument.spreadsheetml.sheet") Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types .xls Microsoft Excel application/vnd.ms-excel .xlsx Microsoft Excel (OpenXML) application/vnd.openxmlformats-officedocument.spreadsheetml.sheet --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9a44127b..1bd0b68d 100644 --- a/README.md +++ b/README.md @@ -80,12 +80,12 @@ DEMO代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/ja @GetMapping("download") public void download(HttpServletResponse response) throws IOException { // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman - response.setContentType("application/vnd.ms-excel"); + response.setContentType("vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系 String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); - EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data()); + EasyExcel.write(response.getOutputStream(), DownloadData.class).excelType(ExcelTypeEnum.XLSX).sheet("模板").doWrite(data()); } /** From 006b102e1625ffebaf814ace8e5d86ebda40021a Mon Sep 17 00:00:00 2001 From: "ian.zhang" Date: Fri, 11 Sep 2020 12:05:54 +0800 Subject: [PATCH 012/129] Update correct content type Update correct content type --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1bd0b68d..d7bf60a4 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ DEMO代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/ja @GetMapping("download") public void download(HttpServletResponse response) throws IOException { // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman - response.setContentType("vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系 String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20"); From 4540aba6997bf6969184712ce8728fb00c80d5de Mon Sep 17 00:00:00 2001 From: "ian.zhang" Date: Fri, 11 Sep 2020 12:20:27 +0800 Subject: [PATCH 013/129] Update WebTest.java Fix incorrect content type. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); --- .../java/com/alibaba/easyexcel/test/demo/web/WebTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java index ab0ad968..ffa01041 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java @@ -43,12 +43,12 @@ public class WebTest { @GetMapping("download") public void download(HttpServletResponse response) throws IOException { // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman - response.setContentType("application/vnd.ms-excel"); + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系 String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); - EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data()); + EasyExcel.write(response.getOutputStream(), DownloadData.class).excelType(ExcelTypeEnum.XLSX).sheet("模板").doWrite(data()); } /** @@ -60,13 +60,13 @@ public class WebTest { public void downloadFailedUsingJson(HttpServletResponse response) throws IOException { // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman try { - response.setContentType("application/vnd.ms-excel"); + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系 String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); // 这里需要设置不关闭流 - EasyExcel.write(response.getOutputStream(), DownloadData.class).autoCloseStream(Boolean.FALSE).sheet("模板") + EasyExcel.write(response.getOutputStream(), DownloadData.class).excelType(ExcelTypeEnum.XLSX).autoCloseStream(Boolean.FALSE).sheet("模板") .doWrite(data()); } catch (Exception e) { // 重置response From 2adb7a472e343327bea17a0bf5a1da644d20183a Mon Sep 17 00:00:00 2001 From: "ian.zhang" Date: Fri, 11 Sep 2020 12:26:35 +0800 Subject: [PATCH 014/129] Update WebTest.java Fix missed dependency. --- src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java index ffa01041..e2c14137 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java @@ -18,6 +18,7 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.fastjson.JSON; /** From ecde3d47e21db84b183422a7a2556a5a394e1874 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 13 Oct 2020 06:42:45 +0000 Subject: [PATCH 015/129] Bump junit from 4.12 to 4.13.1 Bumps [junit](https://github.com/junit-team/junit4) from 4.12 to 4.13.1. - [Release notes](https://github.com/junit-team/junit4/releases) - [Changelog](https://github.com/junit-team/junit4/blob/main/doc/ReleaseNotes4.12.md) - [Commits](https://github.com/junit-team/junit4/compare/r4.12...r4.13.1) Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 831caff0..19590396 100644 --- a/pom.xml +++ b/pom.xml @@ -121,7 +121,7 @@ junit junit - 4.12 + 4.13.1 test From 51bf294b52aaf2fa456ca29ccc82761888e4f998 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E6=9C=AC=E9=BE=99?= <852026881@qq.com> Date: Mon, 26 Oct 2020 14:19:06 +0800 Subject: [PATCH 016/129] =?UTF-8?q?LongestMatchColumnWidthStyleStrategy?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E5=88=97=E5=AE=BDBUG?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LongestMatchColumnWidthStyleStrategy设置列宽BUG:与spring集成时 ,由于bean是单例,CACHE内容不会改变,同一个报表只有第一次调用会动态设置列宽 --- .../style/column/LongestMatchColumnWidthStyleStrategy.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java index cc8dcb20..a00d63d7 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java @@ -33,6 +33,12 @@ public class LongestMatchColumnWidthStyleStrategy extends AbstractColumnWidthSty if (!needSetWidth) { return; } + + //LongestMatchColumnWidthStyleStrategy设置列宽BUG:与spring集成时 ,由于bean是单例,CACHE内容不会改变,同一个报表只有第一次调用会动态设置列宽 + if (cell.getRowIndex() == 0 && cell.getColumnIndex() == 0) { + CACHE.clear(); + } + Map maxColumnWidthMap = cache.get(writeSheetHolder.getSheetNo()); if (maxColumnWidthMap == null) { maxColumnWidthMap = new HashMap(16); From d797accc83beba5d64d2ceed9506e2bf40f3b98c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E9=B9=8F=E4=BD=B3?= <532332729@qq.com> Date: Tue, 27 Oct 2020 13:14:48 +0800 Subject: [PATCH 017/129] =?UTF-8?q?=E5=A4=84=E7=90=86=E6=97=A0=E5=8F=98?= =?UTF-8?q?=E9=87=8Fnpe?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../executor/ExcelWriteFillExecutor.java | 3 +++ .../easyexcel/test/demo/fill/FillTest.java | 18 ++++++++++++++++++ src/test/resources/demo/fill/no_variable.xlsx | Bin 0 -> 9946 bytes 3 files changed, 21 insertions(+) create mode 100644 src/test/resources/demo/fill/no_variable.xlsx diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 5930a311..4bfd06fc 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -188,6 +188,9 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { WriteSheetHolder writeSheetHolder = writeContext.writeSheetHolder(); Map fieldNameContentPropertyMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getFieldNameContentPropertyMap(); + if(null == analysisCellList || analysisCellList.isEmpty()){ + return; + } for (AnalysisCell analysisCell : analysisCellList) { Cell cell = getOneCell(analysisCell, fillConfig); if (analysisCell.getOnlyOneVariable()) { diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java index 7a0e92e5..3c77ba78 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java @@ -80,6 +80,24 @@ public class FillTest { excelWriter.finish(); } + /** + * 处理无变量问题 + * + * @since 2.1.1 + */ + @Test + public void noVariableFill() { + // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替 + // 填充list 的时候还要注意 模板中{.} 多了个点 表示list + String templateFileName = + TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "no_variable.xlsx"; + + // 方案1 一下子全部放到内存里面 并填充 + String fileName = TestFileUtil.getPath() + "listFill" + System.currentTimeMillis() + ".xlsx"; + // 这里 会填充到第一个sheet, 然后文件流会自动关闭 + EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(data()); + } + /** * 复杂的填充 * diff --git a/src/test/resources/demo/fill/no_variable.xlsx b/src/test/resources/demo/fill/no_variable.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..982321d6e39412eef856e1691fe579c303e0324f GIT binary patch literal 9946 zcmeHtbyO7G);CD^P=a(fNDI>4Fm$&ALw5;7hayM`(hbtm-5sKYAl)e-p>(~2zW4Ew z``o+Uf4{Z9vlcTf*m2I@`|Q2f`E8&A96Tz_-3n7)5xx8V*Fu5*^31^;=<-^olJ9oanXY|~5H+LQVts0hRB!qh7p8!V~L> z)G2R_N)oU$p+jl-l69;*R}b)k({7Cnj54)&;KtPGj83kX0Vhh{T?ttcHoyz-TajbJY0n34am^=XFz5)SN zXV8`>5_MrD<_)oe!}yY5 zOhk;8`7|J&;u_IwS0n#g6vB6$j9rr0S!gzBp%vH!(N3$H!9|^NWnA{fIq55buM~t4 zc5%l#9_g?(tb5YBzM6bNl!sSZSwCjQ8vQ^5^$~*&`!U0f1?$#_E3Yi&+J2Ub@7c+P zg-v@2W~8-0KG3l0B;;u$xCuA#&8VpkNaVQvbfv!bwryDov_%TkfdL{5KgHH^{Jg!X?1tLxe zDK{w>fWz1I_!dg>ev!gXj850z5)mWRq?`16BPq(fZ?CS;(EfD7%X}Es8>sPpp^m`) z!wGIKt`2rT13p^FA&4CydMba7mEd8%8j1q|;L9dpmVV|Is8ljTneFGTF8J#AUiG5F zL$GChyouR;-x{W>T$#wQlaC63JdFPK!l3iZDy$u)W9xV`al}JfgW#a1uP6DQwHA1j z3d^EEuy*IGQ}fpq<^)+!2@p!)wj(vuuyTaV$4_HlPL|7|>~YYpkyQ3X zYeQh~%=OPX1P*F0Puri_7{Y&}{mH^{ z=YUA{0sC2YKnuZ^2tcxIbcNgAP6u<2P#UdT6zI`3_PL)*(OM_AGR+4Prnc7Th&d{T zW69^RkOFe|;7;D_@Cs4t_)fEmPV_R*x)$N~5aMpjv9%9cZDt3meK~{63CoA zC!$~%2m5sF0Cu^RT1q;QGcrR$1@WI!KOmjwJ)R6;Xrjm&S51gir`G854leY@K-7wl zEti}o0*hm5e zyTBlkOG`1^$xJashQcqYJ!JL(kHZy9P7roe6978|-5TpOlLs~mjDF+FU-mF(dt!gW z8Si`UJIT#ki80MDS4e&G1(L;GLSK!G(A_%deaazSUG%`&r+^$M@$pc*k)nXdlreNSY78X-4Mc1xC#0V0|_u|RcD}nF}d->>e~E@ciPi$ds4mWIaWe~2i~pAi+OA zLJmJ~!@rZv6S8Lp2H1wd_B2LSnT^*15t>bdxu^+;u?3g*Yfa`R4fP_aEnptD3ypD z)8!_ed~Oc^A_-YCvJ|4n`J%qjuiq>(zNtvcVXB}TsjM{ivB{ut!Vl7Tf&QbjJoR-G zq~64FX`{B6=sDSJye7x%1L2|~FnW|Jp8$3i>v~_v+Azm;S36}|Nspt6e)oLz+1wjW za#52kGHH75HnL^R5>iI0>!+|q)D=uOrIr^Kf-9E{MBw9vG18fg{H)eD%>4V1o-TTJ zLzUeMkUK=9VKP_OX@t~gw1P_*1&!4&-g0Q-D`#7BMjoD1ksqZ5VQ4s(wwi4W@;u4$ z?h_O8wdp)OR;uBSML%Jfy&&YLqCV_x(+eepIi{A8p-iB5Syf^pc$M;D*<~Q9gXl5R zpUL|F;9jo(@818%-22b903s1#U=oRcmF&OBeiHwz7<;;l z4#Yepeljb5<=-GSV|0e;xwx<$Rk#G4QN z{pC{NaaJ?3%)#hZw-1bGJ>I&wWbJ7M_)BTJSo&REUteF?Y_8-9U`t#|$_}pPYYQ14 z0$xIdbDc(h*#BtSoD`(Ne;t;1n8@A27_*QUdAiv2;)|v%RiFuk<%`oeTD<(^+k{-K zE}isEl$WOV-BQ8$&EY0i3g$8Qj7ur9>gely;mL3{Y&79B;uVx)?@!Wds_6|WO>Ko`=ZV^JeY&U2^Ue}x>Qqdf zSs})vv`Nbj#EnLA$*0m}Sg38y)+*`;Qr?g*o+x^vrpuxVR~c2qf29YiscqO@!suVw zaXHhoshT%(J3xGPSnP84Eu`0axQ7_n4;D<9unBW-Vmv0{T(ND!YehV$kw?wQq98ij z8e@?b)Ouyc+F94I^*|KvkrubKb#gTJ31#9e9}#jm4_vddqiHYZxwF0OckwX-ZdIlI zE_eyE4_ht1Cwn`VDkD3VQCRyzLd~aL%h#7-r>%9>sUfp`nBi!~km~_*<2k7|k@KU8 zu1|x9l`n3On~*;F-BgnxKjMzt>e-C)^S(Ii$%!)d{ay~=%6O28yg&Xz)-{qOQ;00U zzL&jh?HPq~T{gMd*OGS15jM(s)hxJX-kuWlFH~iR_NWYGp!T7-+1Dj4Kt(*(WgprI zk|oT|k{+o-*fOvY0@^9P6Y!&fVtBn!#OaV{ozrf8Etg!TwT0OBR4XZt%m>3z^AI>3 z+>jq6f+z+qv6kKePnt zImAE+P*4JNUmid@Nw|!9aYJ%AV<99J*&XlA@Dos`Q&8Jp?8qXdVaM7qGls2%5 zE(VUjH!0B0vtKkF@0UWA>H~4VH~aXipH;4V1dKgluB&6{6SGU4<mJ5j<=mSEg|%WYyl;Si`fgBTORl`m!Gt^q#Arq+`P2Hv*dR| zyH95FzrTLSyFfjtqoVYvfk|nf)fA4%-4ytq%TgtlygL>^=0*nxheUvEJ4w+oA)^t} z0-ztM(-u;qiDuju%??)Jdz`$iHbaEf(pLFyxKTK4YLK#GW?4d@IXkRsRa&`M7C({8 zt`{tY%g0z1kH)AvvZs`&Sp%fs(BjEX%HDDu(wwB@-E?O6DkDPQm<;}iC?*20WfU^r zW`VIu`k@~frOwRgpVFVh>XmhX+HAkmIu%pQ)R8I1yj|jH6lBHgCWJYu4ThKnc6#atjKq;(%j3Q_(T%L zfQIrK>qLafM_Q3^2czcGX=W|e*|j)sPeX#Yx?kHYJma2O+$7>FeM0~#w zD?zhMTdZf(CY^7pt1-ZT5Xg{p`vdmlrfBy zg}n6zHfCk&+Q*Q5D=@zh6tm(D3B3qk9)_f0$ca!#8z3Z~D{F2W1&lE!E28ly*vwagCo^<4oR z$Z&-_81v<PET&)3n9rc6ZyUw){oFfClnPk~iEPF~cE^V;@67U83))%w*ahMyeMs+vuL zP*yEmE@&z~Il$;uwf$QJ1q>%63$|xxl@o(?zIgGgVy@4h#XG36~;?6qBN)%ZY zXa_(~iey2k*J{&_#OUkyeGBF(J^|4)yk&XU#nh%#pYO7&95hGR@ag8K(GR^zYefP# zIIC4Z85q8=S<0BSotV&4FEpEMIvlQ@t-@plXYbUj6tPRMY4S<=LVAw$``3q_RMnVq z9r88$aM>{P#yPpbwa;mM9k!^-vq25rJK77IwvSa}j`{Q~4)NrPb&Z9RRbitV-~;jJ zn|KXeM8BR35i;4bFC#Vsv?1K~Y0{RK1C=Y=baC1}D@?UD>Wdr+_BJcp6aLy9zM!KT zo#tLAko0YQzp;B!w*@E2l=grpBCS;G9ic2f_ZUZftIpeAN;|xDCC*F&8w<4v6Z-{5 zWPU|iZ8h}7jY1vczUWTecG{B{G`VTY#hJblPTLA6=AN-A<1>bz_B-5FD#ynHAAwx0 zT)HYQC>8U4ydB7|F84{;$GBjQKlKD?ap{C3Y6 zDs3Z%Sn>AD*7=?Qg|59aG#p9e54wb_vM{{Qz*V?=NjY`pz(;M7gKj@eUAkO%g*;3e z%0sNrv*x9U%MH)KQcd|`*RHkTK0%9OQHPI5@gIWVHn-k&b(F0Wd+w9l1iZIjt_bsO zO$UoUZdvxun!q@;g0B|2!jaET`=%p@-#hBeG~kKzFi4?@rbHN9+u9K|s1Zl+V}vKc zL*oOg2^98>tnoqif;VVEPle+--^)v;b7v-x;PFrtZoM{%#=)|Tvq8k2zwUO5S z-Qc=glJkp~4X8$JsvkzTi271BD-GHeRdKY~hW6zORM$0d@W1Ca08Ie7dS%X%&%}`T z3)MjKmTP6*ZcIPG>z`w-$Q1NlOw`|asxjILbEQi{p7D1L=W=PcbaXvxp;<&>t((0EP8 zZ=!@epd!_(6VIOQXnK{K{QSXOQI2h^YaCH6e7ucXP7aap_EjMa(_>w1(YQke{o49% zNp~rROvKEkzGx7UM}2Z#w<5Kr4dFB%^Z@Ms?2w8I>TT+T)$0x+}#Zn*(8o_{X)+@{d1dI%@T-@vXiJR^ncL0LtpNwzh62`HytCkg zYMp?l7owl5RGl%%Thj9V4!>CDh+O$zMV;a%flCu`mV*|?xeFZw&UziiSmD>Rm#LE* zrv01Dc?EY}vxeZwGM^v32jSPBxsB5b9ljejB4A1Hl?V1d$RI_ zGUkH>7Oyfq%>yjpgxBW|9j>5zoW$dHB+Q8Fg#7+fO1e@mkNQIiR;mu7wa+a zQ1?~v70^RTHZ$oJ&kx&P_j%mBmF@Lj;$|BiPZ|f4LfquPZK~#>;@VtIrycgu=Un=c z%{K|$tPzV3Nyy<-;Y^gTzDF6*z{X8zIi&Bi%4q1Y+~bG zAIca50t79r#Yxqv#bU9pI;F&sPjwt(sn7Z!MoRsFnR8{KtCzpYzEH^Kh$1x=RT~nF ziHu4BPM6!#A53rE%x|jfOAHHM9$ZTb3X@2o^tc*B`1!9-c9*wbVJ)U#oi0oVS+1Tc zBg2uYcG5%&N-=nnbT|nHlois&5q3m5J96MuCJEkLZmH}a5RT>_(87bPL9`Nh5$Gj8 zhN-2uHzX$VESshXLvJ1osgI%@Wha*%t{2ihqb?}PZ51PKFJyByw1$5{X2Lm?Pv^RZ zZZg81_{b!LHd%@(jv4HhL5cq`l#dxjaRilD0xresLB_iod4o{Q3=UgY$`l>mfEU6c z+!dvdT9_jQQ#DN8^O#han7~7o0jUIM6!JSsMObNQ3dJjGvX&1=X2R$M=>k5T#V(Nf zk5*l5jG#EgKAz=-+~QvK!*w&X?qFQj5|}--OKSBa6`I73_uFCj5%O2RJkTb(aM!;X z{-~8x(_&s=GyGM{Md?e)j9zhVO^epJfd1^Pba9cEfP+|XrtwAN^MWm|wiBN6rd9&a zYsVHel~jW`aGZ ztsK6E`?EQ89M%EmL7T#6=+7M@2YuRb0h>C5o~gS!TiILw>=C7g#ZWuh0SF^4OQfB< zcGd(`vAF^&nMlZcQxB8nwj;8`0PxsROY#S5$0S+?^;i4f&*?-$wMff1>0(2?VgtpQ z%%*`L(4NZfcr2W?4?a$hHF5DLNd7S=44Sqw4 zl)(z-qR?kqe&}OA)~{pTfdXa@4mLlZ>tYlXej$ptl+PUEl*vDjB?T5tMdE#Kd>to{ zHlm0V`?>ITLEus9!$zn0OFo}e?@GN4BBj<2B#@GFAGI<{;+Q<>g#X&puT>w2lg+LM zwxM_@0@!M-Z_%xpByTMd0>CFmk3W^Jd&csHhnp&*1TH9L@IqSB_BtJ5Q>-5d*DYNY z@txl$n6sLm<=T(1wnzgds#cKK#0={&Q%dqOON(v9Op_6#>4u6b)f*qb-Zd6(6l?mq@sF zEgxr|xOMAnPN#YZx_8KmQ82f3)4X*s71Fx1P+Q`>UhkvpZq9p7e2q3v0GPtf+CAsXl_8H}+r$o4++;?3vYd<*^G zBGe&hf6=hrQI^JjlJ8~*^zK99-Hlcy4}9!t*T+=5O3xtviHf%)bhxp)d#x>Esw|%y zk)o2$H&PaTo;4BAQy6jNzitk6QwM{R^NOn@=YYIIuzD4HR_BlV77#GE>ax5XZ4KX@eFn?VLt66{%Edg0xK z=)@P&eD2^-wDWOEC@Dwc6BqNEMogNUZ8UyFkWbE38{k+95t09svzzeHzK48RNvQ=Z zhLk}_qI&q;x_7zlhF;rWWPgwHpVn=O8?x?V2S}ZU+yo^; zSZA#yP-3bWLu_Y%zy%BW0`xhPx4ZlnJ6_d?F4-&c1}2G}rjJTpcByRH@njL~nA{8fh#xz7ykEBB9;tG3$5Lv(!v8Gi0tXW=3F zGl(n;{Qb{qI(aqv5iRy)Ux*opdFkPYhG`kOWE1YtUiR_q>2h`sKv<4F=@igYcpkMv z_|zl&ar^S5ViOd371*~UO~+^x*LvCCCjQucZ1FQnf2RZoF9a$VXi6Z3hUgvcsxRSS z?+UVaHP-NQ1i2XArG=U|L-x=_Cv_TsffZAS&jBnfVtVjOIDu7d8>#*zSh5?-3q7Q5 zzgv_RfG{?qMAMh<{mnoGF(#OPfQPO}m z<;zPb&K&Q>kD7BAZRp9Eo(-%%Hys{KbSz`aLtcCHIASKpl{fee(<%{*eAts`L5D%X z&o?~U^S?!AALa!f#(sMKRVQL0cAUK~kZ|(H|f60-&P#XBNB4czbJL z_846v7o)P-Q-r5eAT?^VuhxBe>d)Zv;0$!VJ3gapGvzz;=6R8n)yJhiR`D4~k=5dH zSxjRa!`z6>ZD+vMMBkp@<F?C^r_%e$>5k`@QZ%xE@%+3@|4rH5ZT+?Gl-;erjl2A*@BYBc z9q})H^nYjj-|?6GCb~bx@tZpu8s2{?{nt##efInF2fx|zp~>Vo`(M)t|LxFsi2Sd0 zcW6l{tPagY|Bc~KD{+zkEp^@B==~gbr{|ZI^#0EFZyE2tock@#Z#g+oJm;Spp8FE+ zzo7k=5DFcmxs&kMd)oi~>{-y5g|hw&Z~8Mr?jugWHTM6V?Kl2(f6Mn9px*+Xll;{C zceDMsP2Y`F{91P&2L1Bz9rIrU7Ju&i{)ojL?=P>#{2TA@fs6awzmL2Ama+=H)KIhi nZ3jQ4`~=zm?@~IE|53_MEElMN@H27XLd!%Pbk7`AciR64z*G7c literal 0 HcmV?d00001 From 6e0ca6b2a456d5c35ffbbe1bcf4f34a9414e787a Mon Sep 17 00:00:00 2001 From: "Cai, Zhouxiang" Date: Wed, 25 Nov 2020 03:39:29 -0600 Subject: [PATCH 018/129] fix flaytests in SimpleDataTest --- .../com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java index 2d3c75b6..39d759d2 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java @@ -62,6 +62,7 @@ public class SimpleDataTest { private void synchronousRead(File file) { // Synchronous read file + EasyExcel.write(file, SimpleData.class).sheet().doWrite(data()); List list = EasyExcel.read(file).head(SimpleData.class).sheet().doReadSync(); Assert.assertEquals(list.size(), 10); Assert.assertTrue(list.get(0) instanceof SimpleData); From 4ada48181241beca24d10a71bd2b7f87168ae491 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BD=95=E4=B9=90=E5=A4=A9?= <869759838@qq.com> Date: Thu, 17 Dec 2020 09:28:50 +0800 Subject: [PATCH 019/129] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=B8=A4=E4=B8=AA?= =?UTF-8?q?=E7=B2=BE=E5=BA=A6=E5=8F=AA=E5=88=B0=E5=88=86=E7=9A=84=E6=97=B6?= =?UTF-8?q?=E9=97=B4=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/alibaba/excel/util/DateUtils.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/com/alibaba/excel/util/DateUtils.java b/src/main/java/com/alibaba/excel/util/DateUtils.java index 815257b9..cef0098a 100644 --- a/src/main/java/com/alibaba/excel/util/DateUtils.java +++ b/src/main/java/com/alibaba/excel/util/DateUtils.java @@ -43,6 +43,8 @@ public class DateUtils { public static final String DATE_FORMAT_10 = "yyyy-MM-dd"; public static final String DATE_FORMAT_14 = "yyyyMMddHHmmss"; + public static final String DATE_FORMAT_16 = "yyyy-MM-dd HH:mm"; + public static final String DATE_FORMAT_16_FORWARD_SLASH = "yyyy/MM/dd HH:mm"; public static final String DATE_FORMAT_17 = "yyyyMMdd HH:mm:ss"; public static final String DATE_FORMAT_19 = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_FORMAT_19_FORWARD_SLASH = "yyyy/MM/dd HH:mm:ss"; @@ -91,6 +93,12 @@ public class DateUtils { } else { return DATE_FORMAT_19_FORWARD_SLASH; } + case 16: + if (dateString.contains(MINUS)) { + return DATE_FORMAT_16; + } else { + return DATE_FORMAT_16_FORWARD_SLASH; + } case 17: return DATE_FORMAT_17; case 14: From 2989ab10191e9313affe4fe32a4f8834abd0b772 Mon Sep 17 00:00:00 2001 From: yuwen Date: Sat, 30 Jan 2021 16:52:55 +0800 Subject: [PATCH 020/129] =?UTF-8?q?fix.=E5=A4=84=E7=90=86=E7=A9=BA?= =?UTF-8?q?=E5=80=BC=E4=B8=8D=E5=8F=97=E6=8C=87=E5=AE=9Aconverter=E5=A4=84?= =?UTF-8?q?=E7=90=86=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/write/executor/AbstractExcelWriteExecutor.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index 4eb115c5..9e7ade6c 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -32,9 +32,6 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { protected CellData converterAndSet(WriteHolder currentWriteHolder, Class clazz, Cell cell, Object value, ExcelContentProperty excelContentProperty, Head head, Integer relativeRowIndex) { - if (value == null) { - return new CellData(CellDataTypeEnum.EMPTY); - } if (value instanceof String && currentWriteHolder.globalConfiguration().getAutoTrim()) { value = ((String)value).trim(); } @@ -70,9 +67,6 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { protected CellData convert(WriteHolder currentWriteHolder, Class clazz, Cell cell, Object value, ExcelContentProperty excelContentProperty) { - if (value == null) { - return new CellData(CellDataTypeEnum.EMPTY); - } // This means that the user has defined the data. if (value instanceof CellData) { CellData cellDataValue = (CellData)value; @@ -103,6 +97,9 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { converter = excelContentProperty.getConverter(); } if (converter == null) { + if (value == null || clazz == null) { + return new CellData(CellDataTypeEnum.EMPTY); + } converter = currentWriteHolder.converterMap().get(ConverterKeyBuild.buildKey(clazz)); } if (converter == null) { From 3e95d1d1637fa2fe4215503a2b52c7119570dd54 Mon Sep 17 00:00:00 2001 From: ZJR <615817413@qq.com> Date: Sun, 28 Mar 2021 21:00:07 +0800 Subject: [PATCH 021/129] fix: issue 1804, inputStream auto close even autoClosedStream is false --- .../excel/analysis/v07/XlsxSaxAnalyser.java | 6 +++-- .../com/alibaba/excel/util/FileUtils.java | 22 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java index a0a9af0e..9f78de65 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java @@ -147,9 +147,11 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor { xlsxReadWorkbookHolder.setTempFile(readTempFile); File tempFile = new File(readTempFile.getPath(), UUID.randomUUID().toString() + ".xlsx"); if (decryptedStream != null) { - FileUtils.writeToFile(tempFile, decryptedStream); + if(xlsxReadWorkbookHolder.getAutoCloseStream()) FileUtils.writeToFile(tempFile, decryptedStream); + else FileUtils.writeToFileNotCloseStream(tempFile, decryptedStream); } else { - FileUtils.writeToFile(tempFile, xlsxReadWorkbookHolder.getInputStream()); + if(xlsxReadWorkbookHolder.getAutoCloseStream()) FileUtils.writeToFile(tempFile, xlsxReadWorkbookHolder.getInputStream()); + else FileUtils.writeToFileNotCloseStream(tempFile, xlsxReadWorkbookHolder.getInputStream()); } return OPCPackage.open(tempFile, PackageAccess.READ); } diff --git a/src/main/java/com/alibaba/excel/util/FileUtils.java b/src/main/java/com/alibaba/excel/util/FileUtils.java index 20b16bc6..09192473 100644 --- a/src/main/java/com/alibaba/excel/util/FileUtils.java +++ b/src/main/java/com/alibaba/excel/util/FileUtils.java @@ -132,6 +132,28 @@ public class FileUtils { } } + public static void writeToFileNotCloseStream(File file, InputStream inputStream) { + OutputStream outputStream = null; + try { + outputStream = new FileOutputStream(file); + int bytesRead; + byte[] buffer = new byte[WRITE_BUFF_SIZE]; + while ((bytesRead = inputStream.read(buffer, 0, WRITE_BUFF_SIZE)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + } catch (Exception e) { + throw new ExcelAnalysisException("Can not create temporary file!", e); + } finally { + if (outputStream != null) { + try { + outputStream.close(); + } catch (IOException e) { + throw new ExcelAnalysisException("Can not close 'outputStream'!", e); + } + } + } + } + public static void createPoiFilesDirectory() { File poiFilesPathFile = new File(poiFilesPath); createDirectory(poiFilesPathFile); From 8ee438ede89165ac0335db7f5a39e9a8d623ea8f Mon Sep 17 00:00:00 2001 From: hackstep Date: Tue, 30 Mar 2021 18:09:17 +0800 Subject: [PATCH 022/129] =?UTF-8?q?Apache=20POI=20<=204.1.0=20XSSFExportTo?= =?UTF-8?q?Xml=20XXE=20=E6=BC=8F=E6=B4=9E=EF=BC=88CVE-2019-12415=EF=BC=89?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 641dd476..37ca87f0 100644 --- a/pom.xml +++ b/pom.xml @@ -19,6 +19,7 @@ 1.6 true true + 4.1.2 @@ -60,17 +61,17 @@ org.apache.poi poi - 3.17 + ${org.apache.poi} org.apache.poi poi-ooxml - 3.17 + ${org.apache.poi} org.apache.poi poi-ooxml-schemas - 3.17 + ${org.apache.poi} cglib From 412a8bd2d1d550666b811b1ea97f2fdc11f4b3c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=98=AF=E4=BB=AA?= Date: Thu, 8 Apr 2021 20:34:47 +0800 Subject: [PATCH 023/129] =?UTF-8?q?=E6=94=AF=E6=8C=81=E9=9D=9E=E9=A9=BC?= =?UTF-8?q?=E5=B3=B0=E7=9A=84=E5=AD=97=E6=AE=B5=E8=AF=BB=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 20 +++--- .../listener/ModelBuildEventListener.java | 3 +- .../com/alibaba/excel/util/FieldUtils.java | 51 +++++++++++++++ .../com/alibaba/excel/util/StringUtils.java | 62 ++++++++++++++++++- .../write/executor/ExcelWriteAddExecutor.java | 12 ++-- .../test/core/noncamel/UnCamelData.java | 16 +++++ .../core/noncamel/UnCamelDataListener.java | 49 +++++++++++++++ .../test/core/noncamel/UnCamelDataTest.java | 59 ++++++++++++++++++ .../alibaba/easyexcel/test/temp/CamlData.java | 18 ++++++ .../easyexcel/test/temp/Xls03Test.java | 29 +++++++-- update.md | 7 +++ 11 files changed, 301 insertions(+), 25 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/util/FieldUtils.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelData.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataListener.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataTest.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/CamlData.java diff --git a/pom.xml b/pom.xml index 641dd476..06a43371 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 com.alibaba easyexcel - 2.2.7 + 3.0.0-beta1 jar easyexcel @@ -16,7 +16,7 @@ UTF-8 - 1.6 + 1.8 true true @@ -60,22 +60,22 @@ org.apache.poi poi - 3.17 + 4.1.2 org.apache.poi poi-ooxml - 3.17 + 4.1.2 org.apache.poi poi-ooxml-schemas - 3.17 + 4.1.2 cglib cglib - 3.1 + 3.3.0 org.slf4j @@ -85,7 +85,7 @@ org.ehcache ehcache - 3.4.0 + 3.8.1 @@ -179,7 +179,7 @@ com.alibaba.p3c p3c-pmd - 1.3.6 + 2.1.1 @@ -187,8 +187,8 @@ org.apache.maven.plugins maven-compiler-plugin - 1.6 - 1.6 + 1.8 + 1.8 diff --git a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java index 78b57e0a..000e298d 100644 --- a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java +++ b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java @@ -17,6 +17,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.read.metadata.holder.ReadHolder; import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty; import com.alibaba.excel.util.ConverterUtils; +import com.alibaba.excel.util.FieldUtils; import net.sf.cglib.beans.BeanMap; @@ -124,7 +125,7 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener excelContentProperty, currentReadHolder.converterMap(), currentReadHolder.globalConfiguration(), context.readRowHolder().getRowIndex(), index); if (value != null) { - map.put(excelContentProperty.getField().getName(), value); + map.put(FieldUtils.resolveCglibFieldName(excelContentProperty.getField()), value); } } BeanMap.create(resultModel).putAll(map); diff --git a/src/main/java/com/alibaba/excel/util/FieldUtils.java b/src/main/java/com/alibaba/excel/util/FieldUtils.java new file mode 100644 index 00000000..1a4d5287 --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/FieldUtils.java @@ -0,0 +1,51 @@ +package com.alibaba.excel.util; + +import java.lang.reflect.Field; + +/** + * Field utils + * + * @author Jiaju Zhuang + **/ +public class FieldUtils { + + private static final int START_RESOLVE_FIELD_LENGTH = 2; + + /** + * Parsing the name matching cglib。 + *
    + *
      null -> null
    + *
      string1 -> string1
    + *
      String2 -> string2
    + *
      sTring3 -> STring3
    + *
      STring4 -> STring4
    + *
      STRING5 -> STRING5
    + *
      STRing6 -> STRing6
    + *
+ * + * @param field field + * @return field name. + */ + public static String resolveCglibFieldName(Field field) { + if (field == null) { + return null; + } + String fieldName = field.getName(); + if (StringUtils.isBlank(fieldName) || fieldName.length() < START_RESOLVE_FIELD_LENGTH) { + return fieldName; + } + char firstChar = fieldName.charAt(0); + char secondChar = fieldName.charAt(1); + if (Character.isUpperCase(firstChar) == Character.isUpperCase(secondChar)) { + return fieldName; + } + if (Character.isUpperCase(firstChar)) { + return buildFieldName(Character.toLowerCase(firstChar), fieldName); + } + return buildFieldName(Character.toUpperCase(firstChar), fieldName); + } + + private static String buildFieldName(char firstChar, String fieldName) { + return firstChar + fieldName.substring(1); + } +} diff --git a/src/main/java/com/alibaba/excel/util/StringUtils.java b/src/main/java/com/alibaba/excel/util/StringUtils.java index 948ae652..a67e46be 100644 --- a/src/main/java/com/alibaba/excel/util/StringUtils.java +++ b/src/main/java/com/alibaba/excel/util/StringUtils.java @@ -6,11 +6,67 @@ package com.alibaba.excel.util; * @author jipengfei */ public class StringUtils { + private StringUtils() {} + + /** + * A String for a space character. + */ + public static final String SPACE = " "; + + /** + * The empty String {@code ""}. + */ public static final String EMPTY = ""; - private StringUtils() {} + /** + *

Checks if a CharSequence is empty ("") or null.

+ * + *
+     * StringUtils.isEmpty(null)      = true
+     * StringUtils.isEmpty("")        = true
+     * StringUtils.isEmpty(" ")       = false
+     * StringUtils.isEmpty("bob")     = false
+     * StringUtils.isEmpty("  bob  ") = false
+     * 
+ * + *

NOTE: This method changed in Lang version 2.0. + * It no longer trims the CharSequence. + * That functionality is available in isBlank().

+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if the CharSequence is empty or null + */ + public static boolean isEmpty(final CharSequence cs) { + return cs == null || cs.length() == 0; + } - public static boolean isEmpty(Object str) { - return (str == null || EMPTY.equals(str)); + /** + *

Checks if a CharSequence is empty (""), null or whitespace only.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}.

+ * + *
+     * StringUtils.isBlank(null)      = true
+     * StringUtils.isBlank("")        = true
+     * StringUtils.isBlank(" ")       = true
+     * StringUtils.isBlank("bob")     = false
+     * StringUtils.isBlank("  bob  ") = false
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if the CharSequence is null, empty or whitespace only + */ + public static boolean isBlank(final CharSequence cs) { + int strLen; + if (cs == null || (strLen = cs.length()) == 0) { + return true; + } + for (int i = 0; i < strLen; i++) { + if (!Character.isWhitespace(cs.charAt(i))) { + return false; + } + } + return true; } + } diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 9f229029..832cbb8a 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -8,9 +8,6 @@ import java.util.Map; import java.util.Set; import java.util.TreeMap; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; - import com.alibaba.excel.context.WriteContext; import com.alibaba.excel.enums.HeadKindEnum; import com.alibaba.excel.metadata.CellData; @@ -18,15 +15,16 @@ import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.util.ClassUtils; import com.alibaba.excel.util.CollectionUtils; +import com.alibaba.excel.util.FieldUtils; import com.alibaba.excel.util.WorkBookUtil; import com.alibaba.excel.util.WriteHandlerUtils; -import com.alibaba.excel.write.metadata.WriteWorkbook; -import com.alibaba.excel.write.metadata.holder.AbstractWriteHolder; import com.alibaba.excel.write.metadata.holder.WriteHolder; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; import net.sf.cglib.beans.BeanMap; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; /** * Add the data into excel @@ -67,7 +65,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { Row row = WorkBookUtil.createRow(writeContext.writeSheetHolder().getSheet(), n); WriteHandlerUtils.afterRowCreate(writeContext, row, relativeRowIndex, Boolean.FALSE); if (oneRowData instanceof List) { - addBasicTypeToExcel((List) oneRowData, row, relativeRowIndex); + addBasicTypeToExcel((List)oneRowData, row, relativeRowIndex); } else { addJavaObjectToExcel(oneRowData, row, relativeRowIndex, sortedAllFiledMap); } @@ -127,7 +125,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { for (Map.Entry entry : contentPropertyMap.entrySet()) { cellIndex = entry.getKey(); ExcelContentProperty excelContentProperty = entry.getValue(); - String name = excelContentProperty.getField().getName(); + String name = FieldUtils.resolveCglibFieldName(excelContentProperty.getField()); if (!beanMap.containsKey(name)) { continue; } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelData.java b/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelData.java new file mode 100644 index 00000000..dd010fc7 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelData.java @@ -0,0 +1,16 @@ +package com.alibaba.easyexcel.test.core.noncamel; + +import lombok.Data; + +/** + * @author Jiaju Zhuang + */ +@Data +public class UnCamelData { + private String string1; + private String String2; + private String sTring3; + private String STring4; + private String STRING5; + private String STRing6; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataListener.java b/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataListener.java new file mode 100644 index 00000000..2f36d665 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataListener.java @@ -0,0 +1,49 @@ +package com.alibaba.easyexcel.test.core.noncamel; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.event.AnalysisEventListener; +import com.alibaba.fastjson.JSON; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; + +/** + * @author Jiaju Zhuang + */ +@Slf4j +public class UnCamelDataListener extends AnalysisEventListener { + List list = new ArrayList<>(); + + @Override + public void invokeHeadMap(Map headMap, AnalysisContext context) { + log.debug("Head is:{}", JSON.toJSONString(headMap)); + Assert.assertEquals(headMap.get(0), "string1"); + Assert.assertEquals(headMap.get(1), "String2"); + Assert.assertEquals(headMap.get(2), "sTring3"); + Assert.assertEquals(headMap.get(3), "STring4"); + Assert.assertEquals(headMap.get(4), "STRING5"); + Assert.assertEquals(headMap.get(5), "STRing6"); + } + + @Override + public void invoke(UnCamelData data, AnalysisContext context) { + list.add(data); + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + Assert.assertEquals(list.size(), 10); + UnCamelData unCamelData = list.get(0); + Assert.assertEquals(unCamelData.getString1(), "string1"); + Assert.assertEquals(unCamelData.getString2(), "string2"); + Assert.assertEquals(unCamelData.getSTring3(), "string3"); + Assert.assertEquals(unCamelData.getSTring4(), "string4"); + Assert.assertEquals(unCamelData.getSTRING5(), "string5"); + Assert.assertEquals(unCamelData.getSTRing6(), "string6"); + log.debug("First row:{}", JSON.toJSONString(list.get(0))); + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataTest.java new file mode 100644 index 00000000..689c9f8a --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataTest.java @@ -0,0 +1,59 @@ +package com.alibaba.easyexcel.test.core.noncamel; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; + +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +/** + * @author Jiaju Zhuang + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class UnCamelDataTest { + + private static File file07; + private static File file03; + + @BeforeClass + public static void init() { + file07 = TestFileUtil.createNewFile("unCame07.xlsx"); + file03 = TestFileUtil.createNewFile("unCame03.xls"); + } + + @Test + public void t01ReadAndWrite07() { + readAndWrite(file07); + } + + @Test + public void t02ReadAndWrite03() { + readAndWrite(file03); + } + + private void readAndWrite(File file) { + EasyExcel.write(file, UnCamelData.class).sheet().doWrite(data()); + EasyExcel.read(file, UnCamelData.class, new UnCamelDataListener()).sheet().doRead(); + } + + private List data() { + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + UnCamelData unCamelData = new UnCamelData(); + unCamelData.setString1("string1"); + unCamelData.setString2("string2"); + unCamelData.setSTring3("string3"); + unCamelData.setSTring4("string4"); + unCamelData.setSTRING5("string5"); + unCamelData.setSTRing6("string6"); + list.add(unCamelData); + } + return list; + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/CamlData.java b/src/test/java/com/alibaba/easyexcel/test/temp/CamlData.java new file mode 100644 index 00000000..9c3f39e4 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/CamlData.java @@ -0,0 +1,18 @@ +package com.alibaba.easyexcel.test.temp; + +import lombok.Data; + +/** + * TODO + * + * @author 是仪 + */ +@Data +public class CamlData { + private String string1; + private String String2; + private String sTring3; + private String STring4; + private String STRING5; + private String STRing6; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/Xls03Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/Xls03Test.java index c4331b1e..e5d7dfc3 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/Xls03Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/Xls03Test.java @@ -2,14 +2,15 @@ package com.alibaba.easyexcel.test.temp; import java.util.List; +import com.alibaba.excel.EasyExcel; +import com.alibaba.fastjson.JSON; + +import net.sf.cglib.core.DebuggingClassWriter; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import com.alibaba.excel.EasyExcel; -import com.alibaba.excel.EasyExcel; -import com.alibaba.fastjson.JSON; +import org.springframework.cglib.beans.BeanMap; /** * 临时测试 @@ -27,4 +28,24 @@ public class Xls03Test { LOGGER.info("返回数据:{}", JSON.toJSONString(data)); } } + + @Test + public void test2() { + System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true"); + System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, + "/Users/zhuangjiaju/IdeaProjects/easyexcel/target"); + + CamlData camlData = new CamlData(); + //camlData.setTest("test2"); + //camlData.setAEst("test3"); + //camlData.setTEST("test4"); + + BeanMap beanMap = BeanMap.create(camlData); + + LOGGER.info("test:{}", beanMap.get("test")); + LOGGER.info("test:{}", beanMap.get("Test")); + LOGGER.info("test:{}", beanMap.get("TEst")); + LOGGER.info("test:{}", beanMap.get("TEST")); + + } } diff --git a/update.md b/update.md index d7a96f7c..2bc6813b 100644 --- a/update.md +++ b/update.md @@ -1,3 +1,10 @@ +# 3.0.0-beta1 +* 升级jdk8 不再支持jdk6 jdk7 +* 升级poi 到 4.1.2 +* 升级cglib 到 3.3.0 +* 升级ehcache 到 3.8.1 +* 支持非驼峰的字段读写 + # 2.2.7 * 修改07在特殊情况下用`String`接收数字会丢小数位的bug From aae5ff0fdb3c1e7d72d50a44c713bd1c64e93933 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=98=AF=E4=BB=AA?= Date: Thu, 8 Apr 2021 21:39:58 +0800 Subject: [PATCH 024/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D`CellData`=E5=8F=AF?= =?UTF-8?q?=E8=83=BD=E4=B8=8D=E8=BF=94=E5=9B=9E=E8=A1=8C=E5=88=97=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/excel/metadata/CellData.java | 2 + .../easyexcel/test/temp/WriteLargeTest.java | 75 ++++++++----------- .../test/temp/large/TempLargeDataTest.java | 26 ++++++- .../easyexcel/test/temp/simple/Wirte.java | 24 ++++-- .../test/temp/simple/WriteCellHandler.java | 39 ++++++++++ .../easyexcel/test/temp/simple/WriteData.java | 4 +- 6 files changed, 115 insertions(+), 55 deletions(-) create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java diff --git a/src/main/java/com/alibaba/excel/metadata/CellData.java b/src/main/java/com/alibaba/excel/metadata/CellData.java index 2124e103..ac18fb8a 100644 --- a/src/main/java/com/alibaba/excel/metadata/CellData.java +++ b/src/main/java/com/alibaba/excel/metadata/CellData.java @@ -53,6 +53,8 @@ public class CellData extends AbstractCell { this.dataFormat = other.dataFormat; this.dataFormatString = other.dataFormatString; this.data = other.data; + setRowIndex(other.getRowIndex()); + setColumnIndex(other.getColumnIndex()); } public CellData() {} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/WriteLargeTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/WriteLargeTest.java index 008d7629..23f623b6 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/WriteLargeTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/WriteLargeTest.java @@ -3,18 +3,7 @@ package com.alibaba.easyexcel.test.temp; 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.HorizontalAlignment; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alibaba.easyexcel.test.core.large.LargeData; -import com.alibaba.easyexcel.test.demo.write.DemoData; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; @@ -23,6 +12,13 @@ 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.FillPatternType; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.junit.Ignore; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * 临时测试 * @@ -59,8 +55,23 @@ public class WriteLargeTest { HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle); + ExcelWriter excelWriter = EasyExcel.write(fileName, LargeData.class).registerWriteHandler( + horizontalCellStyleStrategy).build(); + WriteSheet writeSheet = EasyExcel.writerSheet().build(); + for (int j = 0; j < 100; j++) { + excelWriter.write(data(), writeSheet); + LOGGER.info("{} fill success.", j); + } + excelWriter.finish(); - ExcelWriter excelWriter = EasyExcel.write(fileName,LargeData.class).registerWriteHandler(horizontalCellStyleStrategy).build(); + } + + @Test + public void test2() throws Exception { + // 方法2 如果写到不同的sheet 同一个对象 + String fileName = TestFileUtil.getPath() + "large" + System.currentTimeMillis() + ".xlsx"; + + ExcelWriter excelWriter = EasyExcel.write(fileName, LargeData.class).build(); WriteSheet writeSheet = EasyExcel.writerSheet().build(); for (int j = 0; j < 100; j++) { excelWriter.write(data(), writeSheet); @@ -70,39 +81,17 @@ public class WriteLargeTest { } + private List> data() { + List> list = new ArrayList<>(); - private List data() { - List list = new ArrayList(); - int size = i + 5000; - for (; i < size; i++) { - LargeData largeData = new LargeData(); - list.add(largeData); - largeData.setStr1("str1-" + i); - largeData.setStr2("str2-" + i); - largeData.setStr3("str3-" + i); - largeData.setStr4("str4-" + i); - largeData.setStr5("str5-" + i); - largeData.setStr6("str6-" + i); - largeData.setStr7("str7-" + i); - largeData.setStr8("str8-" + i); - largeData.setStr9("str9-" + i); - largeData.setStr10("str10-" + i); - largeData.setStr11("str11-" + i); - largeData.setStr12("str12-" + i); - largeData.setStr13("str13-" + i); - largeData.setStr14("str14-" + i); - largeData.setStr15("str15-" + i); - largeData.setStr16("str16-" + i); - largeData.setStr17("str17-" + i); - largeData.setStr18("str18-" + i); - largeData.setStr19("str19-" + i); - largeData.setStr20("str20-" + i); - largeData.setStr21("str21-" + i); - largeData.setStr22("str22-" + i); - largeData.setStr23("str23-" + i); - largeData.setStr24("str24-" + i); - largeData.setStr25("str25-" + i); + for (int j = 0; j < 10000; j++) { + List oneRow = new ArrayList<>(); + for (int i = 0; i < 150; i++) { + oneRow.add("这是测试字段" + i); + } + list.add(oneRow); } + return list; } } diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/large/TempLargeDataTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/large/TempLargeDataTest.java index 0bde12ef..7f4a6717 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/large/TempLargeDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/large/TempLargeDataTest.java @@ -1,16 +1,19 @@ package com.alibaba.easyexcel.test.temp.large; +import java.io.File; import java.io.FileInputStream; +import java.lang.reflect.Field; +import com.alibaba.easyexcel.test.core.large.LargeDataTest; +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; + +import org.apache.poi.openxml4j.util.ZipSecureFile; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.alibaba.easyexcel.test.core.large.LargeDataTest; -import com.alibaba.easyexcel.test.util.TestFileUtil; -import com.alibaba.excel.EasyExcel; - /** * @author Jiaju Zhuang */ @@ -29,9 +32,24 @@ public class TempLargeDataTest { @Test public void noModelRead() throws Exception { + ZipSecureFile.setMaxEntrySize(Long.MAX_VALUE); long start = System.currentTimeMillis(); EasyExcel.read(TestFileUtil.readUserHomeFile("test/ld.xlsx"), new NoModelLargeDataListener()) .sheet().doRead(); LOGGER.info("Large data total time spent:{}", System.currentTimeMillis() - start); } + + @Test + public void noModelRead2() throws Exception { + Field field = ZipSecureFile.class.getDeclaredField("MAX_ENTRY_SIZE"); + field.setAccessible(true); + field.set(null, Long.MAX_VALUE); + + long start = System.currentTimeMillis(); + EasyExcel.read( + new File("/Users/zhuangjiaju/IdeaProjects/easyexcel/target/test-classes/large1617887262709.xlsx"), + new NoModelLargeDataListener()) + .sheet().doRead(); + LOGGER.info("Large data total time spent:{}", System.currentTimeMillis() - start); + } } diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/simple/Wirte.java b/src/test/java/com/alibaba/easyexcel/test/temp/simple/Wirte.java index ffabd105..2a907c30 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/simple/Wirte.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/simple/Wirte.java @@ -5,11 +5,6 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alibaba.easyexcel.test.core.large.LargeData; import com.alibaba.easyexcel.test.demo.write.DemoData; import com.alibaba.easyexcel.test.util.TestFileUtil; @@ -20,6 +15,10 @@ import com.alibaba.excel.write.metadata.WriteTable; import com.alibaba.fastjson.JSON; import net.sf.cglib.beans.BeanMap; +import org.junit.Ignore; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * 测试poi @@ -56,7 +55,18 @@ public class Wirte { String fileName = TestFileUtil.getPath() + "t22" + System.currentTimeMillis() + ".xlsx"; // 这里 需要指定写用哪个class去读,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 // 如果这里想使用03 则 传入excelType参数即可 - EasyExcel.write(fileName, WriteData.class).sheet("模板").registerWriteHandler(new WriteHandler()).doWrite(data1()); + EasyExcel.write(fileName, WriteData.class).sheet("模板").registerWriteHandler(new WriteHandler()).doWrite( + data1()); + } + + @Test + public void simpleWrite3() { + // 写法1 + String fileName = TestFileUtil.getPath() + "t33" + System.currentTimeMillis() + ".xlsx"; + // 这里 需要指定写用哪个class去读,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 + // 如果这里想使用03 则 传入excelType参数即可 + EasyExcel.write(fileName).head(head()).inMemory(true).sheet("模板").registerWriteHandler(new WriteCellHandler()).doWrite( + data1()); } @Test @@ -125,7 +135,7 @@ public class Wirte { List list = new ArrayList(); for (int i = 0; i < 10; i++) { WriteData data = new WriteData(); - data.setF(300.35f); + data.setDd(new Date()); data.setF1(33f); list.add(data); } diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java b/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java new file mode 100644 index 00000000..726915e7 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java @@ -0,0 +1,39 @@ +package com.alibaba.easyexcel.test.temp.simple; + +import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.Head; +import com.alibaba.excel.write.handler.AbstractCellWriteHandler; +import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; +import com.alibaba.excel.write.metadata.holder.WriteTableHolder; + +import lombok.extern.slf4j.Slf4j; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.CreationHelper; +import org.apache.poi.ss.usermodel.DataFormat; +import org.apache.poi.ss.usermodel.IndexedColors; + +/** + * @author Jiaju Zhuang + */ +@Slf4j +public class WriteCellHandler extends AbstractCellWriteHandler { + + @Override + public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, + CellData cellData, Cell cell, Head head, Integer integer, Boolean isHead) { + + if (!isHead) { + CreationHelper createHelper = writeSheetHolder.getSheet().getWorkbook().getCreationHelper(); + CellStyle cellStyle = writeSheetHolder.getSheet().getWorkbook().createCellStyle(); + if (cellStyle != null) { + DataFormat dataFormat = createHelper.createDataFormat(); + cellStyle.setWrapText(true); + cellStyle.setFillBackgroundColor(IndexedColors.RED.getIndex()); + cellStyle.setBottomBorderColor(IndexedColors.RED.getIndex()); + cellStyle.setDataFormat(dataFormat.getFormat("yyyy-MM-dd")); + cell.setCellStyle(cellStyle); + } + } + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteData.java b/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteData.java index 2b25bb0a..27967b9f 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteData.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteData.java @@ -1,5 +1,7 @@ package com.alibaba.easyexcel.test.temp.simple; +import java.util.Date; + import com.alibaba.excel.annotation.write.style.ContentStyle; import lombok.Data; @@ -12,7 +14,7 @@ import lombok.Data; @Data public class WriteData { // @ContentStyle(locked = true) - private float f; + private Date dd; // @ContentStyle(locked = false) private float f1; } From 1cd05d40d996293a8f56b21491806881203559bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=98=AF=E4=BB=AA?= Date: Thu, 8 Apr 2021 21:40:03 +0800 Subject: [PATCH 025/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D`CellData`=E5=8F=AF?= =?UTF-8?q?=E8=83=BD=E4=B8=8D=E8=BF=94=E5=9B=9E=E8=A1=8C=E5=88=97=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- update.md | 1 + 1 file changed, 1 insertion(+) diff --git a/update.md b/update.md index 2bc6813b..9e739d52 100644 --- a/update.md +++ b/update.md @@ -4,6 +4,7 @@ * 升级cglib 到 3.3.0 * 升级ehcache 到 3.8.1 * 支持非驼峰的字段读写 +* 修复`CellData`可能不返回行列号 [Issue #1832](https://github.com/alibaba/easyexcel/issues/1832) # 2.2.7 * 修改07在特殊情况下用`String`接收数字会丢小数位的bug From a5730593dcfcb3ec03148d4a41f2aea7becc0c04 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 10:51:18 +0800 Subject: [PATCH 026/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9demo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../easyexcel/test/demo/read/DemoExtraListener.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoExtraListener.java b/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoExtraListener.java index 01adfe72..df2afc36 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoExtraListener.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/read/DemoExtraListener.java @@ -1,19 +1,18 @@ package com.alibaba.easyexcel.test.demo.read; -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.excel.metadata.CellExtra; import com.alibaba.fastjson.JSON; +import org.junit.Assert; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * 读取单元格的批注 * - * @author: kaiux - * @date: 2019-10-23 14:10 + * @author Jiaju Zhuang **/ public class DemoExtraListener extends AnalysisEventListener { private static final Logger LOGGER = LoggerFactory.getLogger(DemoDataListener.class); From df0f51385ef5e0ec43ac71b5e2a7e1a7346cfd0d Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 10:51:46 +0800 Subject: [PATCH 027/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index b645e4c5..06a43371 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,6 @@ 1.8 true true - 4.1.2 From 5d25eb7073b178fc9f6223b0d4dc0f78eb6831a6 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 11:21:01 +0800 Subject: [PATCH 028/129] =?UTF-8?q?Revert=20"easyexcel=E6=95=B4=E4=BD=93?= =?UTF-8?q?=E8=A6=86=E7=9B=96=E7=8E=87=E6=8F=90=E5=8D=873%"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- easyexcel | 1 - .../test/core/style/AnnotationStyleData.java | 21 ----- .../test/core/style/LoopMergeData.java | 17 ---- .../core/style/OnceAbsoluteMergeData.java | 19 ----- .../SimpleVerticalCellStyleStrategy.java | 52 ------------ .../test/core/style/StyleDataTest.java | 80 ------------------- 6 files changed, 190 deletions(-) delete mode 160000 easyexcel delete mode 100644 src/test/java/com/alibaba/easyexcel/test/core/style/AnnotationStyleData.java delete mode 100644 src/test/java/com/alibaba/easyexcel/test/core/style/LoopMergeData.java delete mode 100644 src/test/java/com/alibaba/easyexcel/test/core/style/OnceAbsoluteMergeData.java delete mode 100644 src/test/java/com/alibaba/easyexcel/test/core/style/SimpleVerticalCellStyleStrategy.java diff --git a/easyexcel b/easyexcel deleted file mode 160000 index 4076b897..00000000 --- a/easyexcel +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 4076b897953b18f9e96c278c6929325e89f2be12 diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/AnnotationStyleData.java b/src/test/java/com/alibaba/easyexcel/test/core/style/AnnotationStyleData.java deleted file mode 100644 index dd5dac60..00000000 --- a/src/test/java/com/alibaba/easyexcel/test/core/style/AnnotationStyleData.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.alibaba.easyexcel.test.core.style; - -import com.alibaba.excel.annotation.ExcelProperty; -import com.alibaba.excel.annotation.write.style.ContentFontStyle; -import com.alibaba.excel.annotation.write.style.ContentStyle; -import lombok.Data; - -/** - * @author Pengliang Zhao - */ -@Data -public class AnnotationStyleData { - @ContentStyle(dataFormat = (short)1, rotation = (short)1, indent = (short)1, leftBorderColor = (short)1, - rightBorderColor = (short)1, topBorderColor = (short)1, bottomBorderColor = (short)1, - fillForegroundColor = (short)1, fillBackgroundColor = (short)1) - @ContentFontStyle(fontHeightInPoints = (short)1, color = (short)1, typeOffset = (short)1, charset = (short)1) - @ExcelProperty("字符串") - private String string; - @ExcelProperty("字符串1") - private String string1; -} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/LoopMergeData.java b/src/test/java/com/alibaba/easyexcel/test/core/style/LoopMergeData.java deleted file mode 100644 index 77c5363f..00000000 --- a/src/test/java/com/alibaba/easyexcel/test/core/style/LoopMergeData.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.alibaba.easyexcel.test.core.style; - -import com.alibaba.excel.annotation.ExcelProperty; -import lombok.Data; - -/** - * @author Pengliang Zhao - */ -@Data -public class LoopMergeData { - @ExcelProperty(value = "洗漱种类", index = 0) - private String category; - @ExcelProperty(value = "毛巾名称", index = 1) - private String towel; - @ExcelProperty(value = "毛巾尺寸", index = 2) - private String size; -} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/OnceAbsoluteMergeData.java b/src/test/java/com/alibaba/easyexcel/test/core/style/OnceAbsoluteMergeData.java deleted file mode 100644 index 09de338c..00000000 --- a/src/test/java/com/alibaba/easyexcel/test/core/style/OnceAbsoluteMergeData.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.alibaba.easyexcel.test.core.style; - -import com.alibaba.excel.annotation.ExcelProperty; -import com.alibaba.excel.annotation.write.style.OnceAbsoluteMerge; -import lombok.Data; - -/** - * @author Pengliang Zhao - */ -@Data -@OnceAbsoluteMerge(firstRowIndex = (short)0, lastRowIndex = (short)2, firstColumnIndex = (short)0, lastColumnIndex = (short)2) -public class OnceAbsoluteMergeData { - @ExcelProperty(value = "洗漱种类", index = 0) - private String category; - @ExcelProperty(value = "毛巾名称", index = 1) - private String towel; - @ExcelProperty(value = "毛巾尺寸", index = 2) - private String size; -} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/SimpleVerticalCellStyleStrategy.java b/src/test/java/com/alibaba/easyexcel/test/core/style/SimpleVerticalCellStyleStrategy.java deleted file mode 100644 index 9f4d3ac2..00000000 --- a/src/test/java/com/alibaba/easyexcel/test/core/style/SimpleVerticalCellStyleStrategy.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.alibaba.easyexcel.test.core.style; - -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.IndexedColors; - -import com.alibaba.excel.annotation.write.style.ContentFontStyle; -import com.alibaba.excel.annotation.write.style.ContentStyle; -import com.alibaba.excel.metadata.Head; -import com.alibaba.excel.metadata.property.FontProperty; -import com.alibaba.excel.metadata.property.StyleProperty; -import com.alibaba.excel.write.metadata.style.WriteCellStyle; -import com.alibaba.excel.write.metadata.style.WriteFont; -import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy; - -/** - * @author Pengliang Zhao - */ -public class SimpleVerticalCellStyleStrategy extends AbstractVerticalCellStyleStrategy { - private StyleProperty styleProperty = StyleProperty.build(AnnotationStyleData.class.getAnnotation(ContentStyle.class)); - private FontProperty fontProperty = FontProperty.build(AnnotationStyleData.class.getAnnotation(ContentFontStyle.class)); - - @Override - protected WriteCellStyle headCellStyle(Head head) { - WriteCellStyle writeCellStyle = WriteCellStyle.build(styleProperty, fontProperty); - if (head.getColumnIndex() == 0) { - writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); - WriteFont writeFont = new WriteFont(); - writeFont.setItalic(true); - writeFont.setStrikeout(true); - writeFont.setTypeOffset(Font.SS_NONE); - writeFont.setUnderline(Font.U_DOUBLE); - writeFont.setBold(true); - writeFont.setCharset((int)Font.DEFAULT_CHARSET); - } else { - writeCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex()); - } - return writeCellStyle; - } - - @Override - protected WriteCellStyle contentCellStyle(Head head) { - WriteCellStyle writeCellStyle = new WriteCellStyle(); - writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); - if (head.getColumnIndex() == 0) { - writeCellStyle.setFillForegroundColor(IndexedColors.DARK_GREEN.getIndex()); - } else { - writeCellStyle.setFillForegroundColor(IndexedColors.PINK.getIndex()); - } - return writeCellStyle; - } -} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java index dc61c933..4e170944 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java @@ -17,17 +17,13 @@ import org.junit.runners.MethodSorters; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; -import com.alibaba.excel.annotation.write.style.OnceAbsoluteMerge; import com.alibaba.excel.metadata.Head; -import com.alibaba.excel.metadata.property.LoopMergeProperty; -import com.alibaba.excel.metadata.property.OnceAbsoluteMergeProperty; import com.alibaba.excel.write.merge.LoopMergeStrategy; import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy; import com.alibaba.excel.write.metadata.style.WriteCellStyle; import com.alibaba.excel.write.metadata.style.WriteFont; import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy; -import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy; import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy; import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy; @@ -40,19 +36,11 @@ public class StyleDataTest { private static File file07; private static File file03; - private static File file04; - private static File file05; - private static File file06; - private static File file08; @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("style07.xlsx"); file03 = TestFileUtil.createNewFile("style03.xls"); - file04 = TestFileUtil.createNewFile("simpleVerticalCellStyleStrategy01.xls"); - file05 = TestFileUtil.createNewFile("longestMatchColumnWidthStyleStrategy01.xls"); - file06 = TestFileUtil.createNewFile("loopMergeStrategy01.xls"); - file08 = TestFileUtil.createNewFile("onceAbsoluteMergeStrategy01.xls"); } @Test @@ -129,37 +117,6 @@ public class StyleDataTest { .doWrite(data10()); } - @Test - public void t05AbstractVerticalCellStyleStrategy03() { - AbstractVerticalCellStyleStrategy verticalCellStyleStrategy = new SimpleVerticalCellStyleStrategy(); - EasyExcel.write(file04, AnnotationStyleData.class).registerWriteHandler(verticalCellStyleStrategy).sheet() - .doWrite(data1()); - } - - @Test - public void t06longestMatchColumnWidthStyleStrategy() { - EasyExcel.write(file05, StyleData.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) - .sheet("模板").doWrite(data()); - } - - @Test - public void t07loopMergeStrategy() { - LoopMergeProperty loopMergeProperty = new LoopMergeProperty(1, 2); - loopMergeProperty.setEachRow(2); - loopMergeProperty.setColumnExtend(1); - EasyExcel.write(file06, LoopMergeData.class).registerWriteHandler(new LoopMergeStrategy(loopMergeProperty, 1)) - .sheet("模板").doWrite(data2()); - } - - @Test - public void to8onceAbsoluteMergeStrategy() { - OnceAbsoluteMerge onceAbsoluteMerge = OnceAbsoluteMergeData.class.getAnnotation(OnceAbsoluteMerge.class); - OnceAbsoluteMergeProperty onceAbsoluteMergeProperty = OnceAbsoluteMergeProperty.build(onceAbsoluteMerge); - OnceAbsoluteMergeStrategy onceAbsoluteMergeStrategy = new OnceAbsoluteMergeStrategy(onceAbsoluteMergeProperty); - EasyExcel.write(file08, OnceAbsoluteMergeData.class).registerWriteHandler(onceAbsoluteMergeStrategy).sheet("模板") - .doWrite(data3()); - } - private void readAndWrite(File file) { SimpleColumnWidthStyleStrategy simpleColumnWidthStyleStrategy = new SimpleColumnWidthStyleStrategy(50); SimpleRowHeightStyleStrategy simpleRowHeightStyleStrategy = @@ -199,43 +156,6 @@ public class StyleDataTest { return list; } - private List data1() { - List list = new ArrayList(); - AnnotationStyleData data = new AnnotationStyleData(); - data.setString("字符串0"); - data.setString1("字符串01"); - AnnotationStyleData data1 = new AnnotationStyleData(); - data1.setString("字符串1"); - data1.setString1("字符串11"); - list.add(data); - list.add(data1); - return list; - } - - private List data2() { - List list = new ArrayList(); - for (int i = 0; i <= 5; i++) { - LoopMergeData loopMergeData = new LoopMergeData(); - loopMergeData.setCategory("洗漱用品"); - loopMergeData.setTowel("毛巾"); - loopMergeData.setSize("10" + i + "#"); - list.add(loopMergeData); - } - return list; - } - - private List data3() { - List list = new ArrayList(); - for (int i = 0; i <= 5; i++) { - OnceAbsoluteMergeData onceAbsoluteMergeData = new OnceAbsoluteMergeData(); - onceAbsoluteMergeData.setCategory("洗漱用品"); - onceAbsoluteMergeData.setTowel("毛巾"); - onceAbsoluteMergeData.setSize("10" + i + "#"); - list.add(onceAbsoluteMergeData); - } - return list; - } - private List data10() { List list = new ArrayList(); for (int i = 0; i < 10; i++) { From 4b7ef26a46d680858d97eda26c3db7b7f0cac012 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 13:46:24 +0800 Subject: [PATCH 029/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E6=8C=87=E5=AE=9A=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- .../java/com/alibaba/easyexcel/test/demo/web/WebTest.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5418de1f..9664d654 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ DEMO代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/ja // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系 String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); - EasyExcel.write(response.getOutputStream(), DownloadData.class).excelType(ExcelTypeEnum.XLSX).sheet("模板").doWrite(data()); + EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data()); } /** diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java index e2c14137..0a147564 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java @@ -49,7 +49,7 @@ public class WebTest { // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系 String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); - EasyExcel.write(response.getOutputStream(), DownloadData.class).excelType(ExcelTypeEnum.XLSX).sheet("模板").doWrite(data()); + EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data()); } /** @@ -67,7 +67,7 @@ public class WebTest { String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); // 这里需要设置不关闭流 - EasyExcel.write(response.getOutputStream(), DownloadData.class).excelType(ExcelTypeEnum.XLSX).autoCloseStream(Boolean.FALSE).sheet("模板") + EasyExcel.write(response.getOutputStream(), DownloadData.class).autoCloseStream(Boolean.FALSE).sheet("模板") .doWrite(data()); } catch (Exception e) { // 重置response From b82861f3e04fe4c64ee9ea43d377b1e89afc8b32 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 13:50:01 +0800 Subject: [PATCH 030/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../style/column/LongestMatchColumnWidthStyleStrategy.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java index a00d63d7..cc8dcb20 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java @@ -33,12 +33,6 @@ public class LongestMatchColumnWidthStyleStrategy extends AbstractColumnWidthSty if (!needSetWidth) { return; } - - //LongestMatchColumnWidthStyleStrategy设置列宽BUG:与spring集成时 ,由于bean是单例,CACHE内容不会改变,同一个报表只有第一次调用会动态设置列宽 - if (cell.getRowIndex() == 0 && cell.getColumnIndex() == 0) { - CACHE.clear(); - } - Map maxColumnWidthMap = cache.get(writeSheetHolder.getSheetNo()); if (maxColumnWidthMap == null) { maxColumnWidthMap = new HashMap(16); From b2102159c76698af03cb7a4c0d94b1ba9a4a7bab Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 14:04:54 +0800 Subject: [PATCH 031/129] =?UTF-8?q?=E5=88=A0=E9=99=A4=E9=9B=86=E5=90=88?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- .../excel/analysis/ExcelAnalyserImpl.java | 2 +- .../excel/analysis/v07/XlsxSaxAnalyser.java | 2 +- .../analysis/v07/handlers/RowTagHandler.java | 11 +++---- .../java/com/alibaba/excel/cache/Ehcache.java | 30 ++++++++++-------- .../metadata/property/ExcelHeadProperty.java | 2 +- .../alibaba/excel/util/CollectionUtils.java | 22 ------------- .../write/executor/ExcelWriteAddExecutor.java | 2 +- .../executor/ExcelWriteFillExecutor.java | 19 ++++++----- .../metadata/holder/AbstractWriteHolder.java | 2 +- .../LongestMatchColumnWidthStyleStrategy.java | 2 +- .../easyexcel/test/demo/fill/FillTest.java | 18 ----------- src/test/resources/demo/fill/no_variable.xlsx | Bin 9946 -> 0 bytes 13 files changed, 37 insertions(+), 77 deletions(-) delete mode 100644 src/main/java/com/alibaba/excel/util/CollectionUtils.java delete mode 100644 src/test/resources/demo/fill/no_variable.xlsx diff --git a/pom.xml b/pom.xml index d03e18d1..01efe344 100644 --- a/pom.xml +++ b/pom.xml @@ -179,7 +179,7 @@ com.alibaba.p3c p3c-pmd - 2.1.1 + 1.3.6
diff --git a/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java b/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java index 5487ee10..e049dbfc 100644 --- a/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java +++ b/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java @@ -3,6 +3,7 @@ package com.alibaba.excel.analysis; import java.io.InputStream; import java.util.List; +import org.apache.commons.collections4.CollectionUtils; import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.poifs.crypt.Decryptor; import org.apache.poi.poifs.filesystem.DocumentFactoryHelper; @@ -26,7 +27,6 @@ import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder; import com.alibaba.excel.read.metadata.holder.xls.XlsReadWorkbookHolder; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadWorkbookHolder; import com.alibaba.excel.support.ExcelTypeEnum; -import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.DateUtils; import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.util.NumberDataFormatterUtils; diff --git a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java index a0a9af0e..dbe4e3ab 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java @@ -12,6 +12,7 @@ import java.util.UUID; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import org.apache.commons.collections4.CollectionUtils; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackageAccess; import org.apache.poi.openxml4j.opc.PackagePart; @@ -37,7 +38,6 @@ import com.alibaba.excel.exception.ExcelAnalysisException; import com.alibaba.excel.metadata.CellExtra; import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadWorkbookHolder; -import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.util.SheetUtils; import com.alibaba.excel.util.StringUtils; diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/RowTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/RowTagHandler.java index 877c6a5f..37965254 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/RowTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/RowTagHandler.java @@ -2,17 +2,17 @@ package com.alibaba.excel.analysis.v07.handlers; import java.util.LinkedHashMap; -import org.xml.sax.Attributes; - import com.alibaba.excel.constant.ExcelXmlConstants; import com.alibaba.excel.context.xlsx.XlsxReadContext; import com.alibaba.excel.enums.RowTypeEnum; import com.alibaba.excel.metadata.Cell; import com.alibaba.excel.read.metadata.holder.ReadRowHolder; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder; -import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.PositionUtils; +import org.apache.commons.collections4.MapUtils; +import org.xml.sax.Attributes; + /** * Cell Handler * @@ -40,13 +40,12 @@ public class RowTagHandler extends AbstractXlsxTagHandler { @Override public void endElement(XlsxReadContext xlsxReadContext, String name) { XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder(); - RowTypeEnum rowType = - CollectionUtils.isEmpty(xlsxReadSheetHolder.getCellMap()) ? RowTypeEnum.EMPTY : RowTypeEnum.DATA; + RowTypeEnum rowType = MapUtils.isEmpty(xlsxReadSheetHolder.getCellMap()) ? RowTypeEnum.EMPTY : RowTypeEnum.DATA; xlsxReadContext.readRowHolder(new ReadRowHolder(xlsxReadSheetHolder.getRowIndex(), rowType, xlsxReadSheetHolder.getGlobalConfiguration(), xlsxReadSheetHolder.getCellMap())); xlsxReadContext.analysisEventProcessor().endRow(xlsxReadContext); xlsxReadSheetHolder.setColumnIndex(null); - xlsxReadSheetHolder.setCellMap(new LinkedHashMap()); + xlsxReadSheetHolder.setCellMap(new LinkedHashMap<>()); } } diff --git a/src/main/java/com/alibaba/excel/cache/Ehcache.java b/src/main/java/com/alibaba/excel/cache/Ehcache.java index 4e757fcd..f5bc5ff6 100644 --- a/src/main/java/com/alibaba/excel/cache/Ehcache.java +++ b/src/main/java/com/alibaba/excel/cache/Ehcache.java @@ -2,8 +2,11 @@ package com.alibaba.excel.cache; import java.io.File; import java.util.HashMap; +import java.util.Map; import java.util.UUID; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; import org.ehcache.CacheManager; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; @@ -14,7 +17,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.excel.context.AnalysisContext; -import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.FileUtils; /** @@ -32,11 +34,11 @@ public class Ehcache implements ReadCache { * Key index */ private int index = 0; - private HashMap dataMap = new HashMap(BATCH_COUNT * 4 / 3 + 1); - private static CacheManager fileCacheManager; - private static CacheConfiguration fileCacheConfiguration; - private static CacheManager activeCacheManager; - private CacheConfiguration activeCacheConfiguration; + private HashMap dataMap = new HashMap<>(BATCH_COUNT * 4 / 3 + 1); + private static final CacheManager FILE_CACHE_MANAGER; + private static final CacheConfiguration FILE_CACHE_CONFIGURATION; + private static final CacheManager ACTIVE_CACHE_MANAGER; + private final CacheConfiguration activeCacheConfiguration; /** * Bulk storage data */ @@ -61,10 +63,10 @@ public class Ehcache implements ReadCache { static { File cacheFile = FileUtils.createCacheTmpFile(); - fileCacheManager = + FILE_CACHE_MANAGER = CacheManagerBuilder.newCacheManagerBuilder().with(CacheManagerBuilder.persistence(cacheFile)).build(true); - activeCacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true); - fileCacheConfiguration = CacheConfigurationBuilder + ACTIVE_CACHE_MANAGER = CacheManagerBuilder.newCacheManagerBuilder().build(true); + FILE_CACHE_CONFIGURATION = CacheConfigurationBuilder .newCacheConfigurationBuilder(Integer.class, HashMap.class, ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MemoryUnit.GB)) .withSizeOfMaxObjectGraph(1000 * 1000L).withSizeOfMaxObjectSize(10, MemoryUnit.GB).build(); @@ -73,8 +75,8 @@ public class Ehcache implements ReadCache { @Override public void init(AnalysisContext analysisContext) { cacheAlias = UUID.randomUUID().toString(); - fileCache = fileCacheManager.createCache(cacheAlias, fileCacheConfiguration); - activeCache = activeCacheManager.createCache(cacheAlias, activeCacheConfiguration); + fileCache = FILE_CACHE_MANAGER.createCache(cacheAlias, FILE_CACHE_CONFIGURATION); + activeCache = ACTIVE_CACHE_MANAGER.createCache(cacheAlias, activeCacheConfiguration); } @Override @@ -113,7 +115,7 @@ public class Ehcache implements ReadCache { @Override public void putFinished() { - if (CollectionUtils.isEmpty(dataMap)) { + if (MapUtils.isEmpty(dataMap)) { return; } fileCache.put(index / BATCH_COUNT, dataMap); @@ -121,8 +123,8 @@ public class Ehcache implements ReadCache { @Override public void destroy() { - fileCacheManager.removeCache(cacheAlias); - activeCacheManager.removeCache(cacheAlias); + FILE_CACHE_MANAGER.removeCache(cacheAlias); + ACTIVE_CACHE_MANAGER.removeCache(cacheAlias); } } diff --git a/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java b/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java index a191260d..878e8c0d 100644 --- a/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java +++ b/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java @@ -8,6 +8,7 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; +import org.apache.commons.collections4.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,7 +22,6 @@ import com.alibaba.excel.exception.ExcelCommonException; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Holder; import com.alibaba.excel.util.ClassUtils; -import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.write.metadata.holder.AbstractWriteHolder; diff --git a/src/main/java/com/alibaba/excel/util/CollectionUtils.java b/src/main/java/com/alibaba/excel/util/CollectionUtils.java deleted file mode 100644 index f413be17..00000000 --- a/src/main/java/com/alibaba/excel/util/CollectionUtils.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.alibaba.excel.util; - -import java.util.Collection; -import java.util.Map; - -/** - * Collection utils - * - * @author jipengfei - */ -public class CollectionUtils { - - private CollectionUtils() {} - - public static boolean isEmpty(Collection collection) { - return (collection == null || collection.isEmpty()); - } - - public static boolean isEmpty(Map map) { - return (map == null || map.isEmpty()); - } -} diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 832cbb8a..6e99a9a9 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -14,7 +14,6 @@ import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.util.ClassUtils; -import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.FieldUtils; import com.alibaba.excel.util.WorkBookUtil; import com.alibaba.excel.util.WriteHandlerUtils; @@ -23,6 +22,7 @@ import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; import net.sf.cglib.beans.BeanMap; +import org.apache.commons.collections4.CollectionUtils; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 4bfd06fc..b2f3362b 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -9,12 +9,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; - import com.alibaba.excel.context.WriteContext; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.WriteDirectionEnum; @@ -22,7 +16,6 @@ import com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum; import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; -import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.util.WriteHandlerUtils; import com.alibaba.excel.write.metadata.fill.AnalysisCell; @@ -31,6 +24,12 @@ import com.alibaba.excel.write.metadata.fill.FillWrapper; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import net.sf.cglib.beans.BeanMap; +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.CellType; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; /** * Fill the data into excel @@ -179,6 +178,9 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { private void doFill(List analysisCellList, Object oneRowData, FillConfig fillConfig, Integer relativeRowIndex) { + if (CollectionUtils.isEmpty(analysisCellList)) { + return; + } Map dataMap; if (oneRowData instanceof Map) { dataMap = (Map) oneRowData; @@ -188,9 +190,6 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { WriteSheetHolder writeSheetHolder = writeContext.writeSheetHolder(); Map fieldNameContentPropertyMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getFieldNameContentPropertyMap(); - if(null == analysisCellList || analysisCellList.isEmpty()){ - return; - } for (AnalysisCell analysisCell : analysisCellList) { Cell cell = getOneCell(analysisCell, fillConfig); if (analysisCell.getOnlyOneVariable()) { diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java index 0fced0b5..6ba2c593 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java @@ -9,6 +9,7 @@ import java.util.Map; import java.util.Set; import java.util.TreeMap; +import org.apache.commons.collections4.CollectionUtils; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.IndexedColors; @@ -25,7 +26,6 @@ import com.alibaba.excel.metadata.TableStyle; import com.alibaba.excel.metadata.property.LoopMergeProperty; import com.alibaba.excel.metadata.property.OnceAbsoluteMergeProperty; import com.alibaba.excel.metadata.property.RowHeightProperty; -import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.handler.DefaultWriteHandlerLoader; import com.alibaba.excel.write.handler.RowWriteHandler; diff --git a/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java index cc8dcb20..717077dc 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java @@ -4,12 +4,12 @@ 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.CellData; import com.alibaba.excel.metadata.Head; -import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; /** diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java index 3c77ba78..7a0e92e5 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java @@ -80,24 +80,6 @@ public class FillTest { excelWriter.finish(); } - /** - * 处理无变量问题 - * - * @since 2.1.1 - */ - @Test - public void noVariableFill() { - // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替 - // 填充list 的时候还要注意 模板中{.} 多了个点 表示list - String templateFileName = - TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "no_variable.xlsx"; - - // 方案1 一下子全部放到内存里面 并填充 - String fileName = TestFileUtil.getPath() + "listFill" + System.currentTimeMillis() + ".xlsx"; - // 这里 会填充到第一个sheet, 然后文件流会自动关闭 - EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(data()); - } - /** * 复杂的填充 * diff --git a/src/test/resources/demo/fill/no_variable.xlsx b/src/test/resources/demo/fill/no_variable.xlsx deleted file mode 100644 index 982321d6e39412eef856e1691fe579c303e0324f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 9946 zcmeHtbyO7G);CD^P=a(fNDI>4Fm$&ALw5;7hayM`(hbtm-5sKYAl)e-p>(~2zW4Ew z``o+Uf4{Z9vlcTf*m2I@`|Q2f`E8&A96Tz_-3n7)5xx8V*Fu5*^31^;=<-^olJ9oanXY|~5H+LQVts0hRB!qh7p8!V~L> z)G2R_N)oU$p+jl-l69;*R}b)k({7Cnj54)&;KtPGj83kX0Vhh{T?ttcHoyz-TajbJY0n34am^=XFz5)SN zXV8`>5_MrD<_)oe!}yY5 zOhk;8`7|J&;u_IwS0n#g6vB6$j9rr0S!gzBp%vH!(N3$H!9|^NWnA{fIq55buM~t4 zc5%l#9_g?(tb5YBzM6bNl!sSZSwCjQ8vQ^5^$~*&`!U0f1?$#_E3Yi&+J2Ub@7c+P zg-v@2W~8-0KG3l0B;;u$xCuA#&8VpkNaVQvbfv!bwryDov_%TkfdL{5KgHH^{Jg!X?1tLxe zDK{w>fWz1I_!dg>ev!gXj850z5)mWRq?`16BPq(fZ?CS;(EfD7%X}Es8>sPpp^m`) z!wGIKt`2rT13p^FA&4CydMba7mEd8%8j1q|;L9dpmVV|Is8ljTneFGTF8J#AUiG5F zL$GChyouR;-x{W>T$#wQlaC63JdFPK!l3iZDy$u)W9xV`al}JfgW#a1uP6DQwHA1j z3d^EEuy*IGQ}fpq<^)+!2@p!)wj(vuuyTaV$4_HlPL|7|>~YYpkyQ3X zYeQh~%=OPX1P*F0Puri_7{Y&}{mH^{ z=YUA{0sC2YKnuZ^2tcxIbcNgAP6u<2P#UdT6zI`3_PL)*(OM_AGR+4Prnc7Th&d{T zW69^RkOFe|;7;D_@Cs4t_)fEmPV_R*x)$N~5aMpjv9%9cZDt3meK~{63CoA zC!$~%2m5sF0Cu^RT1q;QGcrR$1@WI!KOmjwJ)R6;Xrjm&S51gir`G854leY@K-7wl zEti}o0*hm5e zyTBlkOG`1^$xJashQcqYJ!JL(kHZy9P7roe6978|-5TpOlLs~mjDF+FU-mF(dt!gW z8Si`UJIT#ki80MDS4e&G1(L;GLSK!G(A_%deaazSUG%`&r+^$M@$pc*k)nXdlreNSY78X-4Mc1xC#0V0|_u|RcD}nF}d->>e~E@ciPi$ds4mWIaWe~2i~pAi+OA zLJmJ~!@rZv6S8Lp2H1wd_B2LSnT^*15t>bdxu^+;u?3g*Yfa`R4fP_aEnptD3ypD z)8!_ed~Oc^A_-YCvJ|4n`J%qjuiq>(zNtvcVXB}TsjM{ivB{ut!Vl7Tf&QbjJoR-G zq~64FX`{B6=sDSJye7x%1L2|~FnW|Jp8$3i>v~_v+Azm;S36}|Nspt6e)oLz+1wjW za#52kGHH75HnL^R5>iI0>!+|q)D=uOrIr^Kf-9E{MBw9vG18fg{H)eD%>4V1o-TTJ zLzUeMkUK=9VKP_OX@t~gw1P_*1&!4&-g0Q-D`#7BMjoD1ksqZ5VQ4s(wwi4W@;u4$ z?h_O8wdp)OR;uBSML%Jfy&&YLqCV_x(+eepIi{A8p-iB5Syf^pc$M;D*<~Q9gXl5R zpUL|F;9jo(@818%-22b903s1#U=oRcmF&OBeiHwz7<;;l z4#Yepeljb5<=-GSV|0e;xwx<$Rk#G4QN z{pC{NaaJ?3%)#hZw-1bGJ>I&wWbJ7M_)BTJSo&REUteF?Y_8-9U`t#|$_}pPYYQ14 z0$xIdbDc(h*#BtSoD`(Ne;t;1n8@A27_*QUdAiv2;)|v%RiFuk<%`oeTD<(^+k{-K zE}isEl$WOV-BQ8$&EY0i3g$8Qj7ur9>gely;mL3{Y&79B;uVx)?@!Wds_6|WO>Ko`=ZV^JeY&U2^Ue}x>Qqdf zSs})vv`Nbj#EnLA$*0m}Sg38y)+*`;Qr?g*o+x^vrpuxVR~c2qf29YiscqO@!suVw zaXHhoshT%(J3xGPSnP84Eu`0axQ7_n4;D<9unBW-Vmv0{T(ND!YehV$kw?wQq98ij z8e@?b)Ouyc+F94I^*|KvkrubKb#gTJ31#9e9}#jm4_vddqiHYZxwF0OckwX-ZdIlI zE_eyE4_ht1Cwn`VDkD3VQCRyzLd~aL%h#7-r>%9>sUfp`nBi!~km~_*<2k7|k@KU8 zu1|x9l`n3On~*;F-BgnxKjMzt>e-C)^S(Ii$%!)d{ay~=%6O28yg&Xz)-{qOQ;00U zzL&jh?HPq~T{gMd*OGS15jM(s)hxJX-kuWlFH~iR_NWYGp!T7-+1Dj4Kt(*(WgprI zk|oT|k{+o-*fOvY0@^9P6Y!&fVtBn!#OaV{ozrf8Etg!TwT0OBR4XZt%m>3z^AI>3 z+>jq6f+z+qv6kKePnt zImAE+P*4JNUmid@Nw|!9aYJ%AV<99J*&XlA@Dos`Q&8Jp?8qXdVaM7qGls2%5 zE(VUjH!0B0vtKkF@0UWA>H~4VH~aXipH;4V1dKgluB&6{6SGU4<mJ5j<=mSEg|%WYyl;Si`fgBTORl`m!Gt^q#Arq+`P2Hv*dR| zyH95FzrTLSyFfjtqoVYvfk|nf)fA4%-4ytq%TgtlygL>^=0*nxheUvEJ4w+oA)^t} z0-ztM(-u;qiDuju%??)Jdz`$iHbaEf(pLFyxKTK4YLK#GW?4d@IXkRsRa&`M7C({8 zt`{tY%g0z1kH)AvvZs`&Sp%fs(BjEX%HDDu(wwB@-E?O6DkDPQm<;}iC?*20WfU^r zW`VIu`k@~frOwRgpVFVh>XmhX+HAkmIu%pQ)R8I1yj|jH6lBHgCWJYu4ThKnc6#atjKq;(%j3Q_(T%L zfQIrK>qLafM_Q3^2czcGX=W|e*|j)sPeX#Yx?kHYJma2O+$7>FeM0~#w zD?zhMTdZf(CY^7pt1-ZT5Xg{p`vdmlrfBy zg}n6zHfCk&+Q*Q5D=@zh6tm(D3B3qk9)_f0$ca!#8z3Z~D{F2W1&lE!E28ly*vwagCo^<4oR z$Z&-_81v<PET&)3n9rc6ZyUw){oFfClnPk~iEPF~cE^V;@67U83))%w*ahMyeMs+vuL zP*yEmE@&z~Il$;uwf$QJ1q>%63$|xxl@o(?zIgGgVy@4h#XG36~;?6qBN)%ZY zXa_(~iey2k*J{&_#OUkyeGBF(J^|4)yk&XU#nh%#pYO7&95hGR@ag8K(GR^zYefP# zIIC4Z85q8=S<0BSotV&4FEpEMIvlQ@t-@plXYbUj6tPRMY4S<=LVAw$``3q_RMnVq z9r88$aM>{P#yPpbwa;mM9k!^-vq25rJK77IwvSa}j`{Q~4)NrPb&Z9RRbitV-~;jJ zn|KXeM8BR35i;4bFC#Vsv?1K~Y0{RK1C=Y=baC1}D@?UD>Wdr+_BJcp6aLy9zM!KT zo#tLAko0YQzp;B!w*@E2l=grpBCS;G9ic2f_ZUZftIpeAN;|xDCC*F&8w<4v6Z-{5 zWPU|iZ8h}7jY1vczUWTecG{B{G`VTY#hJblPTLA6=AN-A<1>bz_B-5FD#ynHAAwx0 zT)HYQC>8U4ydB7|F84{;$GBjQKlKD?ap{C3Y6 zDs3Z%Sn>AD*7=?Qg|59aG#p9e54wb_vM{{Qz*V?=NjY`pz(;M7gKj@eUAkO%g*;3e z%0sNrv*x9U%MH)KQcd|`*RHkTK0%9OQHPI5@gIWVHn-k&b(F0Wd+w9l1iZIjt_bsO zO$UoUZdvxun!q@;g0B|2!jaET`=%p@-#hBeG~kKzFi4?@rbHN9+u9K|s1Zl+V}vKc zL*oOg2^98>tnoqif;VVEPle+--^)v;b7v-x;PFrtZoM{%#=)|Tvq8k2zwUO5S z-Qc=glJkp~4X8$JsvkzTi271BD-GHeRdKY~hW6zORM$0d@W1Ca08Ie7dS%X%&%}`T z3)MjKmTP6*ZcIPG>z`w-$Q1NlOw`|asxjILbEQi{p7D1L=W=PcbaXvxp;<&>t((0EP8 zZ=!@epd!_(6VIOQXnK{K{QSXOQI2h^YaCH6e7ucXP7aap_EjMa(_>w1(YQke{o49% zNp~rROvKEkzGx7UM}2Z#w<5Kr4dFB%^Z@Ms?2w8I>TT+T)$0x+}#Zn*(8o_{X)+@{d1dI%@T-@vXiJR^ncL0LtpNwzh62`HytCkg zYMp?l7owl5RGl%%Thj9V4!>CDh+O$zMV;a%flCu`mV*|?xeFZw&UziiSmD>Rm#LE* zrv01Dc?EY}vxeZwGM^v32jSPBxsB5b9ljejB4A1Hl?V1d$RI_ zGUkH>7Oyfq%>yjpgxBW|9j>5zoW$dHB+Q8Fg#7+fO1e@mkNQIiR;mu7wa+a zQ1?~v70^RTHZ$oJ&kx&P_j%mBmF@Lj;$|BiPZ|f4LfquPZK~#>;@VtIrycgu=Un=c z%{K|$tPzV3Nyy<-;Y^gTzDF6*z{X8zIi&Bi%4q1Y+~bG zAIca50t79r#Yxqv#bU9pI;F&sPjwt(sn7Z!MoRsFnR8{KtCzpYzEH^Kh$1x=RT~nF ziHu4BPM6!#A53rE%x|jfOAHHM9$ZTb3X@2o^tc*B`1!9-c9*wbVJ)U#oi0oVS+1Tc zBg2uYcG5%&N-=nnbT|nHlois&5q3m5J96MuCJEkLZmH}a5RT>_(87bPL9`Nh5$Gj8 zhN-2uHzX$VESshXLvJ1osgI%@Wha*%t{2ihqb?}PZ51PKFJyByw1$5{X2Lm?Pv^RZ zZZg81_{b!LHd%@(jv4HhL5cq`l#dxjaRilD0xresLB_iod4o{Q3=UgY$`l>mfEU6c z+!dvdT9_jQQ#DN8^O#han7~7o0jUIM6!JSsMObNQ3dJjGvX&1=X2R$M=>k5T#V(Nf zk5*l5jG#EgKAz=-+~QvK!*w&X?qFQj5|}--OKSBa6`I73_uFCj5%O2RJkTb(aM!;X z{-~8x(_&s=GyGM{Md?e)j9zhVO^epJfd1^Pba9cEfP+|XrtwAN^MWm|wiBN6rd9&a zYsVHel~jW`aGZ ztsK6E`?EQ89M%EmL7T#6=+7M@2YuRb0h>C5o~gS!TiILw>=C7g#ZWuh0SF^4OQfB< zcGd(`vAF^&nMlZcQxB8nwj;8`0PxsROY#S5$0S+?^;i4f&*?-$wMff1>0(2?VgtpQ z%%*`L(4NZfcr2W?4?a$hHF5DLNd7S=44Sqw4 zl)(z-qR?kqe&}OA)~{pTfdXa@4mLlZ>tYlXej$ptl+PUEl*vDjB?T5tMdE#Kd>to{ zHlm0V`?>ITLEus9!$zn0OFo}e?@GN4BBj<2B#@GFAGI<{;+Q<>g#X&puT>w2lg+LM zwxM_@0@!M-Z_%xpByTMd0>CFmk3W^Jd&csHhnp&*1TH9L@IqSB_BtJ5Q>-5d*DYNY z@txl$n6sLm<=T(1wnzgds#cKK#0={&Q%dqOON(v9Op_6#>4u6b)f*qb-Zd6(6l?mq@sF zEgxr|xOMAnPN#YZx_8KmQ82f3)4X*s71Fx1P+Q`>UhkvpZq9p7e2q3v0GPtf+CAsXl_8H}+r$o4++;?3vYd<*^G zBGe&hf6=hrQI^JjlJ8~*^zK99-Hlcy4}9!t*T+=5O3xtviHf%)bhxp)d#x>Esw|%y zk)o2$H&PaTo;4BAQy6jNzitk6QwM{R^NOn@=YYIIuzD4HR_BlV77#GE>ax5XZ4KX@eFn?VLt66{%Edg0xK z=)@P&eD2^-wDWOEC@Dwc6BqNEMogNUZ8UyFkWbE38{k+95t09svzzeHzK48RNvQ=Z zhLk}_qI&q;x_7zlhF;rWWPgwHpVn=O8?x?V2S}ZU+yo^; zSZA#yP-3bWLu_Y%zy%BW0`xhPx4ZlnJ6_d?F4-&c1}2G}rjJTpcByRH@njL~nA{8fh#xz7ykEBB9;tG3$5Lv(!v8Gi0tXW=3F zGl(n;{Qb{qI(aqv5iRy)Ux*opdFkPYhG`kOWE1YtUiR_q>2h`sKv<4F=@igYcpkMv z_|zl&ar^S5ViOd371*~UO~+^x*LvCCCjQucZ1FQnf2RZoF9a$VXi6Z3hUgvcsxRSS z?+UVaHP-NQ1i2XArG=U|L-x=_Cv_TsffZAS&jBnfVtVjOIDu7d8>#*zSh5?-3q7Q5 zzgv_RfG{?qMAMh<{mnoGF(#OPfQPO}m z<;zPb&K&Q>kD7BAZRp9Eo(-%%Hys{KbSz`aLtcCHIASKpl{fee(<%{*eAts`L5D%X z&o?~U^S?!AALa!f#(sMKRVQL0cAUK~kZ|(H|f60-&P#XBNB4czbJL z_846v7o)P-Q-r5eAT?^VuhxBe>d)Zv;0$!VJ3gapGvzz;=6R8n)yJhiR`D4~k=5dH zSxjRa!`z6>ZD+vMMBkp@<F?C^r_%e$>5k`@QZ%xE@%+3@|4rH5ZT+?Gl-;erjl2A*@BYBc z9q})H^nYjj-|?6GCb~bx@tZpu8s2{?{nt##efInF2fx|zp~>Vo`(M)t|LxFsi2Sd0 zcW6l{tPagY|Bc~KD{+zkEp^@B==~gbr{|ZI^#0EFZyE2tock@#Z#g+oJm;Spp8FE+ zzo7k=5DFcmxs&kMd)oi~>{-y5g|hw&Z~8Mr?jugWHTM6V?Kl2(f6Mn9px*+Xll;{C zceDMsP2Y`F{91P&2L1Bz9rIrU7Ju&i{)ojL?=P>#{2TA@fs6awzmL2Ama+=H)KIhi nZ3jQ4`~=zm?@~IE|53_MEElMN@H27XLd!%Pbk7`AciR64z*G7c From 72f7c5092a4b27ea2d1896c5fc44d91bd9e2b20b Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 14:37:45 +0800 Subject: [PATCH 032/129] =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E6=80=A7=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 26 +++++-- .../java/com/alibaba/excel/cache/Ehcache.java | 74 +++++++++---------- .../com/alibaba/excel/cache/MapCache.java | 10 +-- .../java/com/alibaba/excel/util/IntUtils.java | 30 ++++++++ .../com/alibaba/excel/util/ListUtils.java | 63 ++++++++++++++++ update.md | 1 + 6 files changed, 154 insertions(+), 50 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/util/IntUtils.java create mode 100644 src/main/java/com/alibaba/excel/util/ListUtils.java diff --git a/pom.xml b/pom.xml index 01efe344..b5ae5cbf 100644 --- a/pom.xml +++ b/pom.xml @@ -87,6 +87,13 @@ ehcache 3.8.1
+ + org.projectlombok + lombok + 1.18.20 + provided + + ch.qos.logback @@ -100,12 +107,6 @@ 1.2.71 test - - org.projectlombok - lombok - 1.18.8 - test - org.springframework.boot spring-boot @@ -232,6 +233,19 @@ + + org.projectlombok + lombok-maven-plugin + 1.18.20.0 + + + generate-sources + + delombok + + + + diff --git a/src/main/java/com/alibaba/excel/cache/Ehcache.java b/src/main/java/com/alibaba/excel/cache/Ehcache.java index f5bc5ff6..a5250900 100644 --- a/src/main/java/com/alibaba/excel/cache/Ehcache.java +++ b/src/main/java/com/alibaba/excel/cache/Ehcache.java @@ -1,52 +1,49 @@ package com.alibaba.excel.cache; import java.io.File; -import java.util.HashMap; -import java.util.Map; +import java.util.ArrayList; import java.util.UUID; +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.util.FileUtils; +import com.alibaba.excel.util.ListUtils; + +import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.MapUtils; import org.ehcache.CacheManager; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.alibaba.excel.context.AnalysisContext; -import com.alibaba.excel.util.FileUtils; /** * Default cache * * @author Jiaju Zhuang */ +@Slf4j public class Ehcache implements ReadCache { - - private static final Logger LOGGER = LoggerFactory.getLogger(Ehcache.class); - private static final int BATCH_COUNT = 1000; - private static final int DEBUG_WRITE_SIZE = 100 * 10000; - private static final int DEBUG_CACHE_MISS_SIZE = 1000; + public static final int BATCH_COUNT = 1000; /** * Key index */ - private int index = 0; - private HashMap dataMap = new HashMap<>(BATCH_COUNT * 4 / 3 + 1); + private int activeIndex = 0; + public static final int DEBUG_CACHE_MISS_SIZE = 1000; + public static final int DEBUG_WRITE_SIZE = 100 * 10000; + private ArrayList dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); private static final CacheManager FILE_CACHE_MANAGER; - private static final CacheConfiguration FILE_CACHE_CONFIGURATION; + private static final CacheConfiguration FILE_CACHE_CONFIGURATION; private static final CacheManager ACTIVE_CACHE_MANAGER; - private final CacheConfiguration activeCacheConfiguration; + private final CacheConfiguration activeCacheConfiguration; /** * Bulk storage data */ - private org.ehcache.Cache fileCache; + private org.ehcache.Cache fileCache; /** * Currently active cache */ - private org.ehcache.Cache activeCache; + private org.ehcache.Cache activeCache; private String cacheAlias; /** * Count the number of cache misses @@ -55,7 +52,7 @@ public class Ehcache implements ReadCache { public Ehcache(int maxCacheActivateSize) { activeCacheConfiguration = CacheConfigurationBuilder - .newCacheConfigurationBuilder(Integer.class, HashMap.class, + .newCacheConfigurationBuilder(Integer.class, ArrayList.class, ResourcePoolsBuilder.newResourcePoolsBuilder().heap(maxCacheActivateSize, MemoryUnit.MB)) .withSizeOfMaxObjectGraph(1000 * 1000L).withSizeOfMaxObjectSize(maxCacheActivateSize, MemoryUnit.MB) .build(); @@ -67,7 +64,7 @@ public class Ehcache implements ReadCache { CacheManagerBuilder.newCacheManagerBuilder().with(CacheManagerBuilder.persistence(cacheFile)).build(true); ACTIVE_CACHE_MANAGER = CacheManagerBuilder.newCacheManagerBuilder().build(true); FILE_CACHE_CONFIGURATION = CacheConfigurationBuilder - .newCacheConfigurationBuilder(Integer.class, HashMap.class, + .newCacheConfigurationBuilder(Integer.class, ArrayList.class, ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MemoryUnit.GB)) .withSizeOfMaxObjectGraph(1000 * 1000L).withSizeOfMaxObjectSize(10, MemoryUnit.GB).build(); } @@ -81,15 +78,16 @@ public class Ehcache implements ReadCache { @Override public void put(String value) { - dataMap.put(index, value); - if ((index + 1) % BATCH_COUNT == 0) { - fileCache.put(index / BATCH_COUNT, dataMap); - dataMap = new HashMap(BATCH_COUNT * 4 / 3 + 1); + dataList.add(value); + if (dataList.size() >= BATCH_COUNT) { + fileCache.put(activeIndex, dataList); + activeIndex++; + dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); } - index++; - if (LOGGER.isDebugEnabled()) { - if (index % DEBUG_WRITE_SIZE == 0) { - LOGGER.debug("Already put :{}", index); + if (log.isDebugEnabled()) { + int alreadyPut = activeIndex * BATCH_COUNT + dataList.size(); + if (alreadyPut % DEBUG_WRITE_SIZE == 0) { + log.debug("Already put :{}", alreadyPut); } } } @@ -100,25 +98,25 @@ public class Ehcache implements ReadCache { return null; } int route = key / BATCH_COUNT; - HashMap dataMap = activeCache.get(route); - if (dataMap == null) { - dataMap = fileCache.get(route); - activeCache.put(route, dataMap); - if (LOGGER.isDebugEnabled()) { + ArrayList dataList = activeCache.get(route); + if (dataList == null) { + dataList = fileCache.get(route); + activeCache.put(route, dataList); + if (log.isDebugEnabled()) { if (cacheMiss++ % DEBUG_CACHE_MISS_SIZE == 0) { - LOGGER.debug("Cache misses count:{}", cacheMiss); + log.debug("Cache misses count:{}", cacheMiss); } } } - return dataMap.get(key); + return dataList.get(key % BATCH_COUNT); } @Override public void putFinished() { - if (MapUtils.isEmpty(dataMap)) { + if (CollectionUtils.isEmpty(dataList)) { return; } - fileCache.put(index / BATCH_COUNT, dataMap); + fileCache.put(activeIndex, dataList); } @Override diff --git a/src/main/java/com/alibaba/excel/cache/MapCache.java b/src/main/java/com/alibaba/excel/cache/MapCache.java index ae948fbc..f83a1233 100644 --- a/src/main/java/com/alibaba/excel/cache/MapCache.java +++ b/src/main/java/com/alibaba/excel/cache/MapCache.java @@ -1,26 +1,24 @@ package com.alibaba.excel.cache; -import java.util.HashMap; -import java.util.Map; +import java.util.ArrayList; +import java.util.List; import com.alibaba.excel.context.AnalysisContext; /** - * * Putting temporary data directly into a map is a little more efficient but very memory intensive * * @author Jiaju Zhuang */ public class MapCache implements ReadCache { - private Map cache = new HashMap(); - private int index = 0; + private List cache = new ArrayList<>(); @Override public void init(AnalysisContext analysisContext) {} @Override public void put(String value) { - cache.put(index++, value); + cache.add(value); } @Override diff --git a/src/main/java/com/alibaba/excel/util/IntUtils.java b/src/main/java/com/alibaba/excel/util/IntUtils.java new file mode 100644 index 00000000..0237e452 --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/IntUtils.java @@ -0,0 +1,30 @@ +package com.alibaba.excel.util; + +import java.util.ArrayList; +import java.util.List; + +/** + * Int utils + * + * @author Jiaju Zhuang + **/ +public class IntUtils { + private IntUtils() {} + /** + * Returns the {@code int} nearest in value to {@code value}. + * + * @param value any {@code long} value + * @return the same value cast to {@code int} if it is in the range of the {@code int} type, + * {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too + * small + */ + public static int saturatedCast(long value) { + if (value > Integer.MAX_VALUE) { + return Integer.MAX_VALUE; + } + if (value < Integer.MIN_VALUE) { + return Integer.MIN_VALUE; + } + return (int) value; + } +} diff --git a/src/main/java/com/alibaba/excel/util/ListUtils.java b/src/main/java/com/alibaba/excel/util/ListUtils.java new file mode 100644 index 00000000..6b4d7499 --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/ListUtils.java @@ -0,0 +1,63 @@ +package com.alibaba.excel.util; + +import java.util.ArrayList; +import java.util.List; + +/** + * List utils + * + * @author Jiaju Zhuang + **/ +public class ListUtils { + private ListUtils() {} + + /** + * Creates an {@code ArrayList} instance backed by an array with the specified initial size; + * simply delegates to {@link ArrayList#ArrayList(int)}. + * + *

Note for Java 7 and later: this method is now unnecessary and should be treated as + * deprecated. Instead, use {@code new }{@link ArrayList#ArrayList(int) ArrayList}{@code <>(int)} + * directly, taking advantage of the new "diamond" syntax. + * (Unlike here, there is no risk of overload ambiguity, since the {@code ArrayList} constructors + * very wisely did not accept varargs.) + * + * @param initialArraySize the exact size of the initial backing array for the returned array list + * ({@code ArrayList} documentation calls this value the "capacity") + * @return a new, empty {@code ArrayList} which is guaranteed not to resize itself unless its size + * reaches {@code initialArraySize + 1} + * @throws IllegalArgumentException if {@code initialArraySize} is negative + */ + public static ArrayList newArrayListWithCapacity(int initialArraySize) { + checkNonnegative(initialArraySize, "initialArraySize"); + return new ArrayList<>(initialArraySize); + } + + /** + * Creates an {@code ArrayList} instance to hold {@code estimatedSize} elements, plus an + * unspecified amount of padding; you almost certainly mean to call {@link + * #newArrayListWithCapacity} (see that method for further advice on usage). + * + *

Note: This method will soon be deprecated. Even in the rare case that you do want + * some amount of padding, it's best if you choose your desired amount explicitly. + * + * @param estimatedSize an estimate of the eventual {@link List#size()} of the new list + * @return a new, empty {@code ArrayList}, sized appropriately to hold the estimated number of + * elements + * @throws IllegalArgumentException if {@code estimatedSize} is negative + */ + public static ArrayList newArrayListWithExpectedSize(int estimatedSize) { + return new ArrayList<>(computeArrayListCapacity(estimatedSize)); + } + + static int computeArrayListCapacity(int arraySize) { + checkNonnegative(arraySize, "arraySize"); + return IntUtils.saturatedCast(5L + arraySize + (arraySize / 10)); + } + + static int checkNonnegative(int value, String name) { + if (value < 0) { + throw new IllegalArgumentException(name + " cannot be negative but was: " + value); + } + return value; + } +} diff --git a/update.md b/update.md index adfc42c2..2a7bfa83 100644 --- a/update.md +++ b/update.md @@ -5,6 +5,7 @@ * 升级ehcache 到 3.8.1 * 支持非驼峰的字段读写 * 修复`CellData`可能不返回行列号 [Issue #1832](https://github.com/alibaba/easyexcel/issues/1832) +* 优化读取性能 # 2.2.8 * 兼容07在特殊的excel的情况下,读取数据异常 From d90b9fd809758c0d838aa2fdb5c2579a84dc9e97 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 14:45:58 +0800 Subject: [PATCH 033/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java index 39d759d2..2d3c75b6 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java @@ -62,7 +62,6 @@ public class SimpleDataTest { private void synchronousRead(File file) { // Synchronous read file - EasyExcel.write(file, SimpleData.class).sheet().doWrite(data()); List list = EasyExcel.read(file).head(SimpleData.class).sheet().doReadSync(); Assert.assertEquals(list.size(), 10); Assert.assertTrue(list.get(0) instanceof SimpleData); From 4652aca20e02ca2ed4001616c06a3f12e2c0aab6 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 14:54:46 +0800 Subject: [PATCH 034/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=96=87=E6=A1=88?= =?UTF-8?q?=E6=8F=8F=E8=BF=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/alibaba/excel/annotation/ExcelProperty.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/alibaba/excel/annotation/ExcelProperty.java b/src/main/java/com/alibaba/excel/annotation/ExcelProperty.java index 5c778a84..e2b169e3 100644 --- a/src/main/java/com/alibaba/excel/annotation/ExcelProperty.java +++ b/src/main/java/com/alibaba/excel/annotation/ExcelProperty.java @@ -23,7 +23,7 @@ public @interface ExcelProperty { *

* write: It automatically merges when you have more than one head *

- * read: When you have multiple heads, take the first one + * read: When you have multiple heads, take the last one * * @return The name of the sheet header */ From e3173247f55dad5a1f553ffc99605e6c0ff8246b Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 15:41:32 +0800 Subject: [PATCH 035/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=83=A8=E5=88=86?= =?UTF-8?q?=E6=83=85=E5=86=B5=E4=B8=8B=E4=B8=8D=E6=8A=9B=E5=87=BA=E5=BC=82?= =?UTF-8?q?=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/context/WriteContextImpl.java | 41 +++++++++++-------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java index c1f89f02..648a7fe9 100644 --- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java @@ -6,22 +6,6 @@ import java.io.OutputStream; import java.util.Map; import java.util.UUID; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.Encryptor; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alibaba.excel.enums.WriteTypeEnum; import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.metadata.CellData; @@ -42,6 +26,22 @@ import com.alibaba.excel.write.metadata.holder.WriteTableHolder; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; import com.alibaba.excel.write.property.ExcelWriteHeadProperty; +import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.openxml4j.opc.PackageAccess; +import org.apache.poi.poifs.crypt.EncryptionInfo; +import org.apache.poi.poifs.crypt.EncryptionMode; +import org.apache.poi.poifs.crypt.Encryptor; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * A context is the main anchorage point of a excel writer. * @@ -50,6 +50,7 @@ import com.alibaba.excel.write.property.ExcelWriteHeadProperty; public class WriteContextImpl implements WriteContext { private static final Logger LOGGER = LoggerFactory.getLogger(WriteContextImpl.class); + private static final String NO_SHEETS="no sheets"; /** * The Workbook currently written @@ -178,8 +179,12 @@ public class WriteContextImpl implements WriteContext { writeSheetHolder .setCachedSheet(writeWorkbookHolder.getCachedWorkbook().getSheet(writeSheetHolder.getSheetName())); } - } catch (Exception e) { - currentSheet = createSheet(); + } catch (IllegalArgumentException e) { + if (e.getMessage() != null && e.getMessage().contains(NO_SHEETS)) { + currentSheet = createSheet(); + } else { + throw e; + } } if (currentSheet == null) { currentSheet = createSheet(); From f879ceb37a2fb9dd5ef98b5eccf461cd8f85cc59 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 15:41:38 +0800 Subject: [PATCH 036/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=83=A8=E5=88=86?= =?UTF-8?q?=E6=83=85=E5=86=B5=E4=B8=8B=E4=B8=8D=E6=8A=9B=E5=87=BA=E5=BC=82?= =?UTF-8?q?=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- update.md | 1 + 1 file changed, 1 insertion(+) diff --git a/update.md b/update.md index 2a7bfa83..e033ccc9 100644 --- a/update.md +++ b/update.md @@ -6,6 +6,7 @@ * 支持非驼峰的字段读写 * 修复`CellData`可能不返回行列号 [Issue #1832](https://github.com/alibaba/easyexcel/issues/1832) * 优化读取性能 +* 修复部分情况下不抛出异常 # 2.2.8 * 兼容07在特殊的excel的情况下,读取数据异常 From 7c60a9248361d31ecad3598c880b06755b504240 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 20:19:53 +0800 Subject: [PATCH 037/129] =?UTF-8?q?=2007=E7=89=88=E5=9C=A8=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=E7=9A=84=E6=97=B6=E5=80=99=E4=BC=9A=E5=AF=BC=E5=87=BA?= =?UTF-8?q?=20=E8=A1=8C=E6=95=B0=20#1282?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/excel/util/ClassUtils.java | 49 ++++++ .../com/alibaba/excel/util/FieldUtils.java | 94 +++++++++++ .../com/alibaba/excel/util/MemberUtils.java | 54 +++++++ .../com/alibaba/excel/util/StringUtils.java | 25 +++ .../java/com/alibaba/excel/util/Validate.java | 151 ++++++++++++++++++ .../alibaba/excel/write/ExcelBuilderImpl.java | 5 + .../write/executor/ExcelWriteAddExecutor.java | 6 +- .../executor/ExcelWriteFillExecutor.java | 14 +- .../handler/AbstractCellWriteHandler.java | 2 + .../handler/AbstractRowWriteHandler.java | 6 +- .../handler/AbstractSheetWriteHandler.java | 2 + .../handler/AbstractWorkbookWriteHandler.java | 2 + .../handler/DefaultWriteHandlerLoader.java | 18 ++- .../excel/write/handler/RowWriteHandler.java | 43 ++--- .../write/handler/WorkbookWriteHandler.java | 6 +- .../handler/impl/DefaultRowWriteHandler.java | 22 +++ .../impl/DimensionWorkbookWriteHandler.java | 76 +++++++++ .../metadata/holder/WriteSheetHolder.java | 86 ++-------- .../easyexcel/test/temp/simple/Wirte.java | 3 + 19 files changed, 551 insertions(+), 113 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/util/MemberUtils.java create mode 100644 src/main/java/com/alibaba/excel/util/Validate.java create mode 100644 src/main/java/com/alibaba/excel/write/handler/impl/DefaultRowWriteHandler.java create mode 100644 src/main/java/com/alibaba/excel/write/handler/impl/DimensionWorkbookWriteHandler.java diff --git a/src/main/java/com/alibaba/excel/util/ClassUtils.java b/src/main/java/com/alibaba/excel/util/ClassUtils.java index 936c325d..16643de4 100644 --- a/src/main/java/com/alibaba/excel/util/ClassUtils.java +++ b/src/main/java/com/alibaba/excel/util/ClassUtils.java @@ -6,6 +6,8 @@ import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.TreeMap; @@ -208,4 +210,51 @@ public class ClassUtils { return ignoreMap; } } + + + /** + *

Gets a {@code List} of all interfaces implemented by the given + * class and its superclasses.

+ * + *

The order is determined by looking through each interface in turn as + * declared in the source file and following its hierarchy up. Then each + * superclass is considered in the same way. Later duplicates are ignored, + * so the order is maintained.

+ * + * @param cls the class to look up, may be {@code null} + * @return the {@code List} of interfaces in order, + * {@code null} if null input + */ + public static List> getAllInterfaces(final Class cls) { + if (cls == null) { + return null; + } + + final LinkedHashSet> interfacesFound = new LinkedHashSet<>(); + getAllInterfaces(cls, interfacesFound); + + return new ArrayList<>(interfacesFound); + } + + + /** + * Gets the interfaces for the specified class. + * + * @param cls the class to look up, may be {@code null} + * @param interfacesFound the {@code Set} of interfaces for the class + */ + private static void getAllInterfaces(Class cls, final HashSet> interfacesFound) { + while (cls != null) { + final Class[] interfaces = cls.getInterfaces(); + + for (final Class i : interfaces) { + if (interfacesFound.add(i)) { + getAllInterfaces(i, interfacesFound); + } + } + + cls = cls.getSuperclass(); + } + } + } diff --git a/src/main/java/com/alibaba/excel/util/FieldUtils.java b/src/main/java/com/alibaba/excel/util/FieldUtils.java index 1a4d5287..1e788907 100644 --- a/src/main/java/com/alibaba/excel/util/FieldUtils.java +++ b/src/main/java/com/alibaba/excel/util/FieldUtils.java @@ -1,6 +1,8 @@ package com.alibaba.excel.util; import java.lang.reflect.Field; +import java.lang.reflect.Modifier; + /** * Field utils @@ -48,4 +50,96 @@ public class FieldUtils { private static String buildFieldName(char firstChar, String fieldName) { return firstChar + fieldName.substring(1); } + + + /** + * Gets an accessible {@link Field} by name respecting scope. Superclasses/interfaces will be considered. + * + * @param cls + * the {@link Class} to reflect, must not be {@code null} + * @param fieldName + * the field name to obtain + * @return the Field object + * @throws IllegalArgumentException + * if the class is {@code null}, or the field name is blank or empty + */ + public static Field getField(final Class cls, final String fieldName) { + final Field field = getField(cls, fieldName, false); + MemberUtils.setAccessibleWorkaround(field); + return field; + } + + + + /** + * Gets an accessible {@link Field} by name, breaking scope if requested. Superclasses/interfaces will be + * considered. + * + * @param cls + * the {@link Class} to reflect, must not be {@code null} + * @param fieldName + * the field name to obtain + * @param forceAccess + * whether to break scope restrictions using the + * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only + * match {@code public} fields. + * @return the Field object + * @throws NullPointerException if the class is {@code null} + * @throws IllegalArgumentException if the field name is blank or empty or is matched at multiple places + * in the inheritance hierarchy + */ + public static Field getField(final Class cls, final String fieldName, final boolean forceAccess) { + Validate.isTrue(cls != null, "The class must not be null"); + Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty"); + // FIXME is this workaround still needed? lang requires Java 6 + // Sun Java 1.3 has a bugged implementation of getField hence we write the + // code ourselves + + // getField() will return the Field object with the declaring class + // set correctly to the class that declares the field. Thus requesting the + // field on a subclass will return the field from the superclass. + // + // priority order for lookup: + // searchclass private/protected/package/public + // superclass protected/package/public + // private/different package blocks access to further superclasses + // implementedinterface public + + // check up the superclass hierarchy + for (Class acls = cls; acls != null; acls = acls.getSuperclass()) { + try { + final Field field = acls.getDeclaredField(fieldName); + // getDeclaredField checks for non-public scopes as well + // and it returns accurate results + if (!Modifier.isPublic(field.getModifiers())) { + if (forceAccess) { + field.setAccessible(true); + } else { + continue; + } + } + return field; + } catch (final NoSuchFieldException ex) { // NOPMD + // ignore + } + } + // check the public interface case. This must be manually searched for + // incase there is a public supersuperclass field hidden by a private/package + // superclass field. + Field match = null; + for (final Class class1 : ClassUtils.getAllInterfaces(cls)) { + try { + final Field test = class1.getField(fieldName); + Validate.isTrue(match == null, "Reference to field %s is ambiguous relative to %s" + + "; a matching field exists on two or more implemented interfaces.", fieldName, cls); + match = test; + } catch (final NoSuchFieldException ex) { // NOPMD + // ignore + } + } + return match; + } + + + } diff --git a/src/main/java/com/alibaba/excel/util/MemberUtils.java b/src/main/java/com/alibaba/excel/util/MemberUtils.java new file mode 100644 index 00000000..6bcfaac6 --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/MemberUtils.java @@ -0,0 +1,54 @@ +package com.alibaba.excel.util; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Member; +import java.lang.reflect.Modifier; + +/** + * Member utils. + * + * @author Jiaju Zhuang + */ +public class MemberUtils { + + private static final int ACCESS_TEST = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE; + + + /** + * XXX Default access superclass workaround. + * + * When a {@code public} class has a default access superclass with {@code public} members, + * these members are accessible. Calling them from compiled code works fine. + * Unfortunately, on some JVMs, using reflection to invoke these members + * seems to (wrongly) prevent access even when the modifier is {@code public}. + * Calling {@code setAccessible(true)} solves the problem but will only work from + * sufficiently privileged code. Better workarounds would be gratefully + * accepted. + * @param o the AccessibleObject to set as accessible + * @return a boolean indicating whether the accessibility of the object was set to true. + */ + static boolean setAccessibleWorkaround(final AccessibleObject o) { + if (o == null || o.isAccessible()) { + return false; + } + final Member m = (Member) o; + if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) { + try { + o.setAccessible(true); + return true; + } catch (final SecurityException e) { // NOPMD + // ignore in favor of subsequent IllegalAccessException + } + } + return false; + } + + /** + * Returns whether a given set of modifiers implies package access. + * @param modifiers to test + * @return {@code true} unless {@code package}/{@code protected}/{@code private} modifier detected + */ + static boolean isPackageAccess(final int modifiers) { + return (modifiers & ACCESS_TEST) == 0; + } +} diff --git a/src/main/java/com/alibaba/excel/util/StringUtils.java b/src/main/java/com/alibaba/excel/util/StringUtils.java index a67e46be..667233dc 100644 --- a/src/main/java/com/alibaba/excel/util/StringUtils.java +++ b/src/main/java/com/alibaba/excel/util/StringUtils.java @@ -69,4 +69,29 @@ public class StringUtils { return true; } + + /** + *

Checks if a CharSequence is not empty (""), not null and not whitespace only.

+ * + *

Whitespace is defined by {@link Character#isWhitespace(char)}.

+ * + *
+     * StringUtils.isNotBlank(null)      = false
+     * StringUtils.isNotBlank("")        = false
+     * StringUtils.isNotBlank(" ")       = false
+     * StringUtils.isNotBlank("bob")     = true
+     * StringUtils.isNotBlank("  bob  ") = true
+     * 
+ * + * @param cs the CharSequence to check, may be null + * @return {@code true} if the CharSequence is + * not empty and not null and not whitespace only + * @since 2.0 + * @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence) + */ + public static boolean isNotBlank(final CharSequence cs) { + return !isBlank(cs); + } + + } diff --git a/src/main/java/com/alibaba/excel/util/Validate.java b/src/main/java/com/alibaba/excel/util/Validate.java new file mode 100644 index 00000000..6207bb1a --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/Validate.java @@ -0,0 +1,151 @@ +package com.alibaba.excel.util; + +import java.util.Objects; + +/** + * Validate + * + * @author Jiaju Zhuang + */ +public class Validate { + + private static final String DEFAULT_IS_TRUE_EX_MESSAGE = "The validated expression is false"; + private static final String DEFAULT_IS_NULL_EX_MESSAGE = "The validated object is null"; + + /** + *

Validate that the argument condition is {@code true}; otherwise + * throwing an exception with the specified message. This method is useful when + * validating according to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression.

+ * + *
Validate.isTrue(i > 0.0, "The value must be greater than zero: %d", i);
+ * + *

For performance reasons, the long value is passed as a separate parameter and + * appended to the exception message only in the case of an error.

+ * + * @param expression the boolean expression to check + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param value the value to append to the message when invalid + * @throws IllegalArgumentException if expression is {@code false} + * @see #isTrue(boolean) + * @see #isTrue(boolean, String, double) + * @see #isTrue(boolean, String, Object...) + */ + public static void isTrue(final boolean expression, final String message, final long value) { + if (!expression) { + throw new IllegalArgumentException(String.format(message, Long.valueOf(value))); + } + } + + /** + *

Validate that the argument condition is {@code true}; otherwise + * throwing an exception with the specified message. This method is useful when + * validating according to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression.

+ * + *
Validate.isTrue(d > 0.0, "The value must be greater than zero: %s", d);
+ * + *

For performance reasons, the double value is passed as a separate parameter and + * appended to the exception message only in the case of an error.

+ * + * @param expression the boolean expression to check + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param value the value to append to the message when invalid + * @throws IllegalArgumentException if expression is {@code false} + * @see #isTrue(boolean) + * @see #isTrue(boolean, String, long) + * @see #isTrue(boolean, String, Object...) + */ + public static void isTrue(final boolean expression, final String message, final double value) { + if (!expression) { + throw new IllegalArgumentException(String.format(message, Double.valueOf(value))); + } + } + + /** + *

Validate that the argument condition is {@code true}; otherwise + * throwing an exception with the specified message. This method is useful when + * validating according to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression.

+ * + *
+     * Validate.isTrue(i >= min && i <= max, "The value must be between %d and %d", min, max);
+     * Validate.isTrue(myObject.isOk(), "The object is not okay");
+ * + * @param expression the boolean expression to check + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message, null array not recommended + * @throws IllegalArgumentException if expression is {@code false} + * @see #isTrue(boolean) + * @see #isTrue(boolean, String, long) + * @see #isTrue(boolean, String, double) + */ + public static void isTrue(final boolean expression, final String message, final Object... values) { + if (!expression) { + throw new IllegalArgumentException(String.format(message, values)); + } + } + + /** + *

Validate that the argument condition is {@code true}; otherwise + * throwing an exception. This method is useful when validating according + * to an arbitrary boolean expression, such as validating a + * primitive number or using your own custom validation expression.

+ * + *
+     * Validate.isTrue(i > 0);
+     * Validate.isTrue(myObject.isOk());
+ * + *

The message of the exception is "The validated expression is + * false".

+ * + * @param expression the boolean expression to check + * @throws IllegalArgumentException if expression is {@code false} + * @see #isTrue(boolean, String, long) + * @see #isTrue(boolean, String, double) + * @see #isTrue(boolean, String, Object...) + */ + public static void isTrue(final boolean expression) { + if (!expression) { + throw new IllegalArgumentException(DEFAULT_IS_TRUE_EX_MESSAGE); + } + } + + + /** + *

Validate that the specified argument is not {@code null}; + * otherwise throwing an exception. + * + *

Validate.notNull(myObject, "The object must not be null");
+ * + *

The message of the exception is "The validated object is + * null".

+ * + * @param the object type + * @param object the object to check + * @return the validated object (never {@code null} for method chaining) + * @throws NullPointerException if the object is {@code null} + * @see #notNull(Object, String, Object...) + */ + public static T notNull(final T object) { + return notNull(object, DEFAULT_IS_NULL_EX_MESSAGE); + } + + /** + *

Validate that the specified argument is not {@code null}; + * otherwise throwing an exception with the specified message. + * + *

Validate.notNull(myObject, "The object must not be null");
+ * + * @param the object type + * @param object the object to check + * @param message the {@link String#format(String, Object...)} exception message if invalid, not null + * @param values the optional values for the formatted exception message + * @return the validated object (never {@code null} for method chaining) + * @throws NullPointerException if the object is {@code null} + * @see #notNull(Object) + */ + public static T notNull(final T object, final String message, final Object... values) { + return Objects.requireNonNull(object, () -> String.format(message, values)); + } +} diff --git a/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java b/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java index 0c7158ed..2acd5769 100644 --- a/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java +++ b/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java @@ -1,13 +1,18 @@ package com.alibaba.excel.write; +import java.lang.reflect.Field; import java.util.List; +import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.xssf.streaming.SXSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFSheet; import com.alibaba.excel.context.WriteContext; import com.alibaba.excel.context.WriteContextImpl; import com.alibaba.excel.enums.WriteTypeEnum; import com.alibaba.excel.exception.ExcelGenerateException; +import com.alibaba.excel.util.FieldUtils; import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.write.executor.ExcelWriteAddExecutor; import com.alibaba.excel.write.executor.ExcelWriteFillExecutor; diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 6e99a9a9..529f5d22 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -49,9 +49,10 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { // BeanMap is out of order,so use sortedAllFiledMap Map sortedAllFiledMap = new TreeMap(); int relativeRowIndex = 0; + int lastRowIndex = 0; for (Object oneRowData : data) { - int n = relativeRowIndex + newRowIndex; - addOneRowOfDataToExcel(oneRowData, n, relativeRowIndex, sortedAllFiledMap); + lastRowIndex = relativeRowIndex + newRowIndex; + addOneRowOfDataToExcel(oneRowData, lastRowIndex, relativeRowIndex, sortedAllFiledMap); relativeRowIndex++; } } @@ -108,6 +109,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { Object value = oneRowData.get(dataIndex); CellData cellData = converterAndSet(writeContext.currentWriteHolder(), value == null ? null : value.getClass(), cell, value, null, head, relativeRowIndex); + writeContext.writeSheetHolder().setLastRowIndex(cellData.getRowIndex()); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE); } diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index b2f3362b..7accb669 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -93,7 +93,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { Object realData; if (data instanceof FillWrapper) { - FillWrapper fillWrapper = (FillWrapper) data; + FillWrapper fillWrapper = (FillWrapper)data; currentDataPrefix = fillWrapper.getName(); realData = fillWrapper.getCollectionData(); } else { @@ -105,7 +105,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { // processing data if (realData instanceof Collection) { List analysisCellList = readTemplateData(templateCollectionAnalysisCache); - Collection collectionData = (Collection) realData; + Collection collectionData = (Collection)realData; if (CollectionUtils.isEmpty(collectionData)) { return; } @@ -183,7 +183,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { } Map dataMap; if (oneRowData instanceof Map) { - dataMap = (Map) oneRowData; + dataMap = (Map)oneRowData; } else { dataMap = BeanMap.create(oneRowData); } @@ -293,7 +293,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { } Row row = createRowIfNecessary(sheet, cachedSheet, lastRowIndex, fillConfig, analysisCell, isOriginalCell); - Cell cell = createCellIfNecessary(row,lastColumnIndex); + Cell cell = createCellIfNecessary(row, lastColumnIndex); Map collectionFieldStyleMap = collectionFieldStyleCache.get(currentUniqueDataFlag); if (collectionFieldStyleMap == null) { @@ -335,7 +335,8 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { row = cachedSheet.createRow(lastRowIndex); } else { // The last row of the middle disk inside empty rows, resulting in cachedSheet can not get inside. - // Will throw Attempting to write a row[" + rownum + "] " + "in the range [0," + this._sh.getLastRowNum() + "] that is already written to disk. + // Will throw Attempting to write a row[" + rownum + "] " + "in the range [0," + this._sh + // .getLastRowNum() + "] that is already written to disk. try { row = sheet.createRow(lastRowIndex); } catch (IllegalArgumentException ignore) { @@ -414,7 +415,8 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { int startIndex = 0; int length = value.length(); int lastPrepareDataIndex = 0; - out: while (startIndex < length) { + out: + while (startIndex < length) { int prefixIndex = value.indexOf(FILL_PREFIX, startIndex); if (prefixIndex < 0) { break out; diff --git a/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java index b649af7a..963abc87 100644 --- a/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java @@ -14,7 +14,9 @@ import com.alibaba.excel.write.metadata.holder.WriteTableHolder; * Abstract cell write handler * * @author Jiaju Zhuang + * @deprecated Please use it directly {@link CellWriteHandler} **/ +@Deprecated public abstract class AbstractCellWriteHandler implements CellWriteHandler { @Override diff --git a/src/main/java/com/alibaba/excel/write/handler/AbstractRowWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/AbstractRowWriteHandler.java index d1e8c3a9..286d8757 100644 --- a/src/main/java/com/alibaba/excel/write/handler/AbstractRowWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/AbstractRowWriteHandler.java @@ -1,15 +1,17 @@ package com.alibaba.excel.write.handler; -import org.apache.poi.ss.usermodel.Row; - import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder; +import org.apache.poi.ss.usermodel.Row; + /** * Abstract row write handler * * @author Jiaju Zhuang + * @deprecated Please use it directly {@link RowWriteHandler} **/ +@Deprecated public abstract class AbstractRowWriteHandler implements RowWriteHandler { @Override public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex, diff --git a/src/main/java/com/alibaba/excel/write/handler/AbstractSheetWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/AbstractSheetWriteHandler.java index 76f4c846..d24f9010 100644 --- a/src/main/java/com/alibaba/excel/write/handler/AbstractSheetWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/AbstractSheetWriteHandler.java @@ -7,7 +7,9 @@ import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; * Abstract sheet write handler * * @author Jiaju Zhuang + * @deprecated Please use it directly {@link SheetWriteHandler} **/ +@Deprecated public abstract class AbstractSheetWriteHandler implements SheetWriteHandler { @Override public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) { diff --git a/src/main/java/com/alibaba/excel/write/handler/AbstractWorkbookWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/AbstractWorkbookWriteHandler.java index baad3920..5bb2fc5f 100644 --- a/src/main/java/com/alibaba/excel/write/handler/AbstractWorkbookWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/AbstractWorkbookWriteHandler.java @@ -6,7 +6,9 @@ import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; * Abstract workbook write handler * * @author Jiaju Zhuang + * @deprecated Please use it directly {@link WorkbookWriteHandler} **/ +@Deprecated public abstract class AbstractWorkbookWriteHandler implements WorkbookWriteHandler { @Override diff --git a/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java b/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java index dff84d7a..4afefea6 100644 --- a/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java +++ b/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java @@ -3,12 +3,14 @@ package com.alibaba.excel.write.handler; import java.util.ArrayList; import java.util.List; -import org.apache.poi.ss.usermodel.IndexedColors; - +import com.alibaba.excel.write.handler.impl.DefaultRowWriteHandler; +import com.alibaba.excel.write.handler.impl.DimensionWorkbookWriteHandler; 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.IndexedColors; + /** * Load default handler * @@ -16,13 +18,20 @@ import com.alibaba.excel.write.style.HorizontalCellStyleStrategy; */ public class DefaultWriteHandlerLoader { + public static final List DEFAULT_WRITE_HANDLER_LIST = new ArrayList<>(); + + static { + DEFAULT_WRITE_HANDLER_LIST.add(new DimensionWorkbookWriteHandler()); + DEFAULT_WRITE_HANDLER_LIST.add(new DefaultRowWriteHandler()); + } + /** * Load default handler * * @return */ public static List loadDefaultHandler(Boolean useDefaultStyle) { - List handlerList = new ArrayList(); + List handlerList = new ArrayList<>(); if (useDefaultStyle) { WriteCellStyle headWriteCellStyle = new WriteCellStyle(); headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); @@ -31,8 +40,9 @@ public class DefaultWriteHandlerLoader { headWriteFont.setFontHeightInPoints((short)14); headWriteFont.setBold(true); headWriteCellStyle.setWriteFont(headWriteFont); - handlerList.add(new HorizontalCellStyleStrategy(headWriteCellStyle, new ArrayList())); + handlerList.add(new HorizontalCellStyleStrategy(headWriteCellStyle, new ArrayList<>())); } + handlerList.addAll(DEFAULT_WRITE_HANDLER_LIST); return handlerList; } diff --git a/src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java index 29ac10b0..e12d98f6 100644 --- a/src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java @@ -1,10 +1,10 @@ package com.alibaba.excel.write.handler; -import org.apache.poi.ss.usermodel.Row; - import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder; +import org.apache.poi.ss.usermodel.Row; + /** * intercepts handle row creation * @@ -16,44 +16,35 @@ public interface RowWriteHandler extends WriteHandler { * Called before create the row * * @param writeSheetHolder - * @param writeTableHolder - * Nullable.It is null without using table writes. + * @param writeTableHolder Nullable.It is null without using table writes. * @param rowIndex - * @param relativeRowIndex - * Nullable.It is null in the case of fill data. - * @param isHead - * Nullable.It is null in the case of fill data. + * @param relativeRowIndex Nullable.It is null in the case of fill data. + * @param isHead Nullable.It is null in the case of fill data. */ - void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex, - Integer relativeRowIndex, Boolean isHead); + default void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex, + Integer relativeRowIndex, Boolean isHead) {} /** * Called after the row is created * * @param writeSheetHolder - * @param writeTableHolder - * Nullable.It is null without using table writes. + * @param writeTableHolder Nullable.It is null without using table writes. * @param row - * @param relativeRowIndex - * Nullable.It is null in the case of fill data. - * @param isHead - * Nullable.It is null in the case of fill data. + * @param relativeRowIndex Nullable.It is null in the case of fill data. + * @param isHead Nullable.It is null in the case of fill data. */ - void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, - Integer relativeRowIndex, Boolean isHead); + 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 writeSheetHolder - * @param writeTableHolder - * Nullable.It is null without using table writes. + * @param writeTableHolder Nullable.It is null without using table writes. * @param row - * @param relativeRowIndex - * Nullable.It is null in the case of fill data. - * @param isHead - * Nullable.It is null in the case of fill data. + * @param relativeRowIndex Nullable.It is null in the case of fill data. + * @param isHead Nullable.It is null in the case of fill data. */ - void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, - Integer relativeRowIndex, Boolean isHead); + default void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, + Integer relativeRowIndex, Boolean isHead) {} } diff --git a/src/main/java/com/alibaba/excel/write/handler/WorkbookWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/WorkbookWriteHandler.java index 8dba9646..c3b758f5 100644 --- a/src/main/java/com/alibaba/excel/write/handler/WorkbookWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/WorkbookWriteHandler.java @@ -12,19 +12,19 @@ public interface WorkbookWriteHandler extends WriteHandler { /** * Called before create the workbook */ - void beforeWorkbookCreate(); + default void beforeWorkbookCreate() {} /** * Called after the workbook is created * * @param writeWorkbookHolder */ - void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder); + default void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) {} /** * Called after all operations on the workbook have been completed * * @param writeWorkbookHolder */ - void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder); + default void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) {} } diff --git a/src/main/java/com/alibaba/excel/write/handler/impl/DefaultRowWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/impl/DefaultRowWriteHandler.java new file mode 100644 index 00000000..36f5ed09 --- /dev/null +++ b/src/main/java/com/alibaba/excel/write/handler/impl/DefaultRowWriteHandler.java @@ -0,0 +1,22 @@ +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 lombok.extern.slf4j.Slf4j; +import org.apache.poi.ss.usermodel.Row; + +/** + * Default row handler. + * + * @author Jiaju Zhuang + */ +@Slf4j +public class DefaultRowWriteHandler implements RowWriteHandler { + @Override + public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, + Integer relativeRowIndex, Boolean isHead) { + writeSheetHolder.setLastRowIndex(row.getRowNum()); + } +} diff --git a/src/main/java/com/alibaba/excel/write/handler/impl/DimensionWorkbookWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/impl/DimensionWorkbookWriteHandler.java new file mode 100644 index 00000000..6e2c8bac --- /dev/null +++ b/src/main/java/com/alibaba/excel/write/handler/impl/DimensionWorkbookWriteHandler.java @@ -0,0 +1,76 @@ +package com.alibaba.excel.write.handler.impl; + +import java.lang.reflect.Field; +import java.util.Map; + +import com.alibaba.excel.util.FieldUtils; +import com.alibaba.excel.write.handler.WorkbookWriteHandler; +import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; +import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.apache.poi.ss.util.CellReference; +import org.apache.poi.xssf.streaming.SXSSFSheet; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; + +/** + * Handle the problem of unable to write dimension. + * + * https://github.com/alibaba/easyexcel/issues/1282 + * + * @author Jiaju Zhuang + */ +@Slf4j +public class DimensionWorkbookWriteHandler implements WorkbookWriteHandler { + + private static final String XSSF_SHEET_MEMBER_VARIABLE_NAME = "_sh"; + private static final Field XSSF_SHEET_FIELD = FieldUtils.getField(SXSSFSheet.class, XSSF_SHEET_MEMBER_VARIABLE_NAME, + true); + + @Override + public void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) { + if (writeWorkbookHolder == null || writeWorkbookHolder.getWorkbook() == null) { + return; + } + if (!(writeWorkbookHolder.getWorkbook() instanceof SXSSFWorkbook)) { + return; + } + + Map writeSheetHolderMap = writeWorkbookHolder.getHasBeenInitializedSheetIndexMap(); + if (MapUtils.isEmpty(writeSheetHolderMap)) { + return; + } + for (WriteSheetHolder writeSheetHolder : writeSheetHolderMap.values()) { + if (writeSheetHolder.getSheet() == null || !(writeSheetHolder.getSheet() instanceof SXSSFSheet)) { + continue; + } + SXSSFSheet sxssfSheet = ((SXSSFSheet)writeSheetHolder.getSheet()); + XSSFSheet xssfSheet; + try { + xssfSheet = (XSSFSheet)XSSF_SHEET_FIELD.get(sxssfSheet); + } catch (IllegalAccessException e) { + log.debug("Can not found _sh.", e); + continue; + } + if (xssfSheet == null) { + continue; + } + CTWorksheet ctWorksheet = xssfSheet.getCTWorksheet(); + if (ctWorksheet == null) { + continue; + } + int headSize = 0; + if (MapUtils.isNotEmpty(writeSheetHolder.getExcelWriteHeadProperty().getHeadMap())) { + headSize = writeSheetHolder.getExcelWriteHeadProperty().getHeadMap().size(); + if (headSize > 0) { + headSize--; + } + } + ctWorksheet.getDimension().setRef( + "A1:" + CellReference.convertNumToColString(headSize) + (writeSheetHolder.getLastRowIndex() + 1)); + } + } +} diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java index 56fc7e4e..afae52b8 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java @@ -3,21 +3,25 @@ package com.alibaba.excel.write.metadata.holder; import java.util.HashMap; import java.util.Map; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFSheet; - import com.alibaba.excel.enums.HolderEnum; import com.alibaba.excel.enums.WriteLastRowTypeEnum; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.write.metadata.WriteSheet; +import lombok.Getter; +import lombok.Setter; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.xssf.streaming.SXSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFSheet; + /** * sheet holder * * @author Jiaju Zhuang */ +@Getter +@Setter public class WriteSheetHolder extends AbstractWriteHolder { /** * current param @@ -65,6 +69,11 @@ public class WriteSheetHolder extends AbstractWriteHolder { */ private WriteLastRowTypeEnum writeLastRowTypeEnum; + /** + * last row index + */ + private Integer lastRowIndex; + public WriteSheetHolder(WriteSheet writeSheet, WriteWorkbookHolder writeWorkbookHolder) { super(writeSheet, writeWorkbookHolder, writeWorkbookHolder.getWriteWorkbook().getConvertAllFiled()); this.writeSheet = writeSheet; @@ -75,76 +84,13 @@ public class WriteSheetHolder extends AbstractWriteHolder { } this.sheetName = writeSheet.getSheetName(); this.parentWriteWorkbookHolder = writeWorkbookHolder; - this.hasBeenInitializedTable = new HashMap(); + this.hasBeenInitializedTable = new HashMap<>(); if (writeWorkbookHolder.getTempTemplateInputStream() != null) { writeLastRowTypeEnum = WriteLastRowTypeEnum.TEMPLATE_EMPTY; } else { writeLastRowTypeEnum = WriteLastRowTypeEnum.COMMON_EMPTY; } - } - - public WriteSheet getWriteSheet() { - return writeSheet; - } - - public void setWriteSheet(WriteSheet writeSheet) { - this.writeSheet = writeSheet; - } - - public Sheet getSheet() { - return sheet; - } - - public void setSheet(Sheet sheet) { - this.sheet = sheet; - } - - public Integer getSheetNo() { - return sheetNo; - } - - public Sheet getCachedSheet() { - return cachedSheet; - } - - public void setCachedSheet(Sheet cachedSheet) { - this.cachedSheet = cachedSheet; - } - - public void setSheetNo(Integer sheetNo) { - this.sheetNo = sheetNo; - } - - public String getSheetName() { - return sheetName; - } - - public void setSheetName(String sheetName) { - this.sheetName = sheetName; - } - - public WriteWorkbookHolder getParentWriteWorkbookHolder() { - return parentWriteWorkbookHolder; - } - - public void setParentWriteWorkbookHolder(WriteWorkbookHolder parentWriteWorkbookHolder) { - this.parentWriteWorkbookHolder = parentWriteWorkbookHolder; - } - - public Map getHasBeenInitializedTable() { - return hasBeenInitializedTable; - } - - public void setHasBeenInitializedTable(Map hasBeenInitializedTable) { - this.hasBeenInitializedTable = hasBeenInitializedTable; - } - - public WriteLastRowTypeEnum getWriteLastRowTypeEnum() { - return writeLastRowTypeEnum; - } - - public void setWriteLastRowTypeEnum(WriteLastRowTypeEnum writeLastRowTypeEnum) { - this.writeLastRowTypeEnum = writeLastRowTypeEnum; + lastRowIndex = 0; } /** diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/simple/Wirte.java b/src/test/java/com/alibaba/easyexcel/test/temp/simple/Wirte.java index 2a907c30..98e77527 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/simple/Wirte.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/simple/Wirte.java @@ -14,6 +14,7 @@ import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.metadata.WriteTable; import com.alibaba.fastjson.JSON; +import lombok.extern.slf4j.Slf4j; import net.sf.cglib.beans.BeanMap; import org.junit.Ignore; import org.junit.Test; @@ -26,6 +27,7 @@ import org.slf4j.LoggerFactory; * @author Jiaju Zhuang **/ @Ignore +@Slf4j public class Wirte { private static final Logger LOGGER = LoggerFactory.getLogger(Wirte.class); @@ -42,6 +44,7 @@ public class Wirte { @Test public void simpleWrite() { + log.info("t5"); // 写法1 String fileName = TestFileUtil.getPath() + "t22" + System.currentTimeMillis() + ".xlsx"; // 这里 需要指定写用哪个class去读,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 From 3ca7cf40fadb93832f56d9be7fae241aaa176cb9 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 20:19:58 +0800 Subject: [PATCH 038/129] =?UTF-8?q?=2007=E7=89=88=E5=9C=A8=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=E7=9A=84=E6=97=B6=E5=80=99=E4=BC=9A=E5=AF=BC=E5=87=BA?= =?UTF-8?q?=20=E8=A1=8C=E6=95=B0=20#1282?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- update.md | 1 + 1 file changed, 1 insertion(+) diff --git a/update.md b/update.md index e033ccc9..44113661 100644 --- a/update.md +++ b/update.md @@ -7,6 +7,7 @@ * 修复`CellData`可能不返回行列号 [Issue #1832](https://github.com/alibaba/easyexcel/issues/1832) * 优化读取性能 * 修复部分情况下不抛出异常 +* 07版在导出的时候会导出 行数 [Issue #1282](https://github.com/alibaba/easyexcel/issues/1282) # 2.2.8 * 兼容07在特殊的excel的情况下,读取数据异常 From 6316eda95876ad90643979de6b75ad522405e171 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 20:23:44 +0800 Subject: [PATCH 039/129] =?UTF-8?q?=E4=B8=8D=E4=BD=BF=E7=94=A8=E5=BC=83?= =?UTF-8?q?=E7=94=A8=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/write/handler/CellWriteHandler.java | 76 +++++++------------ .../write/handler/SheetWriteHandler.java | 4 +- .../excel/write/merge/LoopMergeStrategy.java | 3 +- .../merge/OnceAbsoluteMergeStrategy.java | 3 +- .../AbstractColumnWidthStyleStrategy.java | 3 +- .../test/demo/write/CommentWriteHandler.java | 3 +- .../demo/write/CustomCellWriteHandler.java | 3 +- .../test/temp/simple/WriteCellHandler.java | 3 +- .../test/temp/simple/WriteHandler.java | 3 +- 9 files changed, 45 insertions(+), 56 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java index 8701d6a0..66c7acaf 100644 --- a/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.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.CellData; import com.alibaba.excel.metadata.Head; 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; + /** * intercepts handle cell creation * @@ -21,72 +21,54 @@ public interface CellWriteHandler extends WriteHandler { * Called before create the cell * * @param writeSheetHolder - * @param writeTableHolder - * Nullable.It is null without using table writes. + * @param writeTableHolder Nullable.It is null without using table writes. * @param row - * @param head - * Nullable.It is null in the case of fill data and without head. + * @param head Nullable.It is null in the case of fill data and without head. * @param columnIndex - * @param relativeRowIndex - * Nullable.It is null in the case of fill data. - * @param isHead - * It will always be false when fill data. + * @param relativeRowIndex Nullable.It is null in the case of fill data. + * @param isHead It will always be false when fill data. */ - void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, - Integer columnIndex, Integer relativeRowIndex, Boolean isHead); + default void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, + Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {} /** * Called after the cell is created * * @param writeSheetHolder - * @param writeTableHolder - * Nullable.It is null without using table writes. + * @param writeTableHolder Nullable.It is null without using table writes. * @param cell - * @param head - * Nullable.It is null in the case of fill data and without head. - * @param relativeRowIndex - * Nullable.It is null in the case of fill data. - * @param isHead - * It will always be false when fill data. + * @param head Nullable.It is null in the case of fill data and without head. + * @param relativeRowIndex Nullable.It is null in the case of fill data. + * @param isHead It will always be false when fill data. */ - void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, - Integer relativeRowIndex, Boolean isHead); + default void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, + Head head, Integer relativeRowIndex, Boolean isHead) {} /** * Called after the cell data is converted * * @param writeSheetHolder - * @param writeTableHolder - * Nullable.It is null without using table writes. + * @param writeTableHolder Nullable.It is null without using table writes. * @param cell - * @param head - * Nullable.It is null in the case of fill data and without head. - * @param cellData - * Nullable.It is null in the case of add header. - * @param relativeRowIndex - * Nullable.It is null in the case of fill data. - * @param isHead - * It will always be false when fill data. + * @param head Nullable.It is null in the case of fill data and without head. + * @param cellData Nullable.It is null in the case of add header. + * @param relativeRowIndex Nullable.It is null in the case of fill data. + * @param isHead It will always be false when fill data. */ - void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, - Cell cell, Head head, Integer relativeRowIndex, Boolean isHead); + default void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, + CellData cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {} /** * Called after all operations on the cell have been completed * * @param writeSheetHolder - * @param writeTableHolder - * Nullable.It is null without using table writes. + * @param writeTableHolder Nullable.It is null without using table writes. * @param cell - * @param head - * Nullable.It is null in the case of fill data and without head. - * @param cellDataList - * Nullable.It is null in the case of add header.There may be several when fill the data. - * @param relativeRowIndex - * Nullable.It is null in the case of fill data. - * @param isHead - * It will always be false when fill data. + * @param head Nullable.It is null in the case of fill data and without head. + * @param cellDataList Nullable.It is null in the case of add header.There may be several when fill the data. + * @param relativeRowIndex Nullable.It is null in the case of fill data. + * @param isHead It will always be false when fill data. */ - void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, - List cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead); + default void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, + List cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {} } diff --git a/src/main/java/com/alibaba/excel/write/handler/SheetWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/SheetWriteHandler.java index b97e1d15..5490fd39 100644 --- a/src/main/java/com/alibaba/excel/write/handler/SheetWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/SheetWriteHandler.java @@ -16,7 +16,7 @@ public interface SheetWriteHandler extends WriteHandler { * @param writeWorkbookHolder * @param writeSheetHolder */ - void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder); + default void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {} /** * Called after the sheet is created @@ -24,5 +24,5 @@ public interface SheetWriteHandler extends WriteHandler { * @param writeWorkbookHolder * @param writeSheetHolder */ - void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder); + default void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {} } diff --git a/src/main/java/com/alibaba/excel/write/merge/LoopMergeStrategy.java b/src/main/java/com/alibaba/excel/write/merge/LoopMergeStrategy.java index 5796dde5..13ebe3cb 100644 --- a/src/main/java/com/alibaba/excel/write/merge/LoopMergeStrategy.java +++ b/src/main/java/com/alibaba/excel/write/merge/LoopMergeStrategy.java @@ -5,6 +5,7 @@ import org.apache.poi.ss.util.CellRangeAddress; import com.alibaba.excel.metadata.property.LoopMergeProperty; import com.alibaba.excel.write.handler.AbstractRowWriteHandler; +import com.alibaba.excel.write.handler.RowWriteHandler; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder; @@ -13,7 +14,7 @@ import com.alibaba.excel.write.metadata.holder.WriteTableHolder; * * @author Jiaju Zhuang */ -public class LoopMergeStrategy extends AbstractRowWriteHandler { +public class LoopMergeStrategy implements RowWriteHandler { /** * Each row */ diff --git a/src/main/java/com/alibaba/excel/write/merge/OnceAbsoluteMergeStrategy.java b/src/main/java/com/alibaba/excel/write/merge/OnceAbsoluteMergeStrategy.java index d85781e1..0fe3dd61 100644 --- a/src/main/java/com/alibaba/excel/write/merge/OnceAbsoluteMergeStrategy.java +++ b/src/main/java/com/alibaba/excel/write/merge/OnceAbsoluteMergeStrategy.java @@ -4,6 +4,7 @@ import org.apache.poi.ss.util.CellRangeAddress; import com.alibaba.excel.metadata.property.OnceAbsoluteMergeProperty; import com.alibaba.excel.write.handler.AbstractSheetWriteHandler; +import com.alibaba.excel.write.handler.SheetWriteHandler; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; @@ -12,7 +13,7 @@ import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; * * @author Jiaju Zhuang */ -public class OnceAbsoluteMergeStrategy extends AbstractSheetWriteHandler { +public class OnceAbsoluteMergeStrategy implements SheetWriteHandler { /** * First row */ diff --git a/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java index 005f624e..6393745d 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java @@ -8,6 +8,7 @@ import com.alibaba.excel.event.NotRepeatExecutor; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.write.handler.AbstractCellWriteHandler; +import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder; @@ -16,7 +17,7 @@ import com.alibaba.excel.write.metadata.holder.WriteTableHolder; * * @author Jiaju Zhuang */ -public abstract class AbstractColumnWidthStyleStrategy extends AbstractCellWriteHandler implements NotRepeatExecutor { +public abstract class AbstractColumnWidthStyleStrategy implements CellWriteHandler,NotRepeatExecutor { @Override public String uniqueValue() { diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/CommentWriteHandler.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/CommentWriteHandler.java index 299d4072..d6eacb42 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/CommentWriteHandler.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/CommentWriteHandler.java @@ -8,6 +8,7 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import com.alibaba.excel.write.handler.AbstractRowWriteHandler; +import com.alibaba.excel.write.handler.RowWriteHandler; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder; @@ -16,7 +17,7 @@ import com.alibaba.excel.write.metadata.holder.WriteTableHolder; * * @author Jiaju Zhuang */ -public class CommentWriteHandler extends AbstractRowWriteHandler { +public class CommentWriteHandler implements RowWriteHandler { @Override public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java index b1bcb7dc..1222aa79 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java @@ -12,6 +12,7 @@ import org.slf4j.LoggerFactory; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.write.handler.AbstractCellWriteHandler; +import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder; @@ -20,7 +21,7 @@ import com.alibaba.excel.write.metadata.holder.WriteTableHolder; * * @author Jiaju Zhuang */ -public class CustomCellWriteHandler extends AbstractCellWriteHandler { +public class CustomCellWriteHandler implements CellWriteHandler { private static final Logger LOGGER = LoggerFactory.getLogger(CustomCellWriteHandler.class); diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java b/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java index 726915e7..375cf636 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java @@ -3,6 +3,7 @@ package com.alibaba.easyexcel.test.temp.simple; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.write.handler.AbstractCellWriteHandler; +import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder; @@ -17,7 +18,7 @@ import org.apache.poi.ss.usermodel.IndexedColors; * @author Jiaju Zhuang */ @Slf4j -public class WriteCellHandler extends AbstractCellWriteHandler { +public class WriteCellHandler implements CellWriteHandler { @Override public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteHandler.java b/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteHandler.java index 1420b2b0..a82543eb 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteHandler.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteHandler.java @@ -1,6 +1,7 @@ package com.alibaba.easyexcel.test.temp.simple; import com.alibaba.excel.write.handler.AbstractSheetWriteHandler; +import com.alibaba.excel.write.handler.SheetWriteHandler; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; @@ -10,7 +11,7 @@ import lombok.extern.slf4j.Slf4j; * @author Jiaju Zhuang */ @Slf4j -public class WriteHandler extends AbstractSheetWriteHandler { +public class WriteHandler implements SheetWriteHandler { @Override public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, From 961be2def4805da2216a37d58f8b3ffe31b07e77 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 20:35:03 +0800 Subject: [PATCH 040/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=B2=A1=E6=9C=89?= =?UTF-8?q?=E6=A0=B7=E5=BC=8F=E7=9A=84=E6=83=85=E5=86=B5=E4=B8=8B=E7=A9=BA?= =?UTF-8?q?=E6=8C=87=E9=92=88=E5=BC=82=E5=B8=B8=20#1738?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../analysis/v07/handlers/CellTagHandler.java | 14 +++++++++----- update.md | 2 ++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java index fe5a6421..1ef54e3f 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java @@ -1,8 +1,5 @@ package com.alibaba.excel.analysis.v07.handlers; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.xml.sax.Attributes; - import com.alibaba.excel.constant.BuiltinFormats; import com.alibaba.excel.constant.ExcelXmlConstants; import com.alibaba.excel.context.xlsx.XlsxReadContext; @@ -12,6 +9,10 @@ import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder; import com.alibaba.excel.util.PositionUtils; import com.alibaba.excel.util.StringUtils; +import org.apache.poi.xssf.model.StylesTable; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.xml.sax.Attributes; + /** * Cell Handler * @@ -46,8 +47,11 @@ public class CellTagHandler extends AbstractXlsxTagHandler { } else { dateFormatIndexInteger = Integer.parseInt(dateFormatIndex); } - XSSFCellStyle xssfCellStyle = - xlsxReadContext.xlsxReadWorkbookHolder().getStylesTable().getStyleAt(dateFormatIndexInteger); + StylesTable stylesTable = xlsxReadContext.xlsxReadWorkbookHolder().getStylesTable(); + if (stylesTable == null) { + return; + } + XSSFCellStyle xssfCellStyle = stylesTable.getStyleAt(dateFormatIndexInteger); int dataFormat = xssfCellStyle.getDataFormat(); xlsxReadSheetHolder.getTempCellData().setDataFormat(dataFormat); xlsxReadSheetHolder.getTempCellData().setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormat, diff --git a/update.md b/update.md index 44113661..a735589c 100644 --- a/update.md +++ b/update.md @@ -8,6 +8,8 @@ * 优化读取性能 * 修复部分情况下不抛出异常 * 07版在导出的时候会导出 行数 [Issue #1282](https://github.com/alibaba/easyexcel/issues/1282) +* 修复没有样式的情况下空指针异常 [Issue #1738](https://github.com/alibaba/easyexcel/issues/1738) + # 2.2.8 * 兼容07在特殊的excel的情况下,读取数据异常 From 37b1253f8cbf1923db296a2f237f50e6db7e9d25 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 9 Apr 2021 20:54:24 +0800 Subject: [PATCH 041/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E6=8A=9B=E5=87=BA=E9=80=BB=E8=BE=91=20[Issue=20#1618]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/analysis/v07/XlsxSaxAnalyser.java | 34 +++++++++---------- .../easyexcel/test/temp/Lock2Test.java | 2 +- update.md | 1 + 3 files changed, 19 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java index dbe4e3ab..70c9d05b 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java @@ -9,9 +9,24 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; +import com.alibaba.excel.analysis.ExcelReadExecutor; +import com.alibaba.excel.analysis.v07.handlers.sax.SharedStringsTableHandler; +import com.alibaba.excel.analysis.v07.handlers.sax.XlsxRowHandler; +import com.alibaba.excel.cache.ReadCache; +import com.alibaba.excel.context.xlsx.XlsxReadContext; +import com.alibaba.excel.enums.CellExtraTypeEnum; +import com.alibaba.excel.exception.ExcelAnalysisException; +import com.alibaba.excel.metadata.CellExtra; +import com.alibaba.excel.read.metadata.ReadSheet; +import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadWorkbookHolder; +import com.alibaba.excel.util.FileUtils; +import com.alibaba.excel.util.SheetUtils; +import com.alibaba.excel.util.StringUtils; + import org.apache.commons.collections4.CollectionUtils; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackageAccess; @@ -26,22 +41,9 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr; import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; +import org.xml.sax.SAXException; import org.xml.sax.XMLReader; -import com.alibaba.excel.analysis.ExcelReadExecutor; -import com.alibaba.excel.analysis.v07.handlers.sax.SharedStringsTableHandler; -import com.alibaba.excel.analysis.v07.handlers.sax.XlsxRowHandler; -import com.alibaba.excel.cache.ReadCache; -import com.alibaba.excel.context.xlsx.XlsxReadContext; -import com.alibaba.excel.enums.CellExtraTypeEnum; -import com.alibaba.excel.exception.ExcelAnalysisException; -import com.alibaba.excel.metadata.CellExtra; -import com.alibaba.excel.read.metadata.ReadSheet; -import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadWorkbookHolder; -import com.alibaba.excel.util.FileUtils; -import com.alibaba.excel.util.SheetUtils; -import com.alibaba.excel.util.StringUtils; - /** * @author jipengfei */ @@ -177,9 +179,7 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor { xmlReader.setContentHandler(handler); xmlReader.parse(inputSource); inputStream.close(); - } catch (ExcelAnalysisException e) { - throw e; - } catch (Exception e) { + } catch (IOException | ParserConfigurationException | SAXException e) { throw new ExcelAnalysisException(e); } finally { if (inputStream != null) { diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java index 938e031b..c0246db1 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java @@ -34,7 +34,7 @@ public class Lock2Test { @Test public void test() throws Exception { // File file = TestFileUtil.readUserHomeFile("test/test6.xls"); - File file = new File("D:\\test\\T85_税金入库表202010.xlsx"); + File file = new File("/Users/zhuangjiaju/Downloads/easyexcel_error的副本.xlsx"); List list = EasyExcel.read(file).sheet(0).headRowNumber(0).doReadSync(); LOGGER.info("数据:{}", list.size()); diff --git a/update.md b/update.md index a735589c..bde6bc89 100644 --- a/update.md +++ b/update.md @@ -9,6 +9,7 @@ * 修复部分情况下不抛出异常 * 07版在导出的时候会导出 行数 [Issue #1282](https://github.com/alibaba/easyexcel/issues/1282) * 修复没有样式的情况下空指针异常 [Issue #1738](https://github.com/alibaba/easyexcel/issues/1738) +* 修改异常抛出逻辑 [Issue #1618](https://github.com/alibaba/easyexcel/issues/1618) # 2.2.8 From 0e9bc287a388340641e9e9c22107ad8e2e72abfc Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 12 Apr 2021 14:44:33 +0800 Subject: [PATCH 042/129] =?UTF-8?q?=E5=85=BC=E5=AE=B9=E4=B8=80=E4=BA=9B?= =?UTF-8?q?=E9=9D=9E=E5=AE=98=E6=96=B9excel=E7=9A=84=E6=83=85=E5=86=B5=20[?= =?UTF-8?q?Issue=20#1527]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/analysis/v07/XlsxSaxAnalyser.java | 17 ++++++++++++++++- .../alibaba/easyexcel/test/temp/Lock2Test.java | 2 +- update.md | 1 + 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java index 70c9d05b..7f345c30 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java @@ -27,6 +27,7 @@ import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.util.SheetUtils; import com.alibaba.excel.util.StringUtils; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackageAccess; @@ -47,6 +48,7 @@ import org.xml.sax.XMLReader; /** * @author jipengfei */ +@Slf4j public class XlsxSaxAnalyser implements ExcelReadExecutor { private XlsxReadContext xlsxReadContext; @@ -80,7 +82,9 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor { XSSFReader xssfReader = new XSSFReader(pkg); analysisUse1904WindowDate(xssfReader, xlsxReadWorkbookHolder); - xlsxReadWorkbookHolder.setStylesTable(xssfReader.getStylesTable()); + // set style table + setStylesTable(xlsxReadWorkbookHolder, xssfReader); + sheetList = new ArrayList(); sheetMap = new HashMap(); commentsTableMap = new HashMap(); @@ -103,6 +107,17 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor { } } + private void setStylesTable(XlsxReadWorkbookHolder xlsxReadWorkbookHolder, XSSFReader xssfReader) { + try { + xlsxReadWorkbookHolder.setStylesTable(xssfReader.getStylesTable()); + } catch (Exception e) { + log.warn( + "Currently excel cannot get style information, but it doesn't affect the data analysis.You can try to" + + " save the file with office again or ignore the current error.", + e); + } + } + private void defaultReadCache(XlsxReadWorkbookHolder xlsxReadWorkbookHolder, PackagePart sharedStringsTablePackagePart) { ReadCache readCache = xlsxReadWorkbookHolder.getReadCacheSelector().readCache(sharedStringsTablePackagePart); diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java index c0246db1..e8545670 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java @@ -34,7 +34,7 @@ public class Lock2Test { @Test public void test() throws Exception { // File file = TestFileUtil.readUserHomeFile("test/test6.xls"); - File file = new File("/Users/zhuangjiaju/Downloads/easyexcel_error的副本.xlsx"); + File file = new File("/Users/zhuangjiaju/Downloads/1.xlsx"); List list = EasyExcel.read(file).sheet(0).headRowNumber(0).doReadSync(); LOGGER.info("数据:{}", list.size()); diff --git a/update.md b/update.md index bde6bc89..4e07a60a 100644 --- a/update.md +++ b/update.md @@ -10,6 +10,7 @@ * 07版在导出的时候会导出 行数 [Issue #1282](https://github.com/alibaba/easyexcel/issues/1282) * 修复没有样式的情况下空指针异常 [Issue #1738](https://github.com/alibaba/easyexcel/issues/1738) * 修改异常抛出逻辑 [Issue #1618](https://github.com/alibaba/easyexcel/issues/1618) +* 兼容一些非官方excel的情况 [Issue #1527](https://github.com/alibaba/easyexcel/issues/1527) # 2.2.8 From 46f5ffba9c08a4de4741ed2990ae977f588d304c Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 12 Apr 2021 15:42:11 +0800 Subject: [PATCH 043/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E8=AF=BB=E7=9A=84?= =?UTF-8?q?=E5=85=B3=E9=97=AD=E6=B5=81=E6=97=A0=E6=95=88=20[Issue=20#1840]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/analysis/v07/XlsxSaxAnalyser.java | 7 ++- .../com/alibaba/excel/util/FileUtils.java | 44 +++++++------------ update.md | 1 + 3 files changed, 21 insertions(+), 31 deletions(-) diff --git a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java index f833e79b..1b6e6a8b 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java @@ -164,11 +164,10 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor { xlsxReadWorkbookHolder.setTempFile(readTempFile); File tempFile = new File(readTempFile.getPath(), UUID.randomUUID().toString() + ".xlsx"); if (decryptedStream != null) { - if(xlsxReadWorkbookHolder.getAutoCloseStream()) FileUtils.writeToFile(tempFile, decryptedStream); - else FileUtils.writeToFileNotCloseStream(tempFile, decryptedStream); + FileUtils.writeToFile(tempFile, decryptedStream, false); } else { - if(xlsxReadWorkbookHolder.getAutoCloseStream()) FileUtils.writeToFile(tempFile, xlsxReadWorkbookHolder.getInputStream()); - else FileUtils.writeToFileNotCloseStream(tempFile, xlsxReadWorkbookHolder.getInputStream()); + FileUtils.writeToFile(tempFile, xlsxReadWorkbookHolder.getInputStream(), + xlsxReadWorkbookHolder.getAutoCloseStream()); } return OPCPackage.open(tempFile, PackageAccess.READ); } diff --git a/src/main/java/com/alibaba/excel/util/FileUtils.java b/src/main/java/com/alibaba/excel/util/FileUtils.java index 09192473..bc6b5d8a 100644 --- a/src/main/java/com/alibaba/excel/util/FileUtils.java +++ b/src/main/java/com/alibaba/excel/util/FileUtils.java @@ -9,12 +9,12 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; -import org.apache.poi.util.DefaultTempFileCreationStrategy; -import org.apache.poi.util.TempFile; - import com.alibaba.excel.exception.ExcelAnalysisException; import com.alibaba.excel.exception.ExcelCommonException; +import org.apache.poi.util.DefaultTempFileCreationStrategy; +import org.apache.poi.util.TempFile; + /** * * @author jipengfei @@ -100,10 +100,21 @@ public class FileUtils { /** * Write inputStream to file * - * @param file - * @param inputStream + * @param file file + * @param inputStream inputStream */ public static void writeToFile(File file, InputStream inputStream) { + writeToFile(file, inputStream, true); + } + + /** + * Write inputStream to file + * + * @param file file + * @param inputStream inputStream + * @param closeInputStream closeInputStream + */ + public static void writeToFile(File file, InputStream inputStream, boolean closeInputStream) { OutputStream outputStream = null; try { outputStream = new FileOutputStream(file); @@ -122,7 +133,7 @@ public class FileUtils { throw new ExcelAnalysisException("Can not close 'outputStream'!", e); } } - if (inputStream != null) { + if (inputStream != null && closeInputStream) { try { inputStream.close(); } catch (IOException e) { @@ -132,27 +143,6 @@ public class FileUtils { } } - public static void writeToFileNotCloseStream(File file, InputStream inputStream) { - OutputStream outputStream = null; - try { - outputStream = new FileOutputStream(file); - int bytesRead; - byte[] buffer = new byte[WRITE_BUFF_SIZE]; - while ((bytesRead = inputStream.read(buffer, 0, WRITE_BUFF_SIZE)) != -1) { - outputStream.write(buffer, 0, bytesRead); - } - } catch (Exception e) { - throw new ExcelAnalysisException("Can not create temporary file!", e); - } finally { - if (outputStream != null) { - try { - outputStream.close(); - } catch (IOException e) { - throw new ExcelAnalysisException("Can not close 'outputStream'!", e); - } - } - } - } public static void createPoiFilesDirectory() { File poiFilesPathFile = new File(poiFilesPath); diff --git a/update.md b/update.md index 4e07a60a..119758fb 100644 --- a/update.md +++ b/update.md @@ -11,6 +11,7 @@ * 修复没有样式的情况下空指针异常 [Issue #1738](https://github.com/alibaba/easyexcel/issues/1738) * 修改异常抛出逻辑 [Issue #1618](https://github.com/alibaba/easyexcel/issues/1618) * 兼容一些非官方excel的情况 [Issue #1527](https://github.com/alibaba/easyexcel/issues/1527) +* 修改读的关闭流无效 [Issue #1840](https://github.com/alibaba/easyexcel/issues/1840) # 2.2.8 From e1c9081c4195a0b7e9040b4a55cbd3fb27022315 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 12 Apr 2021 16:43:39 +0800 Subject: [PATCH 044/129] =?UTF-8?q?=E5=86=99=E5=85=A5=E6=94=AF=E6=8C=81Col?= =?UTF-8?q?lection=20[Issue=20#1834]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/excel/ExcelWriter.java | 18 ++--- .../com/alibaba/excel/write/ExcelBuilder.java | 7 +- .../alibaba/excel/write/ExcelBuilderImpl.java | 5 +- .../builder/ExcelWriterSheetBuilder.java | 4 +- .../builder/ExcelWriterTableBuilder.java | 4 +- .../write/executor/ExcelWriteAddExecutor.java | 28 +++++--- .../write/metadata/CollectionRowData.java | 32 +++++++++ .../excel/write/metadata/MapRowData.java | 33 +++++++++ .../alibaba/excel/write/metadata/RowData.java | 31 ++++++++ .../test/core/nomodel/NoModelDataTest.java | 70 +++++++++++++++++++ update.md | 1 + 11 files changed, 205 insertions(+), 28 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/write/metadata/CollectionRowData.java create mode 100644 src/main/java/com/alibaba/excel/write/metadata/MapRowData.java create mode 100644 src/main/java/com/alibaba/excel/write/metadata/RowData.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java diff --git a/src/main/java/com/alibaba/excel/ExcelWriter.java b/src/main/java/com/alibaba/excel/ExcelWriter.java index 0eafecde..2f5b61d2 100644 --- a/src/main/java/com/alibaba/excel/ExcelWriter.java +++ b/src/main/java/com/alibaba/excel/ExcelWriter.java @@ -3,6 +3,8 @@ package com.alibaba.excel; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; import org.slf4j.Logger; @@ -142,7 +144,7 @@ public class ExcelWriter { * Write to this sheet * @return this current writer */ - public ExcelWriter write(List data, WriteSheet writeSheet) { + public ExcelWriter write(Collection data, WriteSheet writeSheet) { return write(data, writeSheet, null); } @@ -157,7 +159,7 @@ public class ExcelWriter { * Write to this table * @return this */ - public ExcelWriter write(List data, WriteSheet writeSheet, WriteTable writeTable) { + public ExcelWriter write(Collection data, WriteSheet writeSheet, WriteTable writeTable) { excelBuilder.addContent(data, writeSheet, writeTable); return this; } @@ -194,7 +196,7 @@ public class ExcelWriter { * @param sheet * Write to this sheet * @return this current writer - * @deprecated please use {@link ExcelWriter#write(List, WriteSheet)} + * @deprecated please use {@link ExcelWriter#write(Collection, WriteSheet)} */ @Deprecated public ExcelWriter write(List data, Sheet sheet) { @@ -211,7 +213,7 @@ public class ExcelWriter { * @param table * Write to this table * @return this - * @deprecated * @deprecated please use {@link ExcelWriter#write(List, WriteSheet,WriteTable)} + * @deprecated * @deprecated please use {@link ExcelWriter#write(Collection, WriteSheet,WriteTable)} */ @Deprecated public ExcelWriter write(List data, Sheet sheet, Table table) { @@ -246,7 +248,7 @@ public class ExcelWriter { * @param sheet * Write to this sheet * @return this current writer - * @deprecated please use {@link ExcelWriter#write(List, WriteSheet)} + * @deprecated please use {@link ExcelWriter#write(Collection, WriteSheet)} */ @Deprecated public ExcelWriter write0(List data, Sheet sheet) { @@ -263,7 +265,7 @@ public class ExcelWriter { * @param table * Write to this table * @return this - * @deprecated * @deprecated please use {@link ExcelWriter#write(List, WriteSheet,WriteTable)} + * @deprecated * @deprecated please use {@link ExcelWriter#write(Collection, WriteSheet,WriteTable)} */ @Deprecated public ExcelWriter write0(List data, Sheet sheet, Table table) { @@ -278,7 +280,7 @@ public class ExcelWriter { * @param sheet * Write to this sheet * @return this current writer - * @deprecated please use {@link ExcelWriter#write(List, WriteSheet)} + * @deprecated please use {@link ExcelWriter#write(Collection, WriteSheet)} */ @Deprecated public ExcelWriter write1(List data, Sheet sheet) { @@ -295,7 +297,7 @@ public class ExcelWriter { * @param table * Write to this table * @return this - * @deprecated * @deprecated please use {@link ExcelWriter#write(List, WriteSheet,WriteTable)} + * @deprecated * @deprecated please use {@link ExcelWriter#write(Collection, WriteSheet,WriteTable)} */ @Deprecated public ExcelWriter write1(List data, Sheet sheet, Table table) { diff --git a/src/main/java/com/alibaba/excel/write/ExcelBuilder.java b/src/main/java/com/alibaba/excel/write/ExcelBuilder.java index d3a50e35..a9f7e601 100644 --- a/src/main/java/com/alibaba/excel/write/ExcelBuilder.java +++ b/src/main/java/com/alibaba/excel/write/ExcelBuilder.java @@ -1,5 +1,6 @@ package com.alibaba.excel.write; +import java.util.Collection; import java.util.List; import com.alibaba.excel.context.WriteContext; @@ -20,10 +21,10 @@ public interface ExcelBuilder { * java basic type or java model extend BaseModel * @param writeSheet * Write the sheet - * @deprecated please use{@link ExcelBuilder#addContent(List, WriteSheet, WriteTable)} + * @deprecated please use{@link ExcelBuilder#addContent(Collection, WriteSheet, WriteTable)} */ @Deprecated - void addContent(List data, WriteSheet writeSheet); + void addContent(Collection data, WriteSheet writeSheet); /** * WorkBook increase value @@ -35,7 +36,7 @@ public interface ExcelBuilder { * @param writeTable * Write the table */ - void addContent(List data, WriteSheet writeSheet, WriteTable writeTable); + void addContent(Collection data, WriteSheet writeSheet, WriteTable writeTable); /** * WorkBook fill value diff --git a/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java b/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java index 2acd5769..e172140d 100644 --- a/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java +++ b/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java @@ -1,6 +1,7 @@ package com.alibaba.excel.write; import java.lang.reflect.Field; +import java.util.Collection; import java.util.List; import org.apache.poi.ss.usermodel.Sheet; @@ -48,12 +49,12 @@ public class ExcelBuilderImpl implements ExcelBuilder { } @Override - public void addContent(List data, WriteSheet writeSheet) { + public void addContent(Collection data, WriteSheet writeSheet) { addContent(data, writeSheet, null); } @Override - public void addContent(List data, WriteSheet writeSheet, WriteTable writeTable) { + public void addContent(Collection data, WriteSheet writeSheet, WriteTable writeTable) { try { context.currentSheet(writeSheet, WriteTypeEnum.ADD); context.currentTable(writeTable); diff --git a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java index f79b7710..0ec448e2 100644 --- a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java +++ b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java @@ -1,6 +1,6 @@ package com.alibaba.excel.write.builder; -import java.util.List; +import java.util.Collection; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.exception.ExcelGenerateException; @@ -54,7 +54,7 @@ public class ExcelWriterSheetBuilder extends AbstractExcelWriterParameterBuilder return writeSheet; } - public void doWrite(List data) { + public void doWrite(Collection data) { if (excelWriter == null) { throw new ExcelGenerateException("Must use 'EasyExcelFactory.write().sheet()' to call this method"); } diff --git a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java index 077361ad..b7a90be9 100644 --- a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java +++ b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java @@ -1,6 +1,6 @@ package com.alibaba.excel.write.builder; -import java.util.List; +import java.util.Collection; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.exception.ExcelGenerateException; @@ -47,7 +47,7 @@ public class ExcelWriterTableBuilder extends AbstractExcelWriterParameterBuilder return writeTable; } - public void doWrite(List data) { + public void doWrite(Collection data) { if (excelWriter == null) { throw new ExcelGenerateException("Must use 'EasyExcelFactory.write().sheet().table()' to call this method"); } diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 529f5d22..194a2233 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -2,8 +2,8 @@ package com.alibaba.excel.write.executor; import java.lang.reflect.Field; import java.util.ArrayList; +import java.util.Collection; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; @@ -17,6 +17,9 @@ import com.alibaba.excel.util.ClassUtils; import com.alibaba.excel.util.FieldUtils; import com.alibaba.excel.util.WorkBookUtil; import com.alibaba.excel.util.WriteHandlerUtils; +import com.alibaba.excel.write.metadata.CollectionRowData; +import com.alibaba.excel.write.metadata.MapRowData; +import com.alibaba.excel.write.metadata.RowData; import com.alibaba.excel.write.metadata.holder.WriteHolder; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; @@ -37,9 +40,9 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { super(writeContext); } - public void add(List data) { + public void add(Collection data) { if (CollectionUtils.isEmpty(data)) { - data = new ArrayList(); + data = new ArrayList<>(); } WriteSheetHolder writeSheetHolder = writeContext.writeSheetHolder(); int newRowIndex = writeSheetHolder.getNewRowIndexAndStartDoWrite(); @@ -47,11 +50,10 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { newRowIndex += writeContext.currentWriteHolder().relativeHeadRowIndex(); } // BeanMap is out of order,so use sortedAllFiledMap - Map sortedAllFiledMap = new TreeMap(); + Map sortedAllFiledMap = new TreeMap<>(); int relativeRowIndex = 0; - int lastRowIndex = 0; for (Object oneRowData : data) { - lastRowIndex = relativeRowIndex + newRowIndex; + int lastRowIndex = relativeRowIndex + newRowIndex; addOneRowOfDataToExcel(oneRowData, lastRowIndex, relativeRowIndex, sortedAllFiledMap); relativeRowIndex++; } @@ -65,16 +67,19 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { WriteHandlerUtils.beforeRowCreate(writeContext, n, relativeRowIndex, Boolean.FALSE); Row row = WorkBookUtil.createRow(writeContext.writeSheetHolder().getSheet(), n); WriteHandlerUtils.afterRowCreate(writeContext, row, relativeRowIndex, Boolean.FALSE); - if (oneRowData instanceof List) { - addBasicTypeToExcel((List)oneRowData, row, relativeRowIndex); + + if (oneRowData instanceof Collection) { + addBasicTypeToExcel(new CollectionRowData((Collection)oneRowData), row, relativeRowIndex); + } else if (oneRowData instanceof Map) { + addBasicTypeToExcel(new MapRowData((Map)oneRowData), row, relativeRowIndex); } else { addJavaObjectToExcel(oneRowData, row, relativeRowIndex, sortedAllFiledMap); } WriteHandlerUtils.afterRowDispose(writeContext, row, relativeRowIndex, Boolean.FALSE); } - private void addBasicTypeToExcel(List oneRowData, Row row, int relativeRowIndex) { - if (CollectionUtils.isEmpty(oneRowData)) { + private void addBasicTypeToExcel(RowData oneRowData, Row row, int relativeRowIndex) { + if (oneRowData.isEmpty()) { return; } Map headMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadMap(); @@ -101,7 +106,8 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { } } - private void doAddBasicTypeToExcel(List 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); diff --git a/src/main/java/com/alibaba/excel/write/metadata/CollectionRowData.java b/src/main/java/com/alibaba/excel/write/metadata/CollectionRowData.java new file mode 100644 index 00000000..bf98f5c5 --- /dev/null +++ b/src/main/java/com/alibaba/excel/write/metadata/CollectionRowData.java @@ -0,0 +1,32 @@ +package com.alibaba.excel.write.metadata; + +import java.util.Collection; + +/** + * A collection row of data. + * + * @author Jiaju Zhuang + */ +public class CollectionRowData implements RowData { + + private final Object[] array; + + public CollectionRowData(Collection collection) { + this.array = collection.toArray(); + } + + @Override + public Object get(int index) { + return array[index]; + } + + @Override + public int size() { + return array.length; + } + + @Override + public boolean isEmpty() { + return array.length == 0; + } +} diff --git a/src/main/java/com/alibaba/excel/write/metadata/MapRowData.java b/src/main/java/com/alibaba/excel/write/metadata/MapRowData.java new file mode 100644 index 00000000..409fc58d --- /dev/null +++ b/src/main/java/com/alibaba/excel/write/metadata/MapRowData.java @@ -0,0 +1,33 @@ +package com.alibaba.excel.write.metadata; + +import java.util.Map; + +/** + * A map row of data. + * + * @author Jiaju Zhuang + */ +public class MapRowData implements RowData { + + private final Map map; + + public MapRowData(Map map) { + this.map = map; + } + + @Override + public Object get(int index) { + return map.get(index); + } + + @Override + public int size() { + return map.size(); + } + + @Override + public boolean isEmpty() { + return map.isEmpty(); + } + +} diff --git a/src/main/java/com/alibaba/excel/write/metadata/RowData.java b/src/main/java/com/alibaba/excel/write/metadata/RowData.java new file mode 100644 index 00000000..937395b9 --- /dev/null +++ b/src/main/java/com/alibaba/excel/write/metadata/RowData.java @@ -0,0 +1,31 @@ +package com.alibaba.excel.write.metadata; + +/** + * A row of data. + * + * @author Jiaju Zhuang + */ +public interface RowData { + /** + * Returns the value to which the specified key is mapped, + * or {@code null} if this map contains no mapping for the key. + */ + Object get(int index); + + /** + * Returns the number of elements in this collection. If this collection + * contains more than Integer.MAX_VALUE elements, returns + * Integer.MAX_VALUE. + * + * @return the number of elements in this collection + */ + int size(); + + /** + * Returns true if this collection contains no elements. + * + * @return true if this collection contains no elements + */ + boolean isEmpty(); + +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java new file mode 100644 index 00000000..a6ff2683 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java @@ -0,0 +1,70 @@ +package com.alibaba.easyexcel.test.core.nomodel; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +/** + * @author Jiaju Zhuang + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class NoModelDataTest { + + private static File file07; + private static File file03; + private static File fileRepeat07; + private static File fileRepeat03; + + @BeforeClass + public static void init() { + file07 = TestFileUtil.createNewFile("noModel07.xlsx"); + file03 = TestFileUtil.createNewFile("noModel03.xls"); + fileRepeat07 = TestFileUtil.createNewFile("noModelRepeat07.xlsx"); + fileRepeat03 = TestFileUtil.createNewFile("noModelRepeat03.xls"); + } + + @Test + public void t01ReadAndWrite07() { + readAndWrite(file07, fileRepeat07); + } + + @Test + public void t02ReadAndWrite03() { + readAndWrite(file03, fileRepeat03); + } + + private void readAndWrite(File file, File fileRepeat) { + EasyExcel.write(file).sheet().doWrite(data()); + List> result = EasyExcel.read(file).headRowNumber(0).sheet().doReadSync(); + Assert.assertEquals(10, result.size()); + Map data10 = result.get(9); + Assert.assertEquals("string19", data10.get(0)); + EasyExcel.write(fileRepeat).sheet().doWrite(result); + result = EasyExcel.read(fileRepeat).headRowNumber(0).sheet().doReadSync(); + Assert.assertEquals(10, result.size()); + data10 = result.get(9); + Assert.assertEquals("string19", data10.get(0)); + } + + private List> data() { + List> list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + List data = new ArrayList<>(); + data.add("string1" + i); + data.add("string2" + i); + data.add("string3" + i); + list.add(data); + } + return list; + } +} diff --git a/update.md b/update.md index 119758fb..09ca62ac 100644 --- a/update.md +++ b/update.md @@ -12,6 +12,7 @@ * 修改异常抛出逻辑 [Issue #1618](https://github.com/alibaba/easyexcel/issues/1618) * 兼容一些非官方excel的情况 [Issue #1527](https://github.com/alibaba/easyexcel/issues/1527) * 修改读的关闭流无效 [Issue #1840](https://github.com/alibaba/easyexcel/issues/1840) +* 写入支持Collection [Issue #1834](https://github.com/alibaba/easyexcel/issues/1834) # 2.2.8 From fdd5d85f22a57426577edb3e2f8563e7989f1c13 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 12 Apr 2021 21:52:42 +0800 Subject: [PATCH 045/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=AF=BC=E5=87=BA=E6=97=A5=E6=9C=9F=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../v03/handlers/FormulaRecordHandler.java | 22 +-- .../v03/handlers/NumberRecordHandler.java | 9 +- .../analysis/v07/handlers/CellTagHandler.java | 2 +- .../excel/constant/BuiltinFormats.java | 6 +- .../alibaba/excel/constant/OrderConstant.java | 13 ++ .../alibaba/excel/converters/Converter.java | 78 +++++--- .../converters/DefaultConverterLoader.java | 23 +-- .../bigdecimal/BigDecimalNumberConverter.java | 8 +- .../bigdecimal/BigDecimalStringConverter.java | 2 +- .../byteconverter/ByteNumberConverter.java | 8 +- .../byteconverter/ByteStringConverter.java | 2 +- .../converters/date/DateDateConverter.java | 34 ++++ .../DoubleNumberConverter.java | 9 +- .../DoubleStringConverter.java | 2 +- .../floatconverter/FloatNumberConverter.java | 11 +- .../floatconverter/FloatStringConverter.java | 2 +- .../integer/IntegerNumberConverter.java | 10 +- .../integer/IntegerStringConverter.java | 2 +- .../longconverter/LongBooleanConverter.java | 10 +- .../longconverter/LongNumberConverter.java | 14 +- .../longconverter/LongStringConverter.java | 8 +- .../shortconverter/ShortBooleanConverter.java | 10 +- .../shortconverter/ShortNumberConverter.java | 13 +- .../shortconverter/ShortStringConverter.java | 2 +- .../alibaba/excel/enums/CellDataTypeEnum.java | 8 +- .../excel/event/AnalysisEventListener.java | 2 +- .../excel/metadata/AbstractHolder.java | 8 +- .../com/alibaba/excel/metadata/CellData.java | 110 +++-------- .../excel/metadata/ConfigurationHolder.java | 2 +- .../excel/metadata/format/DataFormatter.java | 10 +- .../listener/ModelBuildEventListener.java | 48 ++--- .../excel/read/listener/ReadListener.java | 2 +- .../metadata/holder/AbstractReadHolder.java | 18 +- .../DefaultAnalysisEventProcessor.java | 4 +- .../com/alibaba/excel/util/BooleanUtils.java | 75 ++++++++ .../alibaba/excel/util/ConverterUtils.java | 49 +++-- .../com/alibaba/excel/util/DateUtils.java | 24 +-- .../java/com/alibaba/excel/util/IntUtils.java | 9 + .../com/alibaba/excel/util/ListUtils.java | 58 ++++++ .../java/com/alibaba/excel/util/MapUtils.java | 63 +++++++ .../excel/util/NumberDataFormatterUtils.java | 2 +- .../com/alibaba/excel/util/NumberUtils.java | 24 ++- .../com/alibaba/excel/util/WorkBookUtil.java | 25 ++- .../alibaba/excel/util/WriteHandlerUtils.java | 4 +- .../executor/AbstractExcelWriteExecutor.java | 21 ++- .../executor/ExcelWriteFillExecutor.java | 2 +- .../handler/AbstractCellWriteHandler.java | 2 +- .../excel/write/handler/CellWriteHandler.java | 4 +- .../handler/DefaultWriteHandlerLoader.java | 2 + .../impl/FillDataFormatCellWriteHandler.java | 75 ++++++++ .../write/merge/AbstractMergeStrategy.java | 25 +-- .../metadata/holder/AbstractWriteHolder.java | 2 +- .../metadata/holder/WriteWorkbookHolder.java | 174 ++++-------------- .../style/AbstractCellStyleStrategy.java | 38 +--- .../AbstractVerticalCellStyleStrategy.java | 28 ++- .../style/HorizontalCellStyleStrategy.java | 50 ++--- .../AbstractColumnWidthStyleStrategy.java | 4 +- .../AbstractHeadColumnWidthStyleStrategy.java | 2 +- .../LongestMatchColumnWidthStyleStrategy.java | 4 +- .../test/core/handler/WriteHandler.java | 2 +- .../demo/write/CustomCellWriteHandler.java | 2 +- .../test/temp/dataformat/DataFormatTest.java | 4 +- 62 files changed, 746 insertions(+), 540 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/constant/OrderConstant.java create mode 100644 src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java create mode 100644 src/main/java/com/alibaba/excel/util/MapUtils.java create mode 100644 src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/FormulaRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/FormulaRecordHandler.java index f78d4102..5f18b841 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/FormulaRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/FormulaRecordHandler.java @@ -3,14 +3,6 @@ package com.alibaba.excel.analysis.v03.handlers; import java.math.BigDecimal; import java.util.Map; -import com.alibaba.excel.enums.RowTypeEnum; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.ss.usermodel.CellType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler; import com.alibaba.excel.constant.BuiltinFormats; import com.alibaba.excel.context.xls.XlsReadContext; @@ -19,6 +11,13 @@ import com.alibaba.excel.enums.RowTypeEnum; import com.alibaba.excel.metadata.Cell; import com.alibaba.excel.metadata.CellData; +import org.apache.poi.hssf.model.HSSFFormulaParser; +import org.apache.poi.hssf.record.FormulaRecord; +import org.apache.poi.hssf.record.Record; +import org.apache.poi.ss.usermodel.CellType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Record handler * @@ -32,7 +31,7 @@ public class FormulaRecordHandler extends AbstractXlsRecordHandler implements Ig public void processRecord(XlsReadContext xlsReadContext, Record record) { FormulaRecord frec = (FormulaRecord)record; Map cellMap = xlsReadContext.xlsReadSheetHolder().getCellMap(); - CellData tempCellData = new CellData(); + CellData tempCellData = new CellData<>(); tempCellData.setRowIndex(frec.getRow()); tempCellData.setColumnIndex((int)frec.getColumn()); CellType cellType = CellType.forInt(frec.getCachedResultType()); @@ -58,8 +57,9 @@ public class FormulaRecordHandler extends AbstractXlsRecordHandler implements Ig tempCellData.setNumberValue(BigDecimal.valueOf(frec.getValue())); Integer dataFormat = xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatIndex(frec); - tempCellData.setDataFormat(dataFormat); - tempCellData.setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormat, + Short dataFormatShort = dataFormat.shortValue(); + tempCellData.setDataFormat(dataFormatShort); + tempCellData.setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormatShort, xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatString(frec), xlsReadContext.readSheetHolder().getGlobalConfiguration().getLocale())); cellMap.put((int)frec.getColumn(), tempCellData); diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java index 50608095..954acd35 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java @@ -2,15 +2,15 @@ package com.alibaba.excel.analysis.v03.handlers; import java.math.BigDecimal; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.Record; - import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler; import com.alibaba.excel.constant.BuiltinFormats; import com.alibaba.excel.context.xls.XlsReadContext; import com.alibaba.excel.enums.RowTypeEnum; import com.alibaba.excel.metadata.CellData; +import org.apache.poi.hssf.record.NumberRecord; +import org.apache.poi.hssf.record.Record; + /** * Record handler * @@ -22,7 +22,8 @@ public class NumberRecordHandler extends AbstractXlsRecordHandler implements Ign public void processRecord(XlsReadContext xlsReadContext, Record record) { NumberRecord nr = (NumberRecord)record; CellData cellData = CellData.newInstance(BigDecimal.valueOf(nr.getValue()), nr.getRow(), (int)nr.getColumn()); - Integer dataFormat = xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatIndex(nr); + short dataFormat = (short)xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatIndex( + nr); cellData.setDataFormat(dataFormat); cellData.setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormat, xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatString(nr), diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java index 1ef54e3f..135153e0 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java @@ -52,7 +52,7 @@ public class CellTagHandler extends AbstractXlsxTagHandler { return; } XSSFCellStyle xssfCellStyle = stylesTable.getStyleAt(dateFormatIndexInteger); - int dataFormat = xssfCellStyle.getDataFormat(); + short dataFormat = xssfCellStyle.getDataFormat(); xlsxReadSheetHolder.getTempCellData().setDataFormat(dataFormat); xlsxReadSheetHolder.getTempCellData().setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormat, xssfCellStyle.getDataFormatString(), xlsxReadSheetHolder.getGlobalConfiguration().getLocale())); diff --git a/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java b/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java index 95eb0b8f..b525916a 100644 --- a/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java +++ b/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java @@ -17,7 +17,7 @@ import java.util.Locale; **/ public class BuiltinFormats { - private static final String[] BUILTIN_FORMATS_CN = { + public static final String[] BUILTIN_FORMATS_CN = { // 0 "General", // 1 @@ -189,7 +189,7 @@ public class BuiltinFormats { // end }; - private static final String[] BUILTIN_FORMATS_US = { + public static final String[] BUILTIN_FORMATS_US = { // 0 "General", // 1 @@ -361,7 +361,7 @@ public class BuiltinFormats { // end }; - public static String getBuiltinFormat(Integer index, String defaultFormat, Locale locale) { + public static String getBuiltinFormat(Short index, String defaultFormat, Locale locale) { String[] builtinFormat = switchBuiltinFormats(locale); if (index == null || index < 0 || index >= builtinFormat.length) { return defaultFormat; diff --git a/src/main/java/com/alibaba/excel/constant/OrderConstant.java b/src/main/java/com/alibaba/excel/constant/OrderConstant.java new file mode 100644 index 00000000..a955025c --- /dev/null +++ b/src/main/java/com/alibaba/excel/constant/OrderConstant.java @@ -0,0 +1,13 @@ +package com.alibaba.excel.constant; + +/** + * Order constant. + * + * @author Jiaju Zhuang + */ +public class OrderConstant { + /** + * Sorting of styles written to cells. + */ + public static final int FILL_DATA_FORMAT = 10000; +} diff --git a/src/main/java/com/alibaba/excel/converters/Converter.java b/src/main/java/com/alibaba/excel/converters/Converter.java index 8700d127..293daf42 100644 --- a/src/main/java/com/alibaba/excel/converters/Converter.java +++ b/src/main/java/com/alibaba/excel/converters/Converter.java @@ -4,12 +4,16 @@ import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; +import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; +import com.alibaba.excel.write.metadata.holder.WriteHolder; +import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; +import com.alibaba.excel.write.metadata.holder.WriteTableHolder; /** * Convert between Java objects and excel objects * - * @author Dan Zheng * @param + * @author Dan Zheng */ public interface Converter { @@ -18,44 +22,72 @@ public interface Converter { * * @return Support for Java class */ - Class supportJavaTypeKey(); + default Class supportJavaTypeKey() { + throw new UnsupportedOperationException("The current operation is not supported by the current converter."); + } /** * Back to object enum in excel * * @return Support for {@link CellDataTypeEnum} */ - CellDataTypeEnum supportExcelTypeKey(); + default CellDataTypeEnum supportExcelTypeKey() { + throw new UnsupportedOperationException("The current operation is not supported by the current converter."); + } + + /** + * Convert excel objects to Java objects + * + * @param cellData Excel cell data.NotNull. + * @param contentProperty Content property.Nullable. + * @param globalConfiguration Global configuration.NotNull. + * @return Data to put into a Java object + * @throws Exception Exception. + */ + default T convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + GlobalConfiguration globalConfiguration) throws Exception { + throw new UnsupportedOperationException("The current operation is not supported by the current converter."); + } /** * Convert excel objects to Java objects * - * @param cellData - * Excel cell data.NotNull. - * @param contentProperty - * Content property.Nullable. - * @param globalConfiguration - * Global configuration.NotNull. + * @param cellData Excel cell data.NotNull. + * @param contentProperty Content property.Nullable. + * @param readSheetHolder .NotNull. * @return Data to put into a Java object - * @throws Exception - * Exception. + * @throws Exception Exception. + */ + default T convertToJavaData(CellData cellData, + ExcelContentProperty contentProperty, ReadSheetHolder readSheetHolder) throws Exception { + return convertToJavaData(cellData, contentProperty, readSheetHolder.globalConfiguration()); + } + + /** + * Convert Java objects to excel objects + * + * @param value Java Data.NotNull. + * @param contentProperty Content property.Nullable. + * @param globalConfiguration Global configuration.NotNull. + * @return Data to put into a Excel + * @throws Exception Exception. */ - T convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) throws Exception; + default CellData convertToExcelData(T value, ExcelContentProperty contentProperty, + GlobalConfiguration globalConfiguration) throws Exception { + throw new UnsupportedOperationException("The current operation is not supported by the current converter."); + } /** * Convert Java objects to excel objects * - * @param value - * Java Data.NotNull. - * @param contentProperty - * Content property.Nullable. - * @param globalConfiguration - * Global configuration.NotNull. + * @param value Java Data.NotNull. + * @param contentProperty Content property.Nullable. + * @param currentWriteHolder He would be {@link WriteSheetHolder} or {@link WriteTableHolder}.NotNull. * @return Data to put into a Excel - * @throws Exception - * Exception. + * @throws Exception Exception. */ - CellData convertToExcelData(T value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) - throws Exception; + default CellData convertToExcelData(T value, ExcelContentProperty contentProperty, + WriteHolder currentWriteHolder) throws Exception { + return convertToExcelData(value, contentProperty, currentWriteHolder.globalConfiguration()); + } } diff --git a/src/main/java/com/alibaba/excel/converters/DefaultConverterLoader.java b/src/main/java/com/alibaba/excel/converters/DefaultConverterLoader.java index 01822559..09fb9d91 100644 --- a/src/main/java/com/alibaba/excel/converters/DefaultConverterLoader.java +++ b/src/main/java/com/alibaba/excel/converters/DefaultConverterLoader.java @@ -1,6 +1,5 @@ package com.alibaba.excel.converters; -import java.util.HashMap; import java.util.Map; import com.alibaba.excel.converters.bigdecimal.BigDecimalBooleanConverter; @@ -14,6 +13,7 @@ import com.alibaba.excel.converters.bytearray.ByteArrayImageConverter; import com.alibaba.excel.converters.byteconverter.ByteBooleanConverter; import com.alibaba.excel.converters.byteconverter.ByteNumberConverter; import com.alibaba.excel.converters.byteconverter.ByteStringConverter; +import com.alibaba.excel.converters.date.DateDateConverter; import com.alibaba.excel.converters.date.DateNumberConverter; import com.alibaba.excel.converters.date.DateStringConverter; import com.alibaba.excel.converters.doubleconverter.DoubleBooleanConverter; @@ -38,6 +38,7 @@ import com.alibaba.excel.converters.string.StringErrorConverter; import com.alibaba.excel.converters.string.StringNumberConverter; import com.alibaba.excel.converters.string.StringStringConverter; import com.alibaba.excel.converters.url.UrlImageConverter; +import com.alibaba.excel.util.MapUtils; /** * Load default handler @@ -45,8 +46,8 @@ import com.alibaba.excel.converters.url.UrlImageConverter; * @author Jiaju Zhuang */ public class DefaultConverterLoader { - private static Map defaultWriteConverter; - private static Map allConverter; + private static Map> defaultWriteConverter; + private static Map> allConverter; static { initDefaultWriteConverter(); @@ -54,7 +55,7 @@ public class DefaultConverterLoader { } private static void initAllConverter() { - allConverter = new HashMap(64); + allConverter = MapUtils.newHashMapWithExpectedSize(40); putAllConverter(new BigDecimalBooleanConverter()); putAllConverter(new BigDecimalNumberConverter()); putAllConverter(new BigDecimalStringConverter()); @@ -97,11 +98,11 @@ public class DefaultConverterLoader { } private static void initDefaultWriteConverter() { - defaultWriteConverter = new HashMap(32); + defaultWriteConverter = MapUtils.newHashMapWithExpectedSize(20); putWriteConverter(new BigDecimalNumberConverter()); putWriteConverter(new BooleanBooleanConverter()); putWriteConverter(new ByteNumberConverter()); - putWriteConverter(new DateStringConverter()); + putWriteConverter(new DateDateConverter()); putWriteConverter(new DoubleNumberConverter()); putWriteConverter(new FloatNumberConverter()); putWriteConverter(new IntegerNumberConverter()); @@ -120,11 +121,11 @@ public class DefaultConverterLoader { * * @return */ - public static Map loadDefaultWriteConverter() { + public static Map> loadDefaultWriteConverter() { return defaultWriteConverter; } - private static void putWriteConverter(Converter converter) { + private static void putWriteConverter(Converter converter) { defaultWriteConverter.put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey()), converter); } @@ -133,7 +134,7 @@ public class DefaultConverterLoader { * * @return */ - public static Map loadDefaultReadConverter() { + public static Map> loadDefaultReadConverter() { return loadAllConverter(); } @@ -142,11 +143,11 @@ public class DefaultConverterLoader { * * @return */ - public static Map loadAllConverter() { + public static Map> loadAllConverter() { return allConverter; } - private static void putAllConverter(Converter converter) { + private static void putAllConverter(Converter converter) { allConverter.put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey(), converter.supportExcelTypeKey()), converter); } diff --git a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java index bf9b735f..402490c7 100644 --- a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java @@ -7,6 +7,8 @@ import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; 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 @@ -32,8 +34,8 @@ public class BigDecimalNumberConverter implements Converter { } @Override - public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - return new CellData(value); + public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, + WriteHolder currentWriteHolder) { + return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); } } diff --git a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java index 8c5f0f48..c6bd3eae 100644 --- a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java @@ -36,6 +36,6 @@ public class BigDecimalStringConverter implements Converter { @Override public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return NumberUtils.formatToCellData(value, contentProperty); + return NumberUtils.formatToCellDataString(value, contentProperty); } } diff --git a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java index f1facdfb..63a3598a 100644 --- a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java @@ -7,6 +7,8 @@ import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; +import com.alibaba.excel.util.NumberUtils; +import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Byte and number converter @@ -32,9 +34,9 @@ public class ByteNumberConverter implements Converter { } @Override - public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - return new CellData(new BigDecimal(Byte.toString(value))); + public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, + WriteHolder currentWriteHolder) { + return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); } } diff --git a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java index c96114de..e1f014b6 100644 --- a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java @@ -35,7 +35,7 @@ public class ByteStringConverter implements Converter { @Override public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return NumberUtils.formatToCellData(value, contentProperty); + return NumberUtils.formatToCellDataString(value, contentProperty); } } diff --git a/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java b/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java new file mode 100644 index 00000000..0bde87d3 --- /dev/null +++ b/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java @@ -0,0 +1,34 @@ +package com.alibaba.excel.converters.date; + +import java.util.Date; + +import com.alibaba.excel.converters.Converter; +import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.property.ExcelContentProperty; +import com.alibaba.excel.util.WorkBookUtil; +import com.alibaba.excel.write.metadata.holder.WriteHolder; + +/** + * Date and date converter + * + * @author Jiaju Zhuang + */ +public class DateDateConverter implements Converter { + @Override + public Class supportJavaTypeKey() { + return Date.class; + } + + @Override + public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, + WriteHolder currentWriteHolder) throws Exception { + CellData cellData = new CellData<>(value); + if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null + || contentProperty.getDateTimeFormatProperty().getFormat() == null) { + return cellData; + } + WorkBookUtil.fillDataFormat(cellData, currentWriteHolder, + contentProperty.getDateTimeFormatProperty().getFormat()); + return cellData; + } +} diff --git a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java index 15fbdae3..0b9541f5 100644 --- a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java @@ -7,6 +7,8 @@ import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; +import com.alibaba.excel.util.NumberUtils; +import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Double and number converter @@ -32,9 +34,8 @@ public class DoubleNumberConverter implements Converter { } @Override - public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - return new CellData(BigDecimal.valueOf(value)); + public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, + WriteHolder currentWriteHolder) { + return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); } - } diff --git a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java index 2572b4ee..116dc129 100644 --- a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java @@ -35,6 +35,6 @@ public class DoubleStringConverter implements Converter { @Override public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return NumberUtils.formatToCellData(value, contentProperty); + return NumberUtils.formatToCellDataString(value, contentProperty); } } diff --git a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java index 69cc22e7..7d90e4c3 100644 --- a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java @@ -1,12 +1,12 @@ package com.alibaba.excel.converters.floatconverter; -import java.math.BigDecimal; - import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; +import com.alibaba.excel.util.NumberUtils; +import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Float and number converter @@ -32,9 +32,8 @@ public class FloatNumberConverter implements Converter { } @Override - public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - return new CellData(new BigDecimal(Float.toString(value))); + public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, + WriteHolder currentWriteHolder) { + return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); } - } diff --git a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java index ee2ef551..a7fd79f1 100644 --- a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java @@ -35,6 +35,6 @@ public class FloatStringConverter implements Converter { @Override public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return NumberUtils.formatToCellData(value, contentProperty); + return NumberUtils.formatToCellDataString(value, contentProperty); } } diff --git a/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java b/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java index 117d4c11..0edae3e1 100644 --- a/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java @@ -1,12 +1,12 @@ package com.alibaba.excel.converters.integer; -import java.math.BigDecimal; - import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; +import com.alibaba.excel.util.NumberUtils; +import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Integer and number converter @@ -32,9 +32,9 @@ public class IntegerNumberConverter implements Converter { } @Override - public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - return new CellData(new BigDecimal(Integer.toString(value))); + public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, + WriteHolder currentWriteHolder) { + return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); } } diff --git a/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java b/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java index 07bc1b77..a0bad356 100644 --- a/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java @@ -35,6 +35,6 @@ public class IntegerStringConverter implements Converter { @Override public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return NumberUtils.formatToCellData(value, contentProperty); + return NumberUtils.formatToCellDataString(value, contentProperty); } } diff --git a/src/main/java/com/alibaba/excel/converters/longconverter/LongBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/longconverter/LongBooleanConverter.java index 6ee0217b..298fed5e 100644 --- a/src/main/java/com/alibaba/excel/converters/longconverter/LongBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/longconverter/LongBooleanConverter.java @@ -16,7 +16,7 @@ public class LongBooleanConverter implements Converter { private static final Long ZERO = 0L; @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Long.class; } @@ -26,7 +26,7 @@ public class LongBooleanConverter implements Converter { } @Override - public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; @@ -35,12 +35,12 @@ public class LongBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { - return new CellData(Boolean.TRUE); + return new CellData<>(Boolean.TRUE); } - return new CellData(Boolean.FALSE); + return new CellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/longconverter/LongNumberConverter.java b/src/main/java/com/alibaba/excel/converters/longconverter/LongNumberConverter.java index 8058d624..7e4aa235 100644 --- a/src/main/java/com/alibaba/excel/converters/longconverter/LongNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/longconverter/LongNumberConverter.java @@ -1,12 +1,12 @@ package com.alibaba.excel.converters.longconverter; -import java.math.BigDecimal; - import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; +import com.alibaba.excel.util.NumberUtils; +import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Long and number converter @@ -16,7 +16,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; public class LongNumberConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Long.class; } @@ -26,15 +26,15 @@ public class LongNumberConverter implements Converter { } @Override - public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().longValue(); } @Override - public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - return new CellData(BigDecimal.valueOf(value)); + public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, + WriteHolder currentWriteHolder) { + return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); } } diff --git a/src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java b/src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java index 06e94f03..873fb113 100644 --- a/src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java @@ -17,7 +17,7 @@ import com.alibaba.excel.util.NumberUtils; public class LongStringConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Long.class; } @@ -27,14 +27,14 @@ public class LongStringConverter implements Converter { } @Override - public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseLong(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return NumberUtils.formatToCellData(value, contentProperty); + return NumberUtils.formatToCellDataString(value, contentProperty); } } diff --git a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortBooleanConverter.java index 2c0cc61d..eb39b7de 100644 --- a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortBooleanConverter.java @@ -16,7 +16,7 @@ public class ShortBooleanConverter implements Converter { private static final Short ZERO = 0; @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Short.class; } @@ -26,7 +26,7 @@ public class ShortBooleanConverter implements Converter { } @Override - public Short convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Short convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; @@ -35,12 +35,12 @@ public class ShortBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(Short value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Short value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { - return new CellData(Boolean.TRUE); + return new CellData<>(Boolean.TRUE); } - return new CellData(Boolean.FALSE); + return new CellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortNumberConverter.java b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortNumberConverter.java index 357c6aeb..eedfca4f 100644 --- a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortNumberConverter.java @@ -7,6 +7,8 @@ import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; +import com.alibaba.excel.util.NumberUtils; +import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Short and number converter @@ -16,7 +18,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; public class ShortNumberConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Short.class; } @@ -26,15 +28,14 @@ public class ShortNumberConverter implements Converter { } @Override - public Short convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Short convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().shortValue(); } @Override - public CellData convertToExcelData(Short value, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - return new CellData(new BigDecimal(Short.toString(value))); + public CellData convertToExcelData(Short value, ExcelContentProperty contentProperty, + WriteHolder currentWriteHolder) { + return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); } - } diff --git a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java index a683a038..9d78f48e 100644 --- a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java @@ -35,6 +35,6 @@ public class ShortStringConverter implements Converter { @Override public CellData convertToExcelData(Short value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return NumberUtils.formatToCellData(value, contentProperty); + return NumberUtils.formatToCellDataString(value, contentProperty); } } diff --git a/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java b/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java index 44efc179..6220340a 100644 --- a/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java +++ b/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java @@ -39,9 +39,15 @@ public enum CellDataTypeEnum { /** * Images are currently supported only when writing */ - IMAGE; + IMAGE, + /** + * date.Support only when writing. + */ + DATE, + ; private static final Map TYPE_ROUTING_MAP = new HashMap(16); + static { TYPE_ROUTING_MAP.put("s", STRING); TYPE_ROUTING_MAP.put("str", DIRECT_STRING); diff --git a/src/main/java/com/alibaba/excel/event/AnalysisEventListener.java b/src/main/java/com/alibaba/excel/event/AnalysisEventListener.java index 4b1b802a..a0cd5078 100644 --- a/src/main/java/com/alibaba/excel/event/AnalysisEventListener.java +++ b/src/main/java/com/alibaba/excel/event/AnalysisEventListener.java @@ -16,7 +16,7 @@ import com.alibaba.excel.util.ConverterUtils; public abstract class AnalysisEventListener implements ReadListener { @Override - public void invokeHead(Map headMap, AnalysisContext context) { + public void invokeHead(Map> headMap, AnalysisContext context) { invokeHeadMap(ConverterUtils.convertToStringMap(headMap, context), context); } diff --git a/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java b/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java index f7cb1ced..548503d0 100644 --- a/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java +++ b/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java @@ -34,7 +34,7 @@ public abstract class AbstractHolder implements ConfigurationHolder { *

* Write key: */ - private Map converterMap; + private Map> converterMap; public AbstractHolder(BasicParameter basicParameter, AbstractHolder prentAbstractHolder) { this.newInitialization = Boolean.TRUE; @@ -103,16 +103,16 @@ public abstract class AbstractHolder implements ConfigurationHolder { this.globalConfiguration = globalConfiguration; } - public Map getConverterMap() { + public Map> getConverterMap() { return converterMap; } - public void setConverterMap(Map converterMap) { + public void setConverterMap(Map> converterMap) { this.converterMap = converterMap; } @Override - public Map converterMap() { + public Map> converterMap() { return getConverterMap(); } diff --git a/src/main/java/com/alibaba/excel/metadata/CellData.java b/src/main/java/com/alibaba/excel/metadata/CellData.java index ac18fb8a..1cac53c2 100644 --- a/src/main/java/com/alibaba/excel/metadata/CellData.java +++ b/src/main/java/com/alibaba/excel/metadata/CellData.java @@ -1,10 +1,14 @@ package com.alibaba.excel.metadata; import java.math.BigDecimal; +import java.util.Date; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.util.StringUtils; +import lombok.Getter; +import lombok.Setter; + /** * Excel internal cell data. * @@ -12,6 +16,8 @@ import com.alibaba.excel.util.StringUtils; * * @author Jiaju Zhuang */ +@Getter +@Setter public class CellData extends AbstractCell { private CellDataTypeEnum type; /** @@ -30,11 +36,15 @@ public class CellData extends AbstractCell { private String formulaValue; private byte[] imageValue; /** - * The number formatting.Currently only supported when reading + * Support only when writing. + */ + private Date dateValue; + /** + * The number formatting. */ - private Integer dataFormat; + private Short dataFormat; /** - * The string of number formatting.Currently only supported when reading + * The string of number formatting. */ private String dataFormatString; /** @@ -120,86 +130,6 @@ public class CellData extends AbstractCell { this.formula = Boolean.FALSE; } - public CellDataTypeEnum getType() { - return type; - } - - public void setType(CellDataTypeEnum type) { - this.type = type; - } - - public BigDecimal getNumberValue() { - return numberValue; - } - - public void setNumberValue(BigDecimal numberValue) { - this.numberValue = numberValue; - } - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(String stringValue) { - this.stringValue = stringValue; - } - - public Boolean getBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(Boolean booleanValue) { - this.booleanValue = booleanValue; - } - - public Boolean getFormula() { - return formula; - } - - public void setFormula(Boolean formula) { - this.formula = formula; - } - - public String getFormulaValue() { - return formulaValue; - } - - public void setFormulaValue(String formulaValue) { - this.formulaValue = formulaValue; - } - - public byte[] getImageValue() { - return imageValue; - } - - public void setImageValue(byte[] imageValue) { - this.imageValue = imageValue; - } - - public Integer getDataFormat() { - return dataFormat; - } - - public void setDataFormat(Integer dataFormat) { - this.dataFormat = dataFormat; - } - - public String getDataFormatString() { - return dataFormatString; - } - - public void setDataFormatString(String dataFormatString) { - this.dataFormatString = dataFormatString; - } - - public T getData() { - return data; - } - - public void setData(T data) { - this.data = data; - } - /** * Ensure that the object does not appear null */ @@ -271,14 +201,28 @@ public class CellData extends AbstractCell { } switch (type) { case NUMBER: + if (numberValue == null) { + return StringUtils.EMPTY; + } return numberValue.toString(); case BOOLEAN: + if (booleanValue == null) { + return StringUtils.EMPTY; + } return booleanValue.toString(); case DIRECT_STRING: case STRING: case ERROR: return stringValue; + case DATE: + if (dateValue == null) { + return StringUtils.EMPTY; + } + return dateValue.toString(); case IMAGE: + if (imageValue == null) { + return StringUtils.EMPTY; + } return "image[" + imageValue.length + "]"; default: return StringUtils.EMPTY; diff --git a/src/main/java/com/alibaba/excel/metadata/ConfigurationHolder.java b/src/main/java/com/alibaba/excel/metadata/ConfigurationHolder.java index d84b1d58..ee4d7edf 100644 --- a/src/main/java/com/alibaba/excel/metadata/ConfigurationHolder.java +++ b/src/main/java/com/alibaba/excel/metadata/ConfigurationHolder.java @@ -32,5 +32,5 @@ public interface ConfigurationHolder extends Holder { * * @return Converter */ - Map converterMap(); + Map> converterMap(); } diff --git a/src/main/java/com/alibaba/excel/metadata/format/DataFormatter.java b/src/main/java/com/alibaba/excel/metadata/format/DataFormatter.java index be9d2ad6..e9266c71 100644 --- a/src/main/java/com/alibaba/excel/metadata/format/DataFormatter.java +++ b/src/main/java/com/alibaba/excel/metadata/format/DataFormatter.java @@ -170,7 +170,7 @@ public class DataFormatter { this.decimalSymbols = DecimalFormatSymbols.getInstance(this.locale); } - private Format getFormat(Double data,Integer dataFormat, String dataFormatString) { + private Format getFormat(Double data,Short dataFormat, String dataFormatString) { // Might be better to separate out the n p and z formats, falling back to p when n and z are not set. // That however would require other code to be re factored. @@ -225,7 +225,7 @@ public class DataFormatter { return format; } - private Format createFormat(Integer dataFormat, String dataFormatString) { + private Format createFormat(Short dataFormat, String dataFormatString) { String formatStr = dataFormatString; Format format = checkSpecialConverter(formatStr); @@ -607,7 +607,7 @@ public class DataFormatter { * @param dataFormatString * @return Formatted value */ - private String getFormattedDateString(Double data, Integer dataFormat, String dataFormatString) { + private String getFormattedDateString(Double data, Short dataFormat, String dataFormatString) { Format dateFormat = getFormat(data, dataFormat, dataFormatString); if (dateFormat instanceof ExcelStyleDateFormatter) { // Hint about the raw excel value @@ -630,7 +630,7 @@ public class DataFormatter { * @param dataFormatString * @return a formatted number string */ - private String getFormattedNumberString(Double data, Integer dataFormat, String dataFormatString) { + private String getFormattedNumberString(Double data, Short dataFormat, String dataFormatString) { Format numberFormat = getFormat(data, dataFormat, dataFormatString); String formatted = numberFormat.format(data); return formatted.replaceFirst("E(\\d)", "E+$1"); // to match Excel's E-notation @@ -644,7 +644,7 @@ public class DataFormatter { * @param dataFormatString * @return */ - public String format(Double data, Integer dataFormat, String dataFormatString) { + public String format(Double data, Short dataFormat, String dataFormatString) { if (DateUtils.isADateFormat(dataFormat, dataFormatString)) { return getFormattedDateString(data, dataFormat, dataFormatString); } diff --git a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java index 000e298d..13e3d45b 100644 --- a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java +++ b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java @@ -14,7 +14,7 @@ import com.alibaba.excel.exception.ExcelDataConvertException; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.property.ExcelContentProperty; -import com.alibaba.excel.read.metadata.holder.ReadHolder; +import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty; import com.alibaba.excel.util.ConverterUtils; import com.alibaba.excel.util.FieldUtils; @@ -26,28 +26,28 @@ import net.sf.cglib.beans.BeanMap; * * @author jipengfei */ -public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener> { +public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener>> { @Override - public void invokeHead(Map cellDataMap, AnalysisContext context) {} + public void invokeHead(Map> cellDataMap, AnalysisContext context) {} @Override - public void invoke(Map cellDataMap, AnalysisContext context) { - ReadHolder currentReadHolder = context.currentReadHolder(); - if (HeadKindEnum.CLASS.equals(currentReadHolder.excelReadHeadProperty().getHeadKind())) { + public void invoke(Map> cellDataMap, AnalysisContext context) { + ReadSheetHolder readSheetHolder = context.readSheetHolder(); + if (HeadKindEnum.CLASS.equals(readSheetHolder.excelReadHeadProperty().getHeadKind())) { context.readRowHolder() - .setCurrentRowAnalysisResult(buildUserModel(cellDataMap, currentReadHolder, context)); + .setCurrentRowAnalysisResult(buildUserModel(cellDataMap, readSheetHolder, context)); return; } - context.readRowHolder().setCurrentRowAnalysisResult(buildStringList(cellDataMap, currentReadHolder, context)); + context.readRowHolder().setCurrentRowAnalysisResult(buildStringList(cellDataMap, readSheetHolder, context)); } - private Object buildStringList(Map cellDataMap, ReadHolder currentReadHolder, + private Object buildStringList(Map> cellDataMap, ReadSheetHolder readSheetHolder, AnalysisContext context) { int index = 0; if (context.readWorkbookHolder().getDefaultReturnMap()) { Map map = new LinkedHashMap(cellDataMap.size() * 4 / 3 + 1); - for (Map.Entry entry : cellDataMap.entrySet()) { + for (Map.Entry> entry : cellDataMap.entrySet()) { Integer key = entry.getKey(); CellData cellData = entry.getValue(); while (index < key) { @@ -60,10 +60,10 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener continue; } map.put(key, - (String)ConverterUtils.convertToJavaObject(cellData, null, null, currentReadHolder.converterMap(), - currentReadHolder.globalConfiguration(), context.readRowHolder().getRowIndex(), key)); + (String)ConverterUtils.convertToJavaObject(cellData, null, null, readSheetHolder.converterMap(), + readSheetHolder, context.readRowHolder().getRowIndex(), key)); } - int headSize = currentReadHolder.excelReadHeadProperty().getHeadMap().size(); + int headSize = readSheetHolder.excelReadHeadProperty().getHeadMap().size(); while (index < headSize) { map.put(index, null); index++; @@ -71,10 +71,10 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener return map; } else { // Compatible with the old code the old code returns a list - List list = new ArrayList(); - for (Map.Entry entry : cellDataMap.entrySet()) { + List list = new ArrayList<>(); + for (Map.Entry> entry : cellDataMap.entrySet()) { Integer key = entry.getKey(); - CellData cellData = entry.getValue(); + CellData cellData = entry.getValue(); while (index < key) { list.add(null); index++; @@ -85,10 +85,10 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener continue; } list.add( - (String)ConverterUtils.convertToJavaObject(cellData, null, null, currentReadHolder.converterMap(), - currentReadHolder.globalConfiguration(), context.readRowHolder().getRowIndex(), key)); + (String)ConverterUtils.convertToJavaObject(cellData, null, null, readSheetHolder.converterMap(), + readSheetHolder, context.readRowHolder().getRowIndex(), key)); } - int headSize = currentReadHolder.excelReadHeadProperty().getHeadMap().size(); + int headSize = readSheetHolder.excelReadHeadProperty().getHeadMap().size(); while (index < headSize) { list.add(null); index++; @@ -97,15 +97,15 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener } } - private Object buildUserModel(Map cellDataMap, ReadHolder currentReadHolder, + private Object buildUserModel(Map> cellDataMap, ReadSheetHolder readSheetHolder, AnalysisContext context) { - ExcelReadHeadProperty excelReadHeadProperty = currentReadHolder.excelReadHeadProperty(); + ExcelReadHeadProperty excelReadHeadProperty = readSheetHolder.excelReadHeadProperty(); Object resultModel; try { resultModel = excelReadHeadProperty.getHeadClazz().newInstance(); } catch (Exception e) { throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), 0, - new CellData(CellDataTypeEnum.EMPTY), null, + new CellData<>(CellDataTypeEnum.EMPTY), null, "Can not instance class: " + excelReadHeadProperty.getHeadClazz().getName(), e); } Map headMap = excelReadHeadProperty.getHeadMap(); @@ -116,13 +116,13 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener if (!cellDataMap.containsKey(index)) { continue; } - CellData cellData = cellDataMap.get(index); + CellData cellData = cellDataMap.get(index); if (cellData.getType() == CellDataTypeEnum.EMPTY) { continue; } ExcelContentProperty excelContentProperty = contentPropertyMap.get(index); Object value = ConverterUtils.convertToJavaObject(cellData, excelContentProperty.getField(), - excelContentProperty, currentReadHolder.converterMap(), currentReadHolder.globalConfiguration(), + excelContentProperty, readSheetHolder.converterMap(), readSheetHolder, context.readRowHolder().getRowIndex(), index); if (value != null) { map.put(FieldUtils.resolveCglibFieldName(excelContentProperty.getField()), value); diff --git a/src/main/java/com/alibaba/excel/read/listener/ReadListener.java b/src/main/java/com/alibaba/excel/read/listener/ReadListener.java index f1d341f5..b3a2e970 100644 --- a/src/main/java/com/alibaba/excel/read/listener/ReadListener.java +++ b/src/main/java/com/alibaba/excel/read/listener/ReadListener.java @@ -29,7 +29,7 @@ public interface ReadListener extends Listener { * @param headMap * @param context */ - void invokeHead(Map headMap, AnalysisContext context); + void invokeHead(Map> headMap, AnalysisContext context); /** * When analysis one row trigger invoke function. diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java index c431ab49..95bf6f89 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java @@ -1,12 +1,8 @@ package com.alibaba.excel.read.metadata.holder; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.ConverterKeyBuild; import com.alibaba.excel.converters.DefaultConverterLoader; @@ -17,6 +13,10 @@ import com.alibaba.excel.read.listener.ReadListener; import com.alibaba.excel.read.metadata.ReadBasicParameter; import com.alibaba.excel.read.metadata.ReadWorkbook; import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty; +import com.alibaba.excel.util.ListUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Read Holder @@ -24,8 +24,6 @@ import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty; * @author Jiaju Zhuang */ public abstract class AbstractReadHolder extends AbstractHolder implements ReadHolder { - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractReadHolder.class); - /** * Count the number of added heads when read sheet. * @@ -84,9 +82,9 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH } if (parentAbstractReadHolder == null) { - this.readListenerList = new ArrayList(); + this.readListenerList = ListUtils.newArrayList(); } else { - this.readListenerList = new ArrayList(parentAbstractReadHolder.getReadListenerList()); + this.readListenerList = ListUtils.newArrayList(parentAbstractReadHolder.getReadListenerList()); } if (HolderEnum.WORKBOOK.equals(holderType())) { Boolean useDefaultListener = ((ReadWorkbook)readBasicParameter).getUseDefaultListener(); @@ -102,11 +100,11 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH if (parentAbstractReadHolder == null) { setConverterMap(DefaultConverterLoader.loadDefaultReadConverter()); } else { - setConverterMap(new HashMap(parentAbstractReadHolder.getConverterMap())); + setConverterMap(new HashMap<>(parentAbstractReadHolder.getConverterMap())); } if (readBasicParameter.getCustomConverterList() != null && !readBasicParameter.getCustomConverterList().isEmpty()) { - for (Converter converter : readBasicParameter.getCustomConverterList()) { + for (Converter converter : readBasicParameter.getCustomConverterList()) { getConverterMap().put( ConverterKeyBuild.buildKey(converter.supportJavaTypeKey(), converter.supportExcelTypeKey()), converter); diff --git a/src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java b/src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java index ddd19504..f23f58c9 100644 --- a/src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java +++ b/src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java @@ -82,7 +82,7 @@ public class DefaultAnalysisEventProcessor implements AnalysisEventProcessor { private void dealData(AnalysisContext analysisContext) { ReadRowHolder readRowHolder = analysisContext.readRowHolder(); - Map cellDataMap = (Map)readRowHolder.getCellMap(); + Map> 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 cellDataMap) { + private void buildHead(AnalysisContext analysisContext, Map> cellDataMap) { if (!HeadKindEnum.CLASS.equals(analysisContext.currentReadHolder().excelReadHeadProperty().getHeadKind())) { return; } diff --git a/src/main/java/com/alibaba/excel/util/BooleanUtils.java b/src/main/java/com/alibaba/excel/util/BooleanUtils.java index 55c48a18..18f6dd39 100644 --- a/src/main/java/com/alibaba/excel/util/BooleanUtils.java +++ b/src/main/java/com/alibaba/excel/util/BooleanUtils.java @@ -25,4 +25,79 @@ public class BooleanUtils { } } + + // boolean Boolean methods + //----------------------------------------------------------------------- + /** + *

Checks if a {@code Boolean} value is {@code true}, + * handling {@code null} by returning {@code false}.

+ * + *
+     *   BooleanUtils.isTrue(Boolean.TRUE)  = true
+     *   BooleanUtils.isTrue(Boolean.FALSE) = false
+     *   BooleanUtils.isTrue(null)          = false
+     * 
+ * + * @param bool the boolean to check, null returns {@code false} + * @return {@code true} only if the input is non-null and true + * @since 2.1 + */ + public static boolean isTrue(final Boolean bool) { + return Boolean.TRUE.equals(bool); + } + + /** + *

Checks if a {@code Boolean} value is not {@code true}, + * handling {@code null} by returning {@code true}.

+ * + *
+     *   BooleanUtils.isNotTrue(Boolean.TRUE)  = false
+     *   BooleanUtils.isNotTrue(Boolean.FALSE) = true
+     *   BooleanUtils.isNotTrue(null)          = true
+     * 
+ * + * @param bool the boolean to check, null returns {@code true} + * @return {@code true} if the input is null or false + * @since 2.3 + */ + public static boolean isNotTrue(final Boolean bool) { + return !isTrue(bool); + } + + /** + *

Checks if a {@code Boolean} value is {@code false}, + * handling {@code null} by returning {@code false}.

+ * + *
+     *   BooleanUtils.isFalse(Boolean.TRUE)  = false
+     *   BooleanUtils.isFalse(Boolean.FALSE) = true
+     *   BooleanUtils.isFalse(null)          = false
+     * 
+ * + * @param bool the boolean to check, null returns {@code false} + * @return {@code true} only if the input is non-null and false + * @since 2.1 + */ + public static boolean isFalse(final Boolean bool) { + return Boolean.FALSE.equals(bool); + } + + /** + *

Checks if a {@code Boolean} value is not {@code false}, + * handling {@code null} by returning {@code true}.

+ * + *
+     *   BooleanUtils.isNotFalse(Boolean.TRUE)  = true
+     *   BooleanUtils.isNotFalse(Boolean.FALSE) = false
+     *   BooleanUtils.isNotFalse(null)          = true
+     * 
+ * + * @param bool the boolean to check, null returns {@code true} + * @return {@code true} if the input is null or true + * @since 2.3 + */ + public static boolean isNotFalse(final Boolean bool) { + return !isFalse(bool); + } + } diff --git a/src/main/java/com/alibaba/excel/util/ConverterUtils.java b/src/main/java/com/alibaba/excel/util/ConverterUtils.java index 43b12c53..61f69ac4 100644 --- a/src/main/java/com/alibaba/excel/util/ConverterUtils.java +++ b/src/main/java/com/alibaba/excel/util/ConverterUtils.java @@ -3,7 +3,6 @@ package com.alibaba.excel.util; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.util.HashMap; import java.util.Map; import com.alibaba.excel.context.AnalysisContext; @@ -12,9 +11,9 @@ import com.alibaba.excel.converters.ConverterKeyBuild; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.exception.ExcelDataConvertException; import com.alibaba.excel.metadata.CellData; -import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.read.metadata.holder.ReadHolder; +import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; /** * Converting objects @@ -32,13 +31,13 @@ public class ConverterUtils { * @param context * @return */ - public static Map convertToStringMap(Map cellDataMap, AnalysisContext context) { - Map stringMap = new HashMap(cellDataMap.size() * 4 / 3 + 1); - ReadHolder currentReadHolder = context.currentReadHolder(); + public static Map convertToStringMap(Map> cellDataMap, AnalysisContext context) { + Map stringMap = MapUtils.newHashMapWithExpectedSize(cellDataMap.size()); + ReadSheetHolder readSheetHolder = context.readSheetHolder(); int index = 0; - for (Map.Entry entry : cellDataMap.entrySet()) { + for (Map.Entry> entry : cellDataMap.entrySet()) { Integer key = entry.getKey(); - CellData cellData = entry.getValue(); + CellData cellData = entry.getValue(); while (index < key) { stringMap.put(index, null); index++; @@ -48,15 +47,15 @@ public class ConverterUtils { stringMap.put(key, null); continue; } - Converter converter = - currentReadHolder.converterMap().get(ConverterKeyBuild.buildKey(String.class, cellData.getType())); + Converter converter = + readSheetHolder.converterMap().get(ConverterKeyBuild.buildKey(String.class, cellData.getType())); if (converter == null) { throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), key, cellData, null, "Converter not found, convert " + cellData.getType() + " to String"); } try { stringMap.put(key, - (String)(converter.convertToJavaData(cellData, null, currentReadHolder.globalConfiguration()))); + (String)(converter.convertToJavaData(cellData, null, readSheetHolder))); } catch (Exception e) { throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), key, cellData, null, "Convert data " + cellData + " to String error ", e); @@ -72,15 +71,15 @@ public class ConverterUtils { * @param field * @param contentProperty * @param converterMap - * @param globalConfiguration + * @param readSheetHolder * @param rowIndex * @param columnIndex * @return */ - public static Object convertToJavaObject(CellData cellData, Field field, ExcelContentProperty contentProperty, - Map converterMap, GlobalConfiguration globalConfiguration, Integer rowIndex, + public static Object convertToJavaObject(CellData cellData, Field field, ExcelContentProperty contentProperty, + Map> converterMap, ReadSheetHolder readSheetHolder, Integer rowIndex, Integer columnIndex) { - Class clazz; + Class clazz; if (field == null) { clazz = String.class; } else { @@ -88,37 +87,37 @@ public class ConverterUtils { } if (clazz == CellData.class) { Type type = field.getGenericType(); - Class classGeneric; + Class classGeneric; if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; - classGeneric = (Class)parameterizedType.getActualTypeArguments()[0]; + classGeneric = (Class)parameterizedType.getActualTypeArguments()[0]; } else { classGeneric = String.class; } - CellData cellDataReturn = new CellData(cellData); + CellData cellDataReturn = new CellData(cellData); cellDataReturn.setData(doConvertToJavaObject(cellData, classGeneric, contentProperty, converterMap, - globalConfiguration, rowIndex, columnIndex)); + readSheetHolder, rowIndex, columnIndex)); return cellDataReturn; } - return doConvertToJavaObject(cellData, clazz, contentProperty, converterMap, globalConfiguration, rowIndex, + return doConvertToJavaObject(cellData, clazz, contentProperty, converterMap, readSheetHolder, rowIndex, columnIndex); } /** - * * @param cellData * @param clazz * @param contentProperty * @param converterMap - * @param globalConfiguration + * @param readSheetHolder * @param rowIndex * @param columnIndex * @return */ - private static Object doConvertToJavaObject(CellData cellData, Class clazz, ExcelContentProperty contentProperty, - Map converterMap, GlobalConfiguration globalConfiguration, Integer rowIndex, + private static Object doConvertToJavaObject(CellData cellData, Class clazz, + ExcelContentProperty contentProperty, + Map> converterMap, ReadSheetHolder readSheetHolder, Integer rowIndex, Integer columnIndex) { - Converter converter = null; + Converter converter = null; if (contentProperty != null) { converter = contentProperty.getConverter(); } @@ -130,7 +129,7 @@ public class ConverterUtils { "Converter not found, convert " + cellData.getType() + " to " + clazz.getName()); } try { - return converter.convertToJavaData(cellData, contentProperty, globalConfiguration); + return converter.convertToJavaData(cellData, contentProperty, readSheetHolder); } catch (Exception e) { throw new ExcelDataConvertException(rowIndex, columnIndex, cellData, contentProperty, "Convert data " + cellData + " to " + clazz + " error ", e); diff --git a/src/main/java/com/alibaba/excel/util/DateUtils.java b/src/main/java/com/alibaba/excel/util/DateUtils.java index cef0098a..bc85adf6 100644 --- a/src/main/java/com/alibaba/excel/util/DateUtils.java +++ b/src/main/java/com/alibaba/excel/util/DateUtils.java @@ -17,16 +17,16 @@ public class DateUtils { /** * Is a cache of dates */ - private static final ThreadLocal> DATE_THREAD_LOCAL = - new ThreadLocal>(); + private static final ThreadLocal> DATE_THREAD_LOCAL = + new ThreadLocal<>(); /** * Is a cache of dates */ private static final ThreadLocal> DATE_FORMAT_THREAD_LOCAL = - new ThreadLocal>(); + new ThreadLocal<>(); /** - * The following patterns are used in {@link #isADateFormat(Integer, String)} + * The following patterns are used in {@link #isADateFormat(Short, String)} */ private static final Pattern date_ptrn1 = Pattern.compile("^\\[\\$\\-.*?\\]"); private static final Pattern date_ptrn2 = Pattern.compile("^\\[[a-zA-Z]+\\]"); @@ -50,6 +50,8 @@ public class DateUtils { public static final String DATE_FORMAT_19_FORWARD_SLASH = "yyyy/MM/dd HH:mm:ss"; private static final String MINUS = "-"; + public static String defaultDateFormat = DATE_FORMAT_19; + private DateUtils() {} /** @@ -134,7 +136,7 @@ public class DateUtils { return ""; } if (StringUtils.isEmpty(dateFormat)) { - dateFormat = DATE_FORMAT_19; + dateFormat = defaultDateFormat; } return getCacheDateFormat(dateFormat).format(date); } @@ -162,13 +164,13 @@ public class DateUtils { * @param formatString * @return */ - public static boolean isADateFormat(Integer formatIndex, String formatString) { + public static boolean isADateFormat(Short formatIndex, String formatString) { if (formatIndex == null) { return false; } - Map isDateCache = DATE_THREAD_LOCAL.get(); + Map isDateCache = DATE_THREAD_LOCAL.get(); if (isDateCache == null) { - isDateCache = new HashMap(); + isDateCache = MapUtils.newHashMap(); DATE_THREAD_LOCAL.set(isDateCache); } else { Boolean isDateCachedData = isDateCache.get(formatIndex); @@ -188,7 +190,7 @@ public class DateUtils { * @param formatString * @return */ - public static boolean isADateFormatUncached(Integer formatIndex, String formatString) { + public static boolean isADateFormatUncached(Short formatIndex, String formatString) { // First up, is this an internal date format? if (isInternalDateFormat(formatIndex)) { return true; @@ -264,9 +266,9 @@ public class DateUtils { /** * Given a format ID this will check whether the format represents an internal excel date format or not. * - * @see #isADateFormat(Integer, String) + * @see #isADateFormat(Short, String) */ - public static boolean isInternalDateFormat(int format) { + public static boolean isInternalDateFormat(short format) { switch (format) { // Internal Date Formats as described on page 427 in // Microsoft Excel Dev's Kit... diff --git a/src/main/java/com/alibaba/excel/util/IntUtils.java b/src/main/java/com/alibaba/excel/util/IntUtils.java index 0237e452..6d2e244c 100644 --- a/src/main/java/com/alibaba/excel/util/IntUtils.java +++ b/src/main/java/com/alibaba/excel/util/IntUtils.java @@ -10,6 +10,15 @@ import java.util.List; **/ public class IntUtils { private IntUtils() {} + + + /** + * The largest power of two that can be represented as an {@code int}. + * + * @since 10.0 + */ + public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); + /** * Returns the {@code int} nearest in value to {@code value}. * diff --git a/src/main/java/com/alibaba/excel/util/ListUtils.java b/src/main/java/com/alibaba/excel/util/ListUtils.java index 6b4d7499..85d06b4d 100644 --- a/src/main/java/com/alibaba/excel/util/ListUtils.java +++ b/src/main/java/com/alibaba/excel/util/ListUtils.java @@ -1,8 +1,13 @@ package com.alibaba.excel.util; import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; import java.util.List; +import lombok.NonNull; +import org.apache.commons.compress.utils.Iterators; + /** * List utils * @@ -11,6 +16,45 @@ import java.util.List; public class ListUtils { private ListUtils() {} + /** + * Creates a mutable, empty {@code ArrayList} instance (for Java 6 and earlier). + * + *

Note for Java 7 and later: this method is now unnecessary and should be treated as + * deprecated. Instead, use the {@code ArrayList} {@linkplain ArrayList#ArrayList() constructor} + * directly, taking advantage of the new "diamond" syntax. + */ + public static ArrayList newArrayList() { + return new ArrayList<>(); + } + + /** + * Creates a mutable {@code ArrayList} instance containing the given elements; a very thin + * shortcut for creating an empty list and then calling {@link Iterators#addAll}. + * + */ + public static ArrayList newArrayList(Iterator elements) { + ArrayList list = newArrayList(); + Iterators.addAll(list, elements); + return list; + } + + /** + * Creates a mutable {@code ArrayList} instance containing the given elements; + * + * + *

Note for Java 7 and later: if {@code elements} is a {@link Collection}, you don't + * need this method. Use the {@code ArrayList} {@linkplain ArrayList#ArrayList(Collection) + * constructor} directly, taking advantage of the new "diamond" + * syntax. + */ + public static ArrayList newArrayList(Iterable elements) { + checkNotNull(elements); // for GWT + // Let ArrayList's sizing logic work, if possible + return (elements instanceof Collection) + ? new ArrayList<>((Collection)elements) + : newArrayList(elements.iterator()); + } + /** * Creates an {@code ArrayList} instance backed by an array with the specified initial size; * simply delegates to {@link ArrayList#ArrayList(int)}. @@ -60,4 +104,18 @@ public class ListUtils { } return value; } + + /** + * Ensures that an object reference passed as a parameter to the calling method is not null. + * + * @param reference an object reference + * @return the non-null reference that was validated + * @throws NullPointerException if {@code reference} is null + */ + public static T checkNotNull(T reference) { + if (reference == null) { + throw new NullPointerException(); + } + return reference; + } } diff --git a/src/main/java/com/alibaba/excel/util/MapUtils.java b/src/main/java/com/alibaba/excel/util/MapUtils.java new file mode 100644 index 00000000..6af4129e --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/MapUtils.java @@ -0,0 +1,63 @@ +package com.alibaba.excel.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Map utils + * + * @author Jiaju Zhuang + **/ +public class MapUtils { + private MapUtils() {} + /** + * Creates a mutable, empty {@code HashMap} instance. + * + *

Note: if mutability is not required, use {@link ImmutableMap#of()} instead. + * + *

Note: if {@code K} is an {@code enum} type, use {@link #newEnumMap} instead. + * + *

Note for Java 7 and later: this method is now unnecessary and should be treated as + * deprecated. Instead, use the {@code HashMap} constructor directly, taking advantage of the new + * "diamond" syntax. + * + * @return a new, empty {@code HashMap} + */ + public static HashMap newHashMap() { + return new HashMap<>(); + } + + /** + * Creates a {@code HashMap} instance, with a high enough "initial capacity" that it should + * hold {@code expectedSize} elements without growth. This behavior cannot be broadly guaranteed, + * but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method + * isn't inadvertently oversizing the returned map. + * + * @param expectedSize the number of entries you expect to add to the returned map + * @return a new, empty {@code HashMap} with enough capacity to hold {@code expectedSize} entries + * without resizing + * @throws IllegalArgumentException if {@code expectedSize} is negative + */ + public static HashMap newHashMapWithExpectedSize(int expectedSize) { + return new HashMap<>(capacity(expectedSize)); + } + + /** + * Returns a capacity that is sufficient to keep the map from being resized as long as it grows no + * larger than expectedSize and the load factor is ≥ its default (0.75). + */ + static int capacity(int expectedSize) { + if (expectedSize < 3) { + return expectedSize + 1; + } + if (expectedSize < IntUtils.MAX_POWER_OF_TWO) { + // This is the calculation used in JDK8 to resize when a putAll + // happens; it seems to be the most conservative calculation we + // can make. 0.75 is the default load factor. + return (int) ((float) expectedSize / 0.75F + 1.0F); + } + return Integer.MAX_VALUE; + } +} diff --git a/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java b/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java index 09d149b6..de01ad54 100644 --- a/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java +++ b/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java @@ -24,7 +24,7 @@ public class NumberDataFormatterUtils { * @param globalConfiguration * @return */ - public static String format(Double data, Integer dataFormat, String dataFormatString, + public static String format(Double data, Short dataFormat, String dataFormatString, GlobalConfiguration globalConfiguration) { DataFormatter dataFormatter = DATA_FORMATTER_THREAD_LOCAL.get(); if (dataFormatter == null) { diff --git a/src/main/java/com/alibaba/excel/util/NumberUtils.java b/src/main/java/com/alibaba/excel/util/NumberUtils.java index 4257ff44..09a15bea 100644 --- a/src/main/java/com/alibaba/excel/util/NumberUtils.java +++ b/src/main/java/com/alibaba/excel/util/NumberUtils.java @@ -7,6 +7,7 @@ import java.text.ParseException; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; +import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Number utils @@ -46,8 +47,27 @@ public class NumberUtils { * @param contentProperty * @return */ - public static CellData formatToCellData(Number num, ExcelContentProperty contentProperty) { - return new CellData(format(num, contentProperty)); + public static CellData formatToCellDataString(Number num, ExcelContentProperty contentProperty) { + return new CellData<>(format(num, contentProperty)); + } + + /** + * format + * + * @param num + * @param contentProperty + * @param currentWriteHolder + * @return + */ + public static CellData formatToCellData(Number num, ExcelContentProperty contentProperty, + WriteHolder currentWriteHolder) { + CellData cellData = new CellData<>(BigDecimal.valueOf(num.doubleValue())); + if (contentProperty != null && contentProperty.getNumberFormatProperty() != null + && StringUtils.isNotBlank(contentProperty.getNumberFormatProperty().getFormat())) { + WorkBookUtil.fillDataFormat(cellData, currentWriteHolder, + contentProperty.getNumberFormatProperty().getFormat()); + } + return cellData; } /** diff --git a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java index 186708c9..0ee92209 100644 --- a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java +++ b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java @@ -2,6 +2,13 @@ package com.alibaba.excel.util; import java.io.IOException; +import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.support.ExcelTypeEnum; +import com.alibaba.excel.write.metadata.holder.WriteHolder; +import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; +import com.alibaba.excel.write.metadata.holder.WriteTableHolder; +import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; + import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; @@ -13,16 +20,12 @@ import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import com.alibaba.excel.support.ExcelTypeEnum; -import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; - /** - * * @author jipengfei */ public class WorkBookUtil { - private static final int ROW_ACCESS_WINDOW_SIZE = 500; + public static final int ROW_ACCESS_WINDOW_SIZE = 500; private WorkBookUtil() {} @@ -91,4 +94,16 @@ public class WorkBookUtil { cell.setCellValue(cellValue); return cell; } + + public static void fillDataFormat(CellData cellData, WriteHolder currentWriteHolder, String format) { + WriteWorkbookHolder writeWorkbookHolder; + if (currentWriteHolder instanceof WriteSheetHolder) { + writeWorkbookHolder = ((WriteSheetHolder)currentWriteHolder).getParentWriteWorkbookHolder(); + } else { + writeWorkbookHolder = ((WriteTableHolder)currentWriteHolder).getParentWriteSheetHolder() + .getParentWriteWorkbookHolder(); + } + cellData.setDataFormat(writeWorkbookHolder.getDataFormat(format)); + cellData.setDataFormatString(format); + } } diff --git a/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java b/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java index 044e7b2e..cac3f7f8 100644 --- a/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java +++ b/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java @@ -157,14 +157,14 @@ public class WriteHandlerUtils { public static void afterCellDispose(WriteContext writeContext, CellData cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { - List cellDataList = new ArrayList(); + List> cellDataList = new ArrayList<>(); if (cell != null) { cellDataList.add(cellData); } afterCellDispose(writeContext, cellDataList, cell, head, relativeRowIndex, isHead); } - public static void afterCellDispose(WriteContext writeContext, List cellDataList, Cell cell, Head head, + public static void afterCellDispose(WriteContext writeContext, List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { List handlerList = writeContext.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class); diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index 4eb115c5..4aa2d33a 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -1,12 +1,5 @@ package com.alibaba.excel.write.executor; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Sheet; - import com.alibaba.excel.context.WriteContext; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.ConverterKeyBuild; @@ -18,6 +11,13 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.util.WriteHandlerUtils; import com.alibaba.excel.write.metadata.holder.WriteHolder; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.ClientAnchor; +import org.apache.poi.ss.usermodel.CreationHelper; +import org.apache.poi.ss.usermodel.Drawing; +import org.apache.poi.ss.usermodel.Sheet; + /** * Excel write Executor * @@ -56,6 +56,9 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { case NUMBER: cell.setCellValue(cellData.getNumberValue().doubleValue()); return cellData; + case DATE: + cell.setCellValue(cellData.getDateValue()); + return cellData; case IMAGE: setImageValue(cellData, cell); return cellData; @@ -64,7 +67,7 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { default: throw new ExcelDataConvertException(cell.getRow().getRowNum(), cell.getColumnIndex(), cellData, excelContentProperty, "Not supported data:" + value + " return type:" + cell.getCellType() - + "at row:" + cell.getRow().getRowNum()); + + "at row:" + cell.getRow().getRowNum()); } } @@ -113,7 +116,7 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { CellData cellData; try { cellData = - converter.convertToExcelData(value, excelContentProperty, currentWriteHolder.globalConfiguration()); + converter.convertToExcelData(value, excelContentProperty, currentWriteHolder); } catch (Exception e) { throw new ExcelDataConvertException(cell.getRow().getRowNum(), cell.getColumnIndex(), new CellData(CellDataTypeEnum.EMPTY), excelContentProperty, diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 7accb669..0c868a12 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -204,7 +204,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { } else { StringBuilder cellValueBuild = new StringBuilder(); int index = 0; - List cellDataList = new ArrayList(); + List> cellDataList = new ArrayList<>(); for (String variable : analysisCell.getVariableList()) { cellValueBuild.append(analysisCell.getPrepareDataList().get(index++)); if (!dataMap.containsKey(variable)) { diff --git a/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java index 963abc87..6b663ce9 100644 --- a/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java @@ -39,7 +39,7 @@ public abstract class AbstractCellWriteHandler implements CellWriteHandler { @Override public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, - List cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { + List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { } } diff --git a/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java index 66c7acaf..4c9e39ed 100644 --- a/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java @@ -56,7 +56,7 @@ 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) {} + CellData cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {} /** * Called after all operations on the cell have been completed @@ -70,5 +70,5 @@ public interface CellWriteHandler extends WriteHandler { * @param isHead It will always be false when fill data. */ default void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, - List cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {} + List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {} } diff --git a/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java b/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java index 4afefea6..16897076 100644 --- a/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java +++ b/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java @@ -5,6 +5,7 @@ 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.metadata.style.WriteCellStyle; import com.alibaba.excel.write.metadata.style.WriteFont; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy; @@ -43,6 +44,7 @@ public class DefaultWriteHandlerLoader { handlerList.add(new HorizontalCellStyleStrategy(headWriteCellStyle, new ArrayList<>())); } handlerList.addAll(DEFAULT_WRITE_HANDLER_LIST); + handlerList.add(new FillDataFormatCellWriteHandler()); return handlerList; } diff --git a/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java new file mode 100644 index 00000000..3b67d0ca --- /dev/null +++ b/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java @@ -0,0 +1,75 @@ +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.CellData; +import com.alibaba.excel.metadata.Head; +import com.alibaba.excel.util.DateUtils; +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 cellStyleSet = new HashSet<>(); + + private CellStyle defaultDateCellStyle; + + @Override + public int order() { + return OrderConstant.FILL_DATA_FORMAT; + } + + @Override + public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, + List> 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) { + 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; + } + +} diff --git a/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java b/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java index 2a2b7b6d..7b3d4b2b 100644 --- a/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java +++ b/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java @@ -2,42 +2,25 @@ package com.alibaba.excel.write.merge; import java.util.List; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; - import com.alibaba.excel.metadata.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 org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Sheet; + /** * Merge strategy * * @author Jiaju Zhuang */ public abstract class AbstractMergeStrategy implements CellWriteHandler { - @Override - public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, - Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) { - - } - - @Override - public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, - Head head, Integer relativeRowIndex, Boolean isHead) {} - - @Override - public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, - WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer relativeRowIndex, - Boolean isHead) { - - } @Override public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, - List cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { + List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { if (isHead) { return; } diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java index 6ba2c593..59a9909f 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java @@ -207,7 +207,7 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ if (parentAbstractWriteHolder == null) { setConverterMap(DefaultConverterLoader.loadDefaultWriteConverter()); } else { - setConverterMap(new HashMap(parentAbstractWriteHolder.getConverterMap())); + setConverterMap(new HashMap<>(parentAbstractWriteHolder.getConverterMap())); } if (writeBasicParameter.getCustomConverterList() != null && !writeBasicParameter.getCustomConverterList().isEmpty()) { diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java index 8c84f1dc..e3ea80d1 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java @@ -10,23 +10,30 @@ import java.io.OutputStream; import java.util.HashMap; import java.util.Map; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - import com.alibaba.excel.enums.HolderEnum; import com.alibaba.excel.exception.ExcelGenerateException; 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.write.metadata.WriteWorkbook; +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.Workbook; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + /** * Workbook holder * * @author Jiaju Zhuang */ +@Getter +@Setter public class WriteWorkbookHolder extends AbstractWriteHolder { /*** * Current poi Workbook.This is only for writing, and there may be no data in version 07 when template data needs to @@ -111,7 +118,10 @@ 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 cache data Format. + */ + private Map dataFormatCache; public WriteWorkbookHolder(WriteWorkbook writeWorkbook) { super(writeWorkbook, null, writeWorkbook.getConvertAllFiled()); @@ -139,7 +149,7 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { if (writeWorkbook.getExcelType() == null) { boolean isXls = (file != null && file.getName().endsWith(ExcelTypeEnum.XLS.getValue())) || (writeWorkbook.getTemplateFile() != null - && writeWorkbook.getTemplateFile().getName().endsWith(ExcelTypeEnum.XLS.getValue())); + && writeWorkbook.getTemplateFile().getName().endsWith(ExcelTypeEnum.XLS.getValue())); if (isXls) { this.excelType = ExcelTypeEnum.XLS; } else { @@ -166,6 +176,7 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { } else { this.writeExcelOnException = writeWorkbook.getWriteExcelOnException(); } + this.dataFormatCache = MapUtils.newHashMap(); } private void copyTemplate() throws IOException { @@ -187,136 +198,29 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { this.tempTemplateInputStream = new ByteArrayInputStream(templateFileByte); } - public Workbook getWorkbook() { - return workbook; - } - - public void setWorkbook(Workbook workbook) { - this.workbook = workbook; - } - - public Workbook getCachedWorkbook() { - return cachedWorkbook; - } - - public void setCachedWorkbook(Workbook cachedWorkbook) { - this.cachedWorkbook = cachedWorkbook; - } - - public Map getHasBeenInitializedSheetIndexMap() { - return hasBeenInitializedSheetIndexMap; - } - - public void setHasBeenInitializedSheetIndexMap(Map hasBeenInitializedSheetIndexMap) { - this.hasBeenInitializedSheetIndexMap = hasBeenInitializedSheetIndexMap; - } - - public Map getHasBeenInitializedSheetNameMap() { - return hasBeenInitializedSheetNameMap; - } - - public void setHasBeenInitializedSheetNameMap(Map hasBeenInitializedSheetNameMap) { - this.hasBeenInitializedSheetNameMap = hasBeenInitializedSheetNameMap; - } - - public WriteWorkbook getWriteWorkbook() { - return writeWorkbook; - } - - public void setWriteWorkbook(WriteWorkbook writeWorkbook) { - this.writeWorkbook = writeWorkbook; - } - - public File getFile() { - return file; - } - - public void setFile(File file) { - this.file = file; - } - - public OutputStream getOutputStream() { - return outputStream; - } - - public void setOutputStream(OutputStream outputStream) { - this.outputStream = outputStream; - } - - public InputStream getTemplateInputStream() { - return templateInputStream; - } - - public void setTemplateInputStream(InputStream templateInputStream) { - this.templateInputStream = templateInputStream; - } - - public InputStream getTempTemplateInputStream() { - return tempTemplateInputStream; - } - - public void setTempTemplateInputStream(InputStream tempTemplateInputStream) { - this.tempTemplateInputStream = tempTemplateInputStream; - } - - public File getTemplateFile() { - return templateFile; - } - - public void setTemplateFile(File templateFile) { - this.templateFile = templateFile; - } - - public Boolean getAutoCloseStream() { - return autoCloseStream; - } - - public void setAutoCloseStream(Boolean autoCloseStream) { - this.autoCloseStream = autoCloseStream; - } - - public ExcelTypeEnum getExcelType() { - return excelType; - } - - public void setExcelType(ExcelTypeEnum excelType) { - this.excelType = excelType; - } - - public Boolean getMandatoryUseInputStream() { - return mandatoryUseInputStream; - } - - public void setMandatoryUseInputStream(Boolean mandatoryUseInputStream) { - this.mandatoryUseInputStream = mandatoryUseInputStream; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public Boolean getInMemory() { - return inMemory; - } - - public void setInMemory(Boolean inMemory) { - this.inMemory = inMemory; - } - - public Boolean getWriteExcelOnException() { - return writeExcelOnException; - } - - public void setWriteExcelOnException(Boolean writeExcelOnException) { - this.writeExcelOnException = writeExcelOnException; - } - @Override public HolderEnum holderType() { return HolderEnum.WORKBOOK; } + + /** + * Get a data format. + * + * @param format + * @return + */ + public Short getDataFormat(String format) { + if (StringUtils.isEmpty(format)) { + return 0; + } + Short dataFormat = dataFormatCache.get(format); + if (dataFormat != null) { + return dataFormat; + } + DataFormat dataFormatCreate = workbook.createDataFormat(); + dataFormat = dataFormatCreate.getFormat(format); + dataFormatCache.put(format,dataFormat); + return dataFormat; + } + } diff --git a/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java index 14ad9ce5..2e88cc84 100644 --- a/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java @@ -2,20 +2,18 @@ package com.alibaba.excel.write.style; import java.util.List; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Workbook; - import com.alibaba.excel.event.NotRepeatExecutor; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.write.handler.CellWriteHandler; -import com.alibaba.excel.write.handler.SheetWriteHandler; 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 org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Workbook; + /** * Cell style strategy * @@ -30,27 +28,9 @@ public abstract class AbstractCellStyleStrategy implements CellWriteHandler, Wor return "CellStyleStrategy"; } - @Override - public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, - Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) { - - } - - @Override - public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, - Head head, Integer relativeRowIndex, Boolean isHead) { - - } - - @Override - public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, - CellData cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { - - } - @Override public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, - List cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { + List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { if (isHead == null) { return; } @@ -61,22 +41,12 @@ public abstract class AbstractCellStyleStrategy implements CellWriteHandler, Wor } } - @Override - public void beforeWorkbookCreate() { - - } - @Override public void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) { initCellStyle(writeWorkbookHolder.getWorkbook()); hasInitialized = true; } - @Override - public void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) { - - } - /** * Initialization cell style * diff --git a/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java index 197c5cf8..9a9261db 100644 --- a/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java @@ -3,14 +3,14 @@ package com.alibaba.excel.write.style; import java.util.HashMap; import java.util.Map; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Workbook; - import com.alibaba.excel.metadata.Head; import com.alibaba.excel.util.StyleUtil; 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; + /** * Use the same style for the column * @@ -63,7 +63,7 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl } return; } - WriteCellStyle contentCellStyle = contentCellStyle(head); + WriteCellStyle contentCellStyle = contentCellStyle(cell, head, relativeRowIndex); if (contentCellStyle == null) { contentCellStyleCache.put(columnIndex, null); } else { @@ -73,6 +73,18 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl } } + /** + * Returns the column width corresponding to each column head. + * + * @param cell + * @param head + * @param relativeRowIndex + * @return + */ + protected WriteCellStyle contentCellStyle(Cell cell, Head head, Integer relativeRowIndex) { + return contentCellStyle(head); + } + /** * Returns the column width corresponding to each column head * @@ -87,6 +99,10 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl * @param head Nullable * @return */ - protected abstract WriteCellStyle contentCellStyle(Head head); + protected WriteCellStyle contentCellStyle(Head head) { + throw new UnsupportedOperationException( + "One of the two methods 'contentCellStyle(Cell cell, Head head, Integer relativeRowIndex)' and " + + "'contentCellStyle(Head head)' must be implemented."); + } } diff --git a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java index 295cd556..7e8fbe4a 100644 --- a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java @@ -1,29 +1,23 @@ package com.alibaba.excel.write.style; -import java.util.ArrayList; import java.util.List; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Workbook; - import com.alibaba.excel.metadata.Head; -import com.alibaba.excel.util.StyleUtil; +import com.alibaba.excel.util.ListUtils; 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 * * @author Jiaju Zhuang */ -public class HorizontalCellStyleStrategy extends AbstractCellStyleStrategy { - - private WriteCellStyle headWriteCellStyle; - private List contentWriteCellStyleList; +public class HorizontalCellStyleStrategy extends AbstractVerticalCellStyleStrategy { - private CellStyle headCellStyle; - private List contentCellStyleList; + private final WriteCellStyle headWriteCellStyle; + private final List contentWriteCellStyleList; public HorizontalCellStyleStrategy(WriteCellStyle headWriteCellStyle, List contentWriteCellStyleList) { @@ -33,37 +27,21 @@ public class HorizontalCellStyleStrategy extends AbstractCellStyleStrategy { public HorizontalCellStyleStrategy(WriteCellStyle headWriteCellStyle, WriteCellStyle contentWriteCellStyle) { this.headWriteCellStyle = headWriteCellStyle; - contentWriteCellStyleList = new ArrayList(); + contentWriteCellStyleList = ListUtils.newArrayList(); contentWriteCellStyleList.add(contentWriteCellStyle); } @Override - protected void initCellStyle(Workbook workbook) { - if (headWriteCellStyle != null) { - headCellStyle = StyleUtil.buildHeadCellStyle(workbook, headWriteCellStyle); - } - if (contentWriteCellStyleList != null && !contentWriteCellStyleList.isEmpty()) { - contentCellStyleList = new ArrayList(); - for (WriteCellStyle writeCellStyle : contentWriteCellStyleList) { - contentCellStyleList.add(StyleUtil.buildContentCellStyle(workbook, writeCellStyle)); - } - } - } - - @Override - protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) { - if (headCellStyle == null) { - return; - } - cell.setCellStyle(headCellStyle); + protected WriteCellStyle headCellStyle(Head head) { + return headWriteCellStyle; } @Override - protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) { - if (contentCellStyleList == null || contentCellStyleList.isEmpty()) { - return; + protected WriteCellStyle contentCellStyle(Cell cell, Head head, Integer relativeRowIndex) { + if (CollectionUtils.isEmpty(contentWriteCellStyleList)) { + return null; } - cell.setCellStyle(contentCellStyleList.get(relativeRowIndex % contentCellStyleList.size())); + return contentWriteCellStyleList.get(relativeRowIndex % contentWriteCellStyleList.size()); } } diff --git a/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java index 6393745d..277f96b9 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java @@ -26,7 +26,7 @@ public abstract class AbstractColumnWidthStyleStrategy implements CellWriteHandl @Override public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, - List cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { + List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { setColumnWidth(writeSheetHolder, cellDataList, cell, head, relativeRowIndex, isHead); } @@ -40,7 +40,7 @@ public abstract class AbstractColumnWidthStyleStrategy implements CellWriteHandl * @param relativeRowIndex * @param isHead */ - protected abstract void setColumnWidth(WriteSheetHolder writeSheetHolder, List cellDataList, Cell cell, + protected abstract void setColumnWidth(WriteSheetHolder writeSheetHolder, List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead); } diff --git a/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java index 1a88eff6..d306d2e4 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java @@ -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 cellDataList, Cell cell, Head head, + protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { boolean needSetWidth = relativeRowIndex != null && (isHead || relativeRowIndex == 0); if (!needSetWidth) { diff --git a/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java index 717077dc..c6cc9df1 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java @@ -27,7 +27,7 @@ public class LongestMatchColumnWidthStyleStrategy extends AbstractColumnWidthSty private Map> cache = new HashMap>(8); @Override - protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List cellDataList, Cell cell, Head head, + protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList); if (!needSetWidth) { @@ -52,7 +52,7 @@ public class LongestMatchColumnWidthStyleStrategy extends AbstractColumnWidthSty } } - private Integer dataLength(List cellDataList, Cell cell, Boolean isHead) { + private Integer dataLength(List> cellDataList, Cell cell, Boolean isHead) { if (isHead) { return cell.getStringCellValue().getBytes().length; } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java b/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java index c762db79..cf9c5d26 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java @@ -98,7 +98,7 @@ public class WriteHandler implements WorkbookWriteHandler, SheetWriteHandler, Ro @Override public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, - List cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { + List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { if (isHead) { Assert.assertEquals(1L, beforeCellCreate); Assert.assertEquals(1L, afterCellCreate); diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java index 1222aa79..b4ade88f 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java @@ -27,7 +27,7 @@ public class CustomCellWriteHandler implements CellWriteHandler { @Override public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, - List cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { + List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { // 这里可以对cell进行任何操作 LOGGER.info("第{}行,第{}列写入完成。", cell.getRowIndex(), cell.getColumnIndex()); if (isHead && cell.getColumnIndex() == 0) { diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatTest.java index e165d987..53902240 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatTest.java @@ -44,7 +44,7 @@ public class DataFormatTest { EasyExcel.read(file, DataFormatData.class, null).sheet().headRowNumber(0).doReadSync(); LOGGER.info("数据:{}", list.size()); for (DataFormatData data : list) { - Integer dataFormat = data.getDate().getDataFormat(); + Short dataFormat = data.getDate().getDataFormat(); String dataFormatString = data.getDate().getDataFormatString(); @@ -67,7 +67,7 @@ public class DataFormatTest { EasyExcel.read(file, DataFormatData.class, null).sheet().headRowNumber(0).doReadSync(); LOGGER.info("数据:{}", list.size()); for (DataFormatData data : list) { - Integer dataFormat = data.getDate().getDataFormat(); + Short dataFormat = data.getDate().getDataFormat(); String dataFormatString = data.getDate().getDataFormatString(); From 55551799bdca9d8ced5d85df2a63c090af4c732f Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Tue, 13 Apr 2021 14:46:30 +0800 Subject: [PATCH 046/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E5=A1=AB=E5=85=85=E6=97=A5=E6=9C=9F=E6=A0=BC=E5=BC=8F=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../v03/handlers/NumberRecordHandler.java | 2 +- .../v03/handlers/StringRecordHandler.java | 2 +- .../CellInlineStringValueTagHandler.java | 2 +- .../excel/constant/BuiltinFormats.java | 2 + .../excel/converters/AutoConverter.java | 8 ++-- .../alibaba/excel/converters/Converter.java | 2 +- .../excel/converters/ConverterKeyBuild.java | 14 ++++--- .../converters/DefaultConverterLoader.java | 19 ++++++++- .../BigDecimalBooleanConverter.java | 10 ++--- .../bigdecimal/BigDecimalNumberConverter.java | 4 +- .../bigdecimal/BigDecimalStringConverter.java | 6 +-- .../BooleanBooleanConverter.java | 8 ++-- .../BooleanNumberConverter.java | 10 ++--- .../BooleanStringConverter.java | 8 ++-- .../BoxingByteArrayImageConverter.java | 8 ++-- .../bytearray/ByteArrayImageConverter.java | 8 ++-- .../byteconverter/ByteBooleanConverter.java | 10 ++--- .../byteconverter/ByteNumberConverter.java | 4 +- .../byteconverter/ByteStringConverter.java | 6 +-- .../converters/date/DateDateConverter.java | 13 ++++++ .../converters/date/DateNumberConverter.java | 10 ++--- .../converters/date/DateStringConverter.java | 10 ++--- .../DoubleBooleanConverter.java | 10 ++--- .../DoubleNumberConverter.java | 4 +- .../DoubleStringConverter.java | 6 +-- .../converters/file/FileImageConverter.java | 8 ++-- .../floatconverter/FloatBooleanConverter.java | 10 ++--- .../floatconverter/FloatNumberConverter.java | 4 +- .../floatconverter/FloatStringConverter.java | 6 +-- .../InputStreamImageConverter.java | 8 ++-- .../integer/IntegerBooleanConverter.java | 10 ++--- .../integer/IntegerNumberConverter.java | 4 +- .../integer/IntegerStringConverter.java | 6 +-- .../shortconverter/ShortStringConverter.java | 6 +-- .../string/StringBooleanConverter.java | 8 ++-- .../string/StringErrorConverter.java | 8 ++-- .../string/StringImageConverter.java | 8 ++-- .../string/StringNumberConverter.java | 8 ++-- .../string/StringStringConverter.java | 8 ++-- .../converters/url/UrlImageConverter.java | 8 ++-- .../exception/ExcelDataConvertException.java | 38 +++-------------- .../com/alibaba/excel/metadata/CellData.java | 30 +++++++++----- .../read/metadata/holder/ReadSheetHolder.java | 6 +-- .../com/alibaba/excel/util/StyleUtil.java | 20 +++++++-- .../alibaba/excel/util/WriteHandlerUtils.java | 34 ++++++++------- .../executor/AbstractExcelWriteExecutor.java | 41 ++++++++++--------- .../write/executor/ExcelWriteAddExecutor.java | 10 ++--- .../executor/ExcelWriteFillExecutor.java | 8 ++-- .../impl/DimensionWorkbookWriteHandler.java | 7 +++- .../impl/FillDataFormatCellWriteHandler.java | 3 +- .../metadata/holder/WriteWorkbookHolder.java | 3 +- .../property/ExcelWriteHeadProperty.java | 8 ---- .../AbstractVerticalCellStyleStrategy.java | 4 +- .../style/HorizontalCellStyleStrategy.java | 2 +- .../test/core/annotation/AnnotationData.java | 3 +- .../test/core/celldata/CellDataData.java | 2 +- .../test/core/celldata/CellDataDataTest.java | 2 +- .../test/core/converter/ConverterData.java | 2 +- .../test/core/nomodel/NoModelDataTest.java | 22 ++++++---- .../easyexcel/test/demo/fill/FillTest.java | 5 ++- .../easyexcel/test/temp/poi/TestCell.java | 2 +- 61 files changed, 294 insertions(+), 254 deletions(-) diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java index 954acd35..f9e27c7a 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java @@ -21,7 +21,7 @@ public class NumberRecordHandler extends AbstractXlsRecordHandler implements Ign @Override public void processRecord(XlsReadContext xlsReadContext, Record record) { NumberRecord nr = (NumberRecord)record; - CellData cellData = CellData.newInstance(BigDecimal.valueOf(nr.getValue()), nr.getRow(), (int)nr.getColumn()); + CellDatacellData = CellData.newInstance(BigDecimal.valueOf(nr.getValue()), nr.getRow(), (int)nr.getColumn()); short dataFormat = (short)xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatIndex( nr); cellData.setDataFormat(dataFormat); diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/StringRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/StringRecordHandler.java index 3b95cfdb..2408d219 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/StringRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/StringRecordHandler.java @@ -23,7 +23,7 @@ public class StringRecordHandler extends AbstractXlsRecordHandler implements Ign // String for formula StringRecord srec = (StringRecord)record; XlsReadSheetHolder xlsReadSheetHolder = xlsReadContext.xlsReadSheetHolder(); - CellData tempCellData = xlsReadSheetHolder.getTempCellData(); + CellDatatempCellData = xlsReadSheetHolder.getTempCellData(); if (tempCellData == null) { LOGGER.warn("String type formula but no value found."); return; diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellInlineStringValueTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellInlineStringValueTagHandler.java index 277348a7..3058e8e8 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellInlineStringValueTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellInlineStringValueTagHandler.java @@ -15,7 +15,7 @@ public class CellInlineStringValueTagHandler extends AbstractCellValueTagHandler @Override protected void setStringValue(XlsxReadContext xlsxReadContext) { // This is a special form of string - CellData tempCellData = xlsxReadContext.xlsxReadSheetHolder().getTempCellData(); + CellData tempCellData = xlsxReadContext.xlsxReadSheetHolder().getTempCellData(); XSSFRichTextString richTextString = new XSSFRichTextString(tempCellData.getStringValue()); tempCellData.setStringValue(richTextString.toString()); } diff --git a/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java b/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java index b525916a..b742cb6c 100644 --- a/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java +++ b/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java @@ -17,6 +17,8 @@ import java.util.Locale; **/ public class BuiltinFormats { + public static short GENERAL = 0; + public static final String[] BUILTIN_FORMATS_CN = { // 0 "General", diff --git a/src/main/java/com/alibaba/excel/converters/AutoConverter.java b/src/main/java/com/alibaba/excel/converters/AutoConverter.java index 800d2d85..07ad471f 100644 --- a/src/main/java/com/alibaba/excel/converters/AutoConverter.java +++ b/src/main/java/com/alibaba/excel/converters/AutoConverter.java @@ -10,10 +10,10 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; * * @author Jiaju Zhuang */ -public class AutoConverter implements Converter { +public class AutoConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return null; } @@ -23,13 +23,13 @@ public class AutoConverter implements Converter { } @Override - public Object convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Object convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return null; } @Override - public CellData convertToExcelData(Object value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Object value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return null; } diff --git a/src/main/java/com/alibaba/excel/converters/Converter.java b/src/main/java/com/alibaba/excel/converters/Converter.java index 293daf42..3d1a369d 100644 --- a/src/main/java/com/alibaba/excel/converters/Converter.java +++ b/src/main/java/com/alibaba/excel/converters/Converter.java @@ -22,7 +22,7 @@ public interface Converter { * * @return Support for Java class */ - default Class supportJavaTypeKey() { + default Class supportJavaTypeKey() { throw new UnsupportedOperationException("The current operation is not supported by the current converter."); } diff --git a/src/main/java/com/alibaba/excel/converters/ConverterKeyBuild.java b/src/main/java/com/alibaba/excel/converters/ConverterKeyBuild.java index 0bd54991..a92f3033 100644 --- a/src/main/java/com/alibaba/excel/converters/ConverterKeyBuild.java +++ b/src/main/java/com/alibaba/excel/converters/ConverterKeyBuild.java @@ -1,9 +1,9 @@ package com.alibaba.excel.converters; -import java.util.HashMap; import java.util.Map; import com.alibaba.excel.enums.CellDataTypeEnum; +import com.alibaba.excel.util.MapUtils; /** * Converter unique key.Consider that you can just use class as the key. @@ -12,7 +12,7 @@ import com.alibaba.excel.enums.CellDataTypeEnum; */ public class ConverterKeyBuild { - private static final Map BOXING_MAP = new HashMap(16); + private static final Map BOXING_MAP = MapUtils.newHashMap(); static { BOXING_MAP.put(int.class.getName(), Integer.class.getName()); @@ -25,7 +25,7 @@ public class ConverterKeyBuild { BOXING_MAP.put(boolean.class.getName(), Boolean.class.getName()); } - public static String buildKey(Class clazz) { + public static String buildKey(Class clazz) { String className = clazz.getName(); String boxingClassName = BOXING_MAP.get(clazz.getName()); if (boxingClassName == null) { @@ -34,7 +34,11 @@ public class ConverterKeyBuild { return boxingClassName; } - public static String buildKey(Class clazz, CellDataTypeEnum cellDataTypeEnum) { - return buildKey(clazz) + "-" + cellDataTypeEnum.toString(); + public static String buildKey(Class clazz, CellDataTypeEnum cellDataTypeEnum) { + String key = buildKey(clazz); + if (cellDataTypeEnum == null) { + return key; + } + return key + "-" + cellDataTypeEnum.toString(); } } diff --git a/src/main/java/com/alibaba/excel/converters/DefaultConverterLoader.java b/src/main/java/com/alibaba/excel/converters/DefaultConverterLoader.java index 09fb9d91..b4cabe0d 100644 --- a/src/main/java/com/alibaba/excel/converters/DefaultConverterLoader.java +++ b/src/main/java/com/alibaba/excel/converters/DefaultConverterLoader.java @@ -98,7 +98,7 @@ public class DefaultConverterLoader { } private static void initDefaultWriteConverter() { - defaultWriteConverter = MapUtils.newHashMapWithExpectedSize(20); + defaultWriteConverter = MapUtils.newHashMapWithExpectedSize(40); putWriteConverter(new BigDecimalNumberConverter()); putWriteConverter(new BooleanBooleanConverter()); putWriteConverter(new ByteNumberConverter()); @@ -114,6 +114,18 @@ public class DefaultConverterLoader { putWriteConverter(new ByteArrayImageConverter()); putWriteConverter(new BoxingByteArrayImageConverter()); putWriteConverter(new UrlImageConverter()); + + // In some cases, it must be converted to string + putWriteStringConverter(new BigDecimalStringConverter()); + putWriteStringConverter(new BooleanStringConverter()); + putWriteStringConverter(new ByteStringConverter()); + putWriteStringConverter(new DateStringConverter()); + putWriteStringConverter(new DoubleStringConverter()); + putWriteStringConverter(new FloatStringConverter()); + putWriteStringConverter(new IntegerStringConverter()); + putWriteStringConverter(new LongStringConverter()); + putWriteStringConverter(new ShortStringConverter()); + putWriteStringConverter(new StringStringConverter()); } /** @@ -129,6 +141,11 @@ public class DefaultConverterLoader { defaultWriteConverter.put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey()), converter); } + private static void putWriteStringConverter(Converter converter) { + defaultWriteConverter.put( + ConverterKeyBuild.buildKey(converter.supportJavaTypeKey(), converter.supportExcelTypeKey()), converter); + } + /** * Load default read converter * diff --git a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java index 8dcac0c9..f4e9ad6f 100644 --- a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java @@ -16,7 +16,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; public class BigDecimalBooleanConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return BigDecimal.class; } @@ -26,7 +26,7 @@ public class BigDecimalBooleanConverter implements Converter { } @Override - public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return BigDecimal.ONE; @@ -35,12 +35,12 @@ public class BigDecimalBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (BigDecimal.ONE.equals(value)) { - return new CellData(Boolean.TRUE); + return new CellData<>(Boolean.TRUE); } - return new CellData(Boolean.FALSE); + return new CellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java index 402490c7..39061d70 100644 --- a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java @@ -18,7 +18,7 @@ import com.alibaba.excel.write.metadata.holder.WriteHolder; public class BigDecimalNumberConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return BigDecimal.class; } @@ -28,7 +28,7 @@ public class BigDecimalNumberConverter implements Converter { } @Override - public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue(); } diff --git a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java index c6bd3eae..356a38c5 100644 --- a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java @@ -18,7 +18,7 @@ import com.alibaba.excel.util.NumberUtils; public class BigDecimalStringConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return BigDecimal.class; } @@ -28,13 +28,13 @@ public class BigDecimalStringConverter implements Converter { } @Override - public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseBigDecimal(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanBooleanConverter.java index 08b83fe9..56654cd5 100644 --- a/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanBooleanConverter.java @@ -14,7 +14,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; public class BooleanBooleanConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Boolean.class; } @@ -24,15 +24,15 @@ public class BooleanBooleanConverter implements Converter { } @Override - public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getBooleanValue(); } @Override - public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return new CellData(value); + return new CellData<>(value); } } diff --git a/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanNumberConverter.java b/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanNumberConverter.java index a0042eaa..00cd4c2c 100644 --- a/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanNumberConverter.java @@ -15,7 +15,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; */ public class BooleanNumberConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Boolean.class; } @@ -25,7 +25,7 @@ public class BooleanNumberConverter implements Converter { } @Override - public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (BigDecimal.ONE.compareTo(cellData.getNumberValue()) == 0) { return Boolean.TRUE; @@ -34,12 +34,12 @@ public class BooleanNumberConverter implements Converter { } @Override - public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (value) { - return new CellData(BigDecimal.ONE); + return new CellData<>(BigDecimal.ONE); } - return new CellData(BigDecimal.ZERO); + return new CellData<>(BigDecimal.ZERO); } } diff --git a/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanStringConverter.java b/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanStringConverter.java index e86c6ada..9f82f32a 100644 --- a/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanStringConverter.java @@ -14,7 +14,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; public class BooleanStringConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Boolean.class; } @@ -24,15 +24,15 @@ public class BooleanStringConverter implements Converter { } @Override - public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return Boolean.valueOf(cellData.getStringValue()); } @Override - public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return new CellData(value.toString()); + return new CellData<>(value.toString()); } } diff --git a/src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java b/src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java index c083601b..883ed87f 100644 --- a/src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java @@ -13,7 +13,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; */ public class BoxingByteArrayImageConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Byte[].class; } @@ -23,19 +23,19 @@ public class BoxingByteArrayImageConverter implements Converter { } @Override - public Byte[] convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Byte[] convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { throw new UnsupportedOperationException("Cannot convert images to byte arrays"); } @Override - public CellData convertToExcelData(Byte[] value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Byte[] value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { byte[] byteValue = new byte[value.length]; for (int i = 0; i < value.length; i++) { byteValue[i] = value[i]; } - return new CellData(byteValue); + return new CellData<>(byteValue); } } diff --git a/src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java b/src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java index 991999d1..afe1fd08 100644 --- a/src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java @@ -13,7 +13,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; */ public class ByteArrayImageConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return byte[].class; } @@ -23,15 +23,15 @@ public class ByteArrayImageConverter implements Converter { } @Override - public byte[] convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public byte[] convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { throw new UnsupportedOperationException("Cannot convert images to byte arrays"); } @Override - public CellData convertToExcelData(byte[] value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(byte[] value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return new CellData(value); + return new CellData<>(value); } } diff --git a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteBooleanConverter.java index 2b621558..afe079cb 100644 --- a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteBooleanConverter.java @@ -16,7 +16,7 @@ public class ByteBooleanConverter implements Converter { private static final Byte ZERO = (byte)0; @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Byte.class; } @@ -26,7 +26,7 @@ public class ByteBooleanConverter implements Converter { } @Override - public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; @@ -35,12 +35,12 @@ public class ByteBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { - return new CellData(Boolean.TRUE); + return new CellData<>(Boolean.TRUE); } - return new CellData(Boolean.FALSE); + return new CellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java index 63a3598a..891ae714 100644 --- a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java @@ -18,7 +18,7 @@ import com.alibaba.excel.write.metadata.holder.WriteHolder; public class ByteNumberConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Byte.class; } @@ -28,7 +28,7 @@ public class ByteNumberConverter implements Converter { } @Override - public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().byteValue(); } diff --git a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java index e1f014b6..041557cf 100644 --- a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java @@ -17,7 +17,7 @@ import com.alibaba.excel.util.NumberUtils; public class ByteStringConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Byte.class; } @@ -27,13 +27,13 @@ public class ByteStringConverter implements Converter { } @Override - public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseByte(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java b/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java index 0bde87d3..73b071af 100644 --- a/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java +++ b/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java @@ -3,7 +3,9 @@ package com.alibaba.excel.converters.date; import java.util.Date; import com.alibaba.excel.converters.Converter; +import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.util.WorkBookUtil; import com.alibaba.excel.write.metadata.holder.WriteHolder; @@ -19,6 +21,17 @@ public class DateDateConverter implements Converter { return Date.class; } + @Override + public CellDataTypeEnum supportExcelTypeKey() { + return CellDataTypeEnum.DATE; + } + + @Override + public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + GlobalConfiguration globalConfiguration) { + return cellData.getDateValue(); + } + @Override public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, WriteHolder currentWriteHolder) throws Exception { diff --git a/src/main/java/com/alibaba/excel/converters/date/DateNumberConverter.java b/src/main/java/com/alibaba/excel/converters/date/DateNumberConverter.java index fcc76bb3..6eee4de0 100644 --- a/src/main/java/com/alibaba/excel/converters/date/DateNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/date/DateNumberConverter.java @@ -19,7 +19,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; public class DateNumberConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Date.class; } @@ -29,7 +29,7 @@ public class DateNumberConverter implements Converter { } @Override - public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { return DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(), @@ -41,13 +41,13 @@ public class DateNumberConverter implements Converter { } @Override - public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { - return new CellData( + return new CellData<>( BigDecimal.valueOf(DateUtil.getExcelDate(value, globalConfiguration.getUse1904windowing()))); } else { - return new CellData(BigDecimal.valueOf( + return new CellData<>(BigDecimal.valueOf( DateUtil.getExcelDate(value, contentProperty.getDateTimeFormatProperty().getUse1904windowing()))); } } diff --git a/src/main/java/com/alibaba/excel/converters/date/DateStringConverter.java b/src/main/java/com/alibaba/excel/converters/date/DateStringConverter.java index ed7eb0a4..687d84d7 100644 --- a/src/main/java/com/alibaba/excel/converters/date/DateStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/date/DateStringConverter.java @@ -17,7 +17,7 @@ import com.alibaba.excel.util.DateUtils; */ public class DateStringConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Date.class; } @@ -27,7 +27,7 @@ public class DateStringConverter implements Converter { } @Override - public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { return DateUtils.parseDate(cellData.getStringValue(), null); @@ -38,12 +38,12 @@ public class DateStringConverter implements Converter { } @Override - public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { - return new CellData(DateUtils.format(value, null)); + return new CellData<>(DateUtils.format(value, null)); } else { - return new CellData(DateUtils.format(value, contentProperty.getDateTimeFormatProperty().getFormat())); + return new CellData<>(DateUtils.format(value, contentProperty.getDateTimeFormatProperty().getFormat())); } } } diff --git a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleBooleanConverter.java index cbf0b0b0..6aa509e1 100644 --- a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleBooleanConverter.java @@ -16,7 +16,7 @@ public class DoubleBooleanConverter implements Converter { private static final Double ZERO = 0.0; @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Double.class; } @@ -26,7 +26,7 @@ public class DoubleBooleanConverter implements Converter { } @Override - public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; @@ -35,12 +35,12 @@ public class DoubleBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { - return new CellData(Boolean.TRUE); + return new CellData<>(Boolean.TRUE); } - return new CellData(Boolean.FALSE); + return new CellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java index 0b9541f5..c3db3d3b 100644 --- a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java @@ -18,7 +18,7 @@ import com.alibaba.excel.write.metadata.holder.WriteHolder; public class DoubleNumberConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Double.class; } @@ -28,7 +28,7 @@ public class DoubleNumberConverter implements Converter { } @Override - public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().doubleValue(); } diff --git a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java index 116dc129..351d0b8a 100644 --- a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java @@ -17,7 +17,7 @@ import com.alibaba.excel.util.NumberUtils; public class DoubleStringConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Double.class; } @@ -27,13 +27,13 @@ public class DoubleStringConverter implements Converter { } @Override - public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseDouble(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java b/src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java index 10522154..0938f6f5 100644 --- a/src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java @@ -17,7 +17,7 @@ import com.alibaba.excel.util.FileUtils; */ public class FileImageConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return File.class; } @@ -27,15 +27,15 @@ public class FileImageConverter implements Converter { } @Override - public File convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public File convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { throw new UnsupportedOperationException("Cannot convert images to file"); } @Override - public CellData convertToExcelData(File value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(File value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { - return new CellData(FileUtils.readFileToByteArray(value)); + return new CellData<>(FileUtils.readFileToByteArray(value)); } } diff --git a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatBooleanConverter.java index 8fa2a647..c2f674f2 100644 --- a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatBooleanConverter.java @@ -16,7 +16,7 @@ public class FloatBooleanConverter implements Converter { private static final Float ZERO = (float)0.0; @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Float.class; } @@ -26,7 +26,7 @@ public class FloatBooleanConverter implements Converter { } @Override - public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; @@ -35,12 +35,12 @@ public class FloatBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { - return new CellData(Boolean.TRUE); + return new CellData<>(Boolean.TRUE); } - return new CellData(Boolean.FALSE); + return new CellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java index 7d90e4c3..1a401dff 100644 --- a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java @@ -16,7 +16,7 @@ import com.alibaba.excel.write.metadata.holder.WriteHolder; public class FloatNumberConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Float.class; } @@ -26,7 +26,7 @@ public class FloatNumberConverter implements Converter { } @Override - public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().floatValue(); } diff --git a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java index a7fd79f1..29c819b1 100644 --- a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java @@ -17,7 +17,7 @@ import com.alibaba.excel.util.NumberUtils; public class FloatStringConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Float.class; } @@ -27,13 +27,13 @@ public class FloatStringConverter implements Converter { } @Override - public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseFloat(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java b/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java index abc2fe68..b45736e4 100644 --- a/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java @@ -17,7 +17,7 @@ import com.alibaba.excel.util.IoUtils; */ public class InputStreamImageConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return InputStream.class; } @@ -27,15 +27,15 @@ public class InputStreamImageConverter implements Converter { } @Override - public InputStream convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public InputStream convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { throw new UnsupportedOperationException("Cannot convert images to input stream"); } @Override - public CellData convertToExcelData(InputStream value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(InputStream value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { - return new CellData(IoUtils.toByteArray(value)); + return new CellData<>(IoUtils.toByteArray(value)); } } diff --git a/src/main/java/com/alibaba/excel/converters/integer/IntegerBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/integer/IntegerBooleanConverter.java index 541de08a..37b5d913 100644 --- a/src/main/java/com/alibaba/excel/converters/integer/IntegerBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/integer/IntegerBooleanConverter.java @@ -16,7 +16,7 @@ public class IntegerBooleanConverter implements Converter { private static final Integer ZERO = 0; @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Integer.class; } @@ -26,7 +26,7 @@ public class IntegerBooleanConverter implements Converter { } @Override - public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; @@ -35,12 +35,12 @@ public class IntegerBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { - return new CellData(Boolean.TRUE); + return new CellData<>(Boolean.TRUE); } - return new CellData(Boolean.FALSE); + return new CellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java b/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java index 0edae3e1..95a796b5 100644 --- a/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java @@ -16,7 +16,7 @@ import com.alibaba.excel.write.metadata.holder.WriteHolder; public class IntegerNumberConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Integer.class; } @@ -26,7 +26,7 @@ public class IntegerNumberConverter implements Converter { } @Override - public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().intValue(); } diff --git a/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java b/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java index a0bad356..e6d91d34 100644 --- a/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java @@ -17,7 +17,7 @@ import com.alibaba.excel.util.NumberUtils; public class IntegerStringConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Integer.class; } @@ -27,13 +27,13 @@ public class IntegerStringConverter implements Converter { } @Override - public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseInteger(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java index 9d78f48e..85c56067 100644 --- a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java @@ -17,7 +17,7 @@ import com.alibaba.excel.util.NumberUtils; public class ShortStringConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return Short.class; } @@ -27,13 +27,13 @@ public class ShortStringConverter implements Converter { } @Override - public Short convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Short convertToJavaData(CellDatacellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseShort(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(Short value, ExcelContentProperty contentProperty, + public CellDataconvertToExcelData(Short value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/string/StringBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/string/StringBooleanConverter.java index c405de5e..f2aafb4d 100644 --- a/src/main/java/com/alibaba/excel/converters/string/StringBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/string/StringBooleanConverter.java @@ -14,7 +14,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; public class StringBooleanConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return String.class; } @@ -24,15 +24,15 @@ public class StringBooleanConverter implements Converter { } @Override - public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getBooleanValue().toString(); } @Override - public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return new CellData(Boolean.valueOf(value)); + return new CellData<>(Boolean.valueOf(value)); } } diff --git a/src/main/java/com/alibaba/excel/converters/string/StringErrorConverter.java b/src/main/java/com/alibaba/excel/converters/string/StringErrorConverter.java index 66112e1a..f0a71a46 100644 --- a/src/main/java/com/alibaba/excel/converters/string/StringErrorConverter.java +++ b/src/main/java/com/alibaba/excel/converters/string/StringErrorConverter.java @@ -13,7 +13,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; */ public class StringErrorConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return String.class; } @@ -23,15 +23,15 @@ public class StringErrorConverter implements Converter { } @Override - public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getStringValue(); } @Override - public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return new CellData(CellDataTypeEnum.ERROR, value); + return new CellData<>(CellDataTypeEnum.ERROR, value); } } diff --git a/src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java b/src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java index 931d4fa9..37e1c3c7 100644 --- a/src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java @@ -17,7 +17,7 @@ import com.alibaba.excel.util.FileUtils; */ public class StringImageConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return String.class; } @@ -27,15 +27,15 @@ public class StringImageConverter implements Converter { } @Override - public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { throw new UnsupportedOperationException("Cannot convert images to string"); } @Override - public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { - return new CellData(FileUtils.readFileToByteArray(new File(value))); + return new CellData<>(FileUtils.readFileToByteArray(new File(value))); } } diff --git a/src/main/java/com/alibaba/excel/converters/string/StringNumberConverter.java b/src/main/java/com/alibaba/excel/converters/string/StringNumberConverter.java index b31bc706..e9b6fef6 100644 --- a/src/main/java/com/alibaba/excel/converters/string/StringNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/string/StringNumberConverter.java @@ -22,7 +22,7 @@ import com.alibaba.excel.util.StringUtils; public class StringNumberConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return String.class; } @@ -32,7 +32,7 @@ public class StringNumberConverter implements Converter { } @Override - public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { // If there are "DateTimeFormat", read as date if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) { @@ -55,8 +55,8 @@ public class StringNumberConverter implements Converter { } @Override - public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return new CellData(new BigDecimal(value)); + return new CellData<>(new BigDecimal(value)); } } diff --git a/src/main/java/com/alibaba/excel/converters/string/StringStringConverter.java b/src/main/java/com/alibaba/excel/converters/string/StringStringConverter.java index df1b1e14..3b1ce3df 100644 --- a/src/main/java/com/alibaba/excel/converters/string/StringStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/string/StringStringConverter.java @@ -13,7 +13,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; */ public class StringStringConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return String.class; } @@ -23,15 +23,15 @@ public class StringStringConverter implements Converter { } @Override - public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getStringValue(); } @Override - public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return new CellData(value); + return new CellData<>(value); } } diff --git a/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java b/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java index b622d66d..a9e60df9 100644 --- a/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java @@ -19,7 +19,7 @@ import com.alibaba.excel.util.IoUtils; */ public class UrlImageConverter implements Converter { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return URL.class; } @@ -29,19 +29,19 @@ public class UrlImageConverter implements Converter { } @Override - public URL convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public URL convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { throw new UnsupportedOperationException("Cannot convert images to url."); } @Override - public CellData convertToExcelData(URL value, ExcelContentProperty contentProperty, + public CellData convertToExcelData(URL value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { InputStream inputStream = null; try { inputStream = value.openStream(); byte[] bytes = IoUtils.toByteArray(inputStream); - return new CellData(bytes); + return new CellData<>(bytes); } finally { if (inputStream != null) { inputStream.close(); diff --git a/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java b/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java index 5198c20f..7231afd9 100644 --- a/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java +++ b/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java @@ -4,11 +4,16 @@ import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.write.builder.ExcelWriterBuilder; +import lombok.Getter; +import lombok.Setter; + /** * Data convert exception * * @author Jiaju Zhuang */ +@Getter +@Setter public class ExcelDataConvertException extends RuntimeException { /** * NotNull. @@ -21,7 +26,7 @@ public class ExcelDataConvertException extends RuntimeException { /** * NotNull. */ - private CellData cellData; + private CellData cellData; /** * Nullable.Only when the header is configured and when the class header is used is not null. * @@ -47,35 +52,4 @@ public class ExcelDataConvertException extends RuntimeException { this.excelContentProperty = excelContentProperty; } - public Integer getRowIndex() { - return rowIndex; - } - - public void setRowIndex(Integer rowIndex) { - this.rowIndex = rowIndex; - } - - public Integer getColumnIndex() { - return columnIndex; - } - - public void setColumnIndex(Integer columnIndex) { - this.columnIndex = columnIndex; - } - - public ExcelContentProperty getExcelContentProperty() { - return excelContentProperty; - } - - public void setExcelContentProperty(ExcelContentProperty excelContentProperty) { - this.excelContentProperty = excelContentProperty; - } - - public CellData getCellData() { - return cellData; - } - - public void setCellData(CellData cellData) { - this.cellData = cellData; - } } diff --git a/src/main/java/com/alibaba/excel/metadata/CellData.java b/src/main/java/com/alibaba/excel/metadata/CellData.java index 1cac53c2..5a522ba8 100644 --- a/src/main/java/com/alibaba/excel/metadata/CellData.java +++ b/src/main/java/com/alibaba/excel/metadata/CellData.java @@ -122,6 +122,16 @@ public class CellData extends AbstractCell { this.formula = Boolean.FALSE; } + public CellData(Date dateValue) { + if (dateValue == null) { + throw new IllegalArgumentException("DateValue can not be null"); + } + this.type = CellDataTypeEnum.DATE; + this.dateValue = dateValue; + this.formula = Boolean.FALSE; + } + + public CellData(CellDataTypeEnum type) { if (type == null) { throw new IllegalArgumentException("Type can not be null"); @@ -158,37 +168,37 @@ public class CellData extends AbstractCell { } } - public static CellData newEmptyInstance() { + public static CellData newEmptyInstance() { return newEmptyInstance(null, null); } - public static CellData newEmptyInstance(Integer rowIndex, Integer columnIndex) { - CellData cellData = new CellData(CellDataTypeEnum.EMPTY); + public static CellData newEmptyInstance(Integer rowIndex, Integer columnIndex) { + CellData cellData = new CellData<>(CellDataTypeEnum.EMPTY); cellData.setRowIndex(rowIndex); cellData.setColumnIndex(columnIndex); return cellData; } - public static CellData newInstance(Boolean booleanValue) { + public static CellData newInstance(Boolean booleanValue) { return newInstance(booleanValue, null, null); } - public static CellData newInstance(Boolean booleanValue, Integer rowIndex, Integer columnIndex) { - CellData cellData = new CellData(booleanValue); + public static CellData newInstance(Boolean booleanValue, Integer rowIndex, Integer columnIndex) { + CellData cellData = new CellData<>(booleanValue); cellData.setRowIndex(rowIndex); cellData.setColumnIndex(columnIndex); return cellData; } - public static CellData newInstance(String stringValue, Integer rowIndex, Integer columnIndex) { - CellData cellData = new CellData(stringValue); + public static CellData newInstance(String stringValue, Integer rowIndex, Integer columnIndex) { + CellData cellData = new CellData<>(stringValue); cellData.setRowIndex(rowIndex); cellData.setColumnIndex(columnIndex); return cellData; } - public static CellData newInstance(BigDecimal numberValue, Integer rowIndex, Integer columnIndex) { - CellData cellData = new CellData(numberValue); + public static CellData newInstance(BigDecimal numberValue, Integer rowIndex, Integer columnIndex) { + CellData cellData = new CellData<>(numberValue); cellData.setRowIndex(rowIndex); cellData.setColumnIndex(columnIndex); return cellData; diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java index 7a5272a6..ddb5ca27 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java @@ -51,7 +51,7 @@ public class ReadSheetHolder extends AbstractReadHolder { /** * Current CellData */ - private CellData tempCellData; + private CellData tempCellData; public ReadSheetHolder(ReadSheet readSheet, ReadWorkbookHolder readWorkbookHolder) { super(readSheet, readWorkbookHolder, readWorkbookHolder.getReadWorkbook().getConvertAllFiled()); @@ -135,11 +135,11 @@ public class ReadSheetHolder extends AbstractReadHolder { this.rowIndex = rowIndex; } - public CellData getTempCellData() { + public CellData getTempCellData() { return tempCellData; } - public void setTempCellData(CellData tempCellData) { + public void setTempCellData(CellData tempCellData) { this.tempCellData = tempCellData; } diff --git a/src/main/java/com/alibaba/excel/util/StyleUtil.java b/src/main/java/com/alibaba/excel/util/StyleUtil.java index d0e1bd32..0154f181 100644 --- a/src/main/java/com/alibaba/excel/util/StyleUtil.java +++ b/src/main/java/com/alibaba/excel/util/StyleUtil.java @@ -1,5 +1,8 @@ package com.alibaba.excel.util; +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.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.FillPatternType; @@ -8,15 +11,17 @@ 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.Workbook; - -import com.alibaba.excel.write.metadata.style.WriteCellStyle; -import com.alibaba.excel.write.metadata.style.WriteFont; +import org.apache.poi.xssf.streaming.SXSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; /** * @author jipengfei */ public class StyleUtil { + public static short XSSF_DEFAULT_STYLE = 0; + public static short HSSF_DEFAULT_STYLE = 15; + private StyleUtil() {} /** @@ -183,4 +188,13 @@ public class StyleUtil { } } + public static boolean isDefaultStyle(CellStyle cellStyle) { + if (cellStyle == null) { + return true; + } + if (cellStyle instanceof XSSFCellStyle) { + return cellStyle.getIndex() == XSSF_DEFAULT_STYLE; + } + return cellStyle.getIndex() == HSSF_DEFAULT_STYLE; + } } diff --git a/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java b/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java index cac3f7f8..0bd0a068 100644 --- a/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java +++ b/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java @@ -4,9 +4,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; - import com.alibaba.excel.context.WriteContext; import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.Head; @@ -16,6 +13,9 @@ import com.alibaba.excel.write.handler.SheetWriteHandler; import com.alibaba.excel.write.handler.WorkbookWriteHandler; import com.alibaba.excel.write.handler.WriteHandler; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; + /** * Write handler utils * @@ -25,7 +25,6 @@ public class WriteHandlerUtils { private WriteHandlerUtils() {} - public static void beforeWorkbookCreate(WriteContext writeContext) { beforeWorkbookCreate(writeContext, false); } @@ -37,7 +36,7 @@ public class WriteHandlerUtils { } for (WriteHandler writeHandler : handlerList) { if (writeHandler instanceof WorkbookWriteHandler) { - ((WorkbookWriteHandler) writeHandler).beforeWorkbookCreate(); + ((WorkbookWriteHandler)writeHandler).beforeWorkbookCreate(); } } } @@ -53,7 +52,7 @@ public class WriteHandlerUtils { } for (WriteHandler writeHandler : handlerList) { if (writeHandler instanceof WorkbookWriteHandler) { - ((WorkbookWriteHandler) writeHandler).afterWorkbookCreate(writeContext.writeWorkbookHolder()); + ((WorkbookWriteHandler)writeHandler).afterWorkbookCreate(writeContext.writeWorkbookHolder()); } } } @@ -66,7 +65,7 @@ public class WriteHandlerUtils { } for (WriteHandler writeHandler : handlerList) { if (writeHandler instanceof WorkbookWriteHandler) { - ((WorkbookWriteHandler) writeHandler).afterWorkbookDispose(writeContext.writeWorkbookHolder()); + ((WorkbookWriteHandler)writeHandler).afterWorkbookDispose(writeContext.writeWorkbookHolder()); } } } @@ -82,13 +81,12 @@ public class WriteHandlerUtils { } for (WriteHandler writeHandler : handlerList) { if (writeHandler instanceof SheetWriteHandler) { - ((SheetWriteHandler) writeHandler).beforeSheetCreate(writeContext.writeWorkbookHolder(), + ((SheetWriteHandler)writeHandler).beforeSheetCreate(writeContext.writeWorkbookHolder(), writeContext.writeSheetHolder()); } } } - public static void afterSheetCreate(WriteContext writeContext) { afterSheetCreate(writeContext, false); } @@ -100,7 +98,7 @@ public class WriteHandlerUtils { } for (WriteHandler writeHandler : handlerList) { if (writeHandler instanceof SheetWriteHandler) { - ((SheetWriteHandler) writeHandler).afterSheetCreate(writeContext.writeWorkbookHolder(), + ((SheetWriteHandler)writeHandler).afterSheetCreate(writeContext.writeWorkbookHolder(), writeContext.writeSheetHolder()); } } @@ -119,7 +117,7 @@ public class WriteHandlerUtils { } for (WriteHandler writeHandler : handlerList) { if (writeHandler instanceof CellWriteHandler) { - ((CellWriteHandler) writeHandler).beforeCellCreate(writeContext.writeSheetHolder(), + ((CellWriteHandler)writeHandler).beforeCellCreate(writeContext.writeSheetHolder(), writeContext.writeTableHolder(), row, head, columnIndex, relativeRowIndex, isHead); } } @@ -134,7 +132,7 @@ public class WriteHandlerUtils { } for (WriteHandler writeHandler : handlerList) { if (writeHandler instanceof CellWriteHandler) { - ((CellWriteHandler) writeHandler).afterCellCreate(writeContext.writeSheetHolder(), + ((CellWriteHandler)writeHandler).afterCellCreate(writeContext.writeSheetHolder(), writeContext.writeTableHolder(), cell, head, relativeRowIndex, isHead); } } @@ -149,7 +147,7 @@ public class WriteHandlerUtils { } for (WriteHandler writeHandler : handlerList) { if (writeHandler instanceof CellWriteHandler) { - ((CellWriteHandler) writeHandler).afterCellDataConverted(writeContext.writeSheetHolder(), + ((CellWriteHandler)writeHandler).afterCellDataConverted(writeContext.writeSheetHolder(), writeContext.writeTableHolder(), cellData, cell, head, relativeRowIndex, isHead); } } @@ -158,7 +156,7 @@ public class WriteHandlerUtils { public static void afterCellDispose(WriteContext writeContext, CellData cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { List> cellDataList = new ArrayList<>(); - if (cell != null) { + if (cellData != null) { cellDataList.add(cellData); } afterCellDispose(writeContext, cellDataList, cell, head, relativeRowIndex, isHead); @@ -173,7 +171,7 @@ public class WriteHandlerUtils { } for (WriteHandler writeHandler : handlerList) { if (writeHandler instanceof CellWriteHandler) { - ((CellWriteHandler) writeHandler).afterCellDispose(writeContext.writeSheetHolder(), + ((CellWriteHandler)writeHandler).afterCellDispose(writeContext.writeSheetHolder(), writeContext.writeTableHolder(), cellDataList, cell, head, relativeRowIndex, isHead); } } @@ -190,7 +188,7 @@ public class WriteHandlerUtils { } for (WriteHandler writeHandler : handlerList) { if (writeHandler instanceof RowWriteHandler) { - ((RowWriteHandler) writeHandler).beforeRowCreate(writeContext.writeSheetHolder(), + ((RowWriteHandler)writeHandler).beforeRowCreate(writeContext.writeSheetHolder(), writeContext.writeTableHolder(), rowIndex, relativeRowIndex, isHead); } } @@ -203,7 +201,7 @@ public class WriteHandlerUtils { } for (WriteHandler writeHandler : handlerList) { if (writeHandler instanceof RowWriteHandler) { - ((RowWriteHandler) writeHandler).afterRowCreate(writeContext.writeSheetHolder(), + ((RowWriteHandler)writeHandler).afterRowCreate(writeContext.writeSheetHolder(), writeContext.writeTableHolder(), row, relativeRowIndex, isHead); } } @@ -217,7 +215,7 @@ public class WriteHandlerUtils { } for (WriteHandler writeHandler : handlerList) { if (writeHandler instanceof RowWriteHandler) { - ((RowWriteHandler) writeHandler).afterRowDispose(writeContext.writeSheetHolder(), + ((RowWriteHandler)writeHandler).afterRowDispose(writeContext.writeSheetHolder(), writeContext.writeTableHolder(), row, relativeRowIndex, isHead); } } diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index 4aa2d33a..b20305f6 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -30,15 +30,16 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { this.writeContext = writeContext; } - protected CellData converterAndSet(WriteHolder currentWriteHolder, Class clazz, Cell cell, Object value, + protected CellData converterAndSet(WriteHolder currentWriteHolder, Class clazz, CellDataTypeEnum targetType, + Cell cell, Object value, ExcelContentProperty excelContentProperty, Head head, Integer relativeRowIndex) { if (value == null) { - return new CellData(CellDataTypeEnum.EMPTY); + return new CellData<>(CellDataTypeEnum.EMPTY); } if (value instanceof String && currentWriteHolder.globalConfiguration().getAutoTrim()) { value = ((String)value).trim(); } - CellData cellData = convert(currentWriteHolder, clazz, cell, value, excelContentProperty); + CellData cellData = convert(currentWriteHolder, clazz, targetType, cell, value, excelContentProperty); if (cellData.getFormula() != null && cellData.getFormula()) { cell.setCellFormula(cellData.getFormulaValue()); } @@ -71,14 +72,15 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { } } - protected CellData convert(WriteHolder currentWriteHolder, Class clazz, Cell cell, Object value, - ExcelContentProperty excelContentProperty) { + protected CellData convert(WriteHolder currentWriteHolder, Class clazz, CellDataTypeEnum targetType, + Cell cell, + Object value, ExcelContentProperty excelContentProperty) { if (value == null) { - return new CellData(CellDataTypeEnum.EMPTY); + return new CellData<>(CellDataTypeEnum.EMPTY); } // This means that the user has defined the data. if (value instanceof CellData) { - CellData cellDataValue = (CellData)value; + CellData cellDataValue = (CellData)value; if (cellDataValue.getType() != null) { return cellDataValue; } else { @@ -87,8 +89,8 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { return cellDataValue; } } - CellData cellDataReturn = doConvert(currentWriteHolder, cellDataValue.getData().getClass(), cell, - cellDataValue.getData(), excelContentProperty); + CellData cellDataReturn = doConvert(currentWriteHolder, cellDataValue.getData().getClass(), targetType, + cell, cellDataValue.getData(), excelContentProperty); // The formula information is subject to user input if (cellDataValue.getFormula() != null) { cellDataReturn.setFormula(cellDataValue.getFormula()); @@ -96,41 +98,40 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { } return cellDataReturn; } - return doConvert(currentWriteHolder, clazz, cell, value, excelContentProperty); + return doConvert(currentWriteHolder, clazz, targetType, cell, value, excelContentProperty); } - private CellData doConvert(WriteHolder currentWriteHolder, Class clazz, Cell cell, Object value, - ExcelContentProperty excelContentProperty) { + private CellData doConvert(WriteHolder currentWriteHolder, Class clazz, CellDataTypeEnum targetType, + Cell cell, Object value, ExcelContentProperty excelContentProperty) { Converter converter = null; if (excelContentProperty != null) { converter = excelContentProperty.getConverter(); } if (converter == null) { - converter = currentWriteHolder.converterMap().get(ConverterKeyBuild.buildKey(clazz)); + converter = currentWriteHolder.converterMap().get(ConverterKeyBuild.buildKey(clazz, targetType)); } if (converter == null) { throw new ExcelDataConvertException(cell.getRow().getRowNum(), cell.getColumnIndex(), - new CellData(CellDataTypeEnum.EMPTY), excelContentProperty, + new CellData<>(CellDataTypeEnum.EMPTY), excelContentProperty, "Can not find 'Converter' support class " + clazz.getSimpleName() + "."); } - CellData cellData; + CellData cellData; try { - cellData = - converter.convertToExcelData(value, excelContentProperty, currentWriteHolder); + cellData = converter.convertToExcelData(value, excelContentProperty, currentWriteHolder); } catch (Exception e) { throw new ExcelDataConvertException(cell.getRow().getRowNum(), cell.getColumnIndex(), - new CellData(CellDataTypeEnum.EMPTY), excelContentProperty, + new CellData<>(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 CellData<>(CellDataTypeEnum.EMPTY), excelContentProperty, "Convert data:" + value + " return null,at row:" + cell.getRow().getRowNum()); } return cellData; } - private void setImageValue(CellData cellData, Cell cell) { + 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(); diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 194a2233..4d96e8c4 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -114,8 +114,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { WriteHandlerUtils.afterCellCreate(writeContext, cell, head, relativeRowIndex, Boolean.FALSE); Object value = oneRowData.get(dataIndex); CellData cellData = converterAndSet(writeContext.currentWriteHolder(), value == null ? null : value.getClass(), - cell, value, null, head, relativeRowIndex); - writeContext.writeSheetHolder().setLastRowIndex(cellData.getRowIndex()); + null, cell, value, null, head, relativeRowIndex); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE); } @@ -142,8 +141,9 @@ 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(), cell, - value, excelContentProperty, head, relativeRowIndex); + CellData cellData = converterAndSet(currentWriteHolder, excelContentProperty.getField().getType(), + null, + cell, value, excelContentProperty, head, relativeRowIndex); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE); beanMapHandledSet.add(name); } @@ -167,7 +167,7 @@ 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(), cell, + CellData cellData = converterAndSet(currentWriteHolder, value == null ? null : value.getClass(), null, cell, value, null, null, relativeRowIndex); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, relativeRowIndex, Boolean.FALSE); } diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 0c868a12..9a144534 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -198,8 +198,8 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { continue; } Object value = dataMap.get(variable); - CellData cellData = converterAndSet(writeSheetHolder, value == null ? null : value.getClass(), cell, - value, fieldNameContentPropertyMap.get(variable), null, relativeRowIndex); + CellData 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(); @@ -211,8 +211,8 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { continue; } Object value = dataMap.get(variable); - CellData cellData = convert(writeSheetHolder, value == null ? null : value.getClass(), cell, value, - fieldNameContentPropertyMap.get(variable)); + CellData cellData = convert(writeSheetHolder, value == null ? null : value.getClass(), + CellDataTypeEnum.STRING, cell, value, fieldNameContentPropertyMap.get(variable)); cellDataList.add(cellData); CellDataTypeEnum type = cellData.getType(); if (type != null) { diff --git a/src/main/java/com/alibaba/excel/write/handler/impl/DimensionWorkbookWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/impl/DimensionWorkbookWriteHandler.java index 6e2c8bac..6b444a47 100644 --- a/src/main/java/com/alibaba/excel/write/handler/impl/DimensionWorkbookWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/impl/DimensionWorkbookWriteHandler.java @@ -69,8 +69,13 @@ public class DimensionWorkbookWriteHandler implements WorkbookWriteHandler { headSize--; } } + Integer lastRowIndex = writeSheetHolder.getLastRowIndex(); + if (lastRowIndex == null) { + lastRowIndex = 0; + } + ctWorksheet.getDimension().setRef( - "A1:" + CellReference.convertNumToColString(headSize) + (writeSheetHolder.getLastRowIndex() + 1)); + "A1:" + CellReference.convertNumToColString(headSize) + (lastRowIndex + 1)); } } } diff --git a/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java index 3b67d0ca..a465546b 100644 --- a/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java @@ -10,6 +10,7 @@ import com.alibaba.excel.event.Order; import com.alibaba.excel.metadata.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; @@ -46,7 +47,7 @@ public class FillDataFormatCellWriteHandler implements CellWriteHandler, Order { } CellData cellData = cellDataList.get(0); CellStyle cellStyle = cell.getCellStyle(); - if (cellStyle == null) { + if (cellStyle == null || StyleUtil.isDefaultStyle(cellStyle)) { if (cellData.getType() == CellDataTypeEnum.DATE) { cell.setCellStyle(getDefaultDateCellStyle(writeSheetHolder)); } diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java index e3ea80d1..19e4622b 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java @@ -10,6 +10,7 @@ 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.support.ExcelTypeEnum; @@ -211,7 +212,7 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { */ public Short getDataFormat(String format) { if (StringUtils.isEmpty(format)) { - return 0; + return BuiltinFormats.GENERAL; } Short dataFormat = dataFormatCache.get(format); if (dataFormat != null) { diff --git a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java index 979a7750..26af5512 100644 --- a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java +++ b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java @@ -102,14 +102,6 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty { headData.setContentFontProperty(FontProperty.build(contentFontStyle)); headData.setLoopMergeProperty(LoopMergeProperty.build(field.getAnnotation(ContentLoopMerge.class))); - // If have @NumberFormat, 'NumberStringConverter' is specified by default - if (excelContentPropertyData.getConverter() == null) { - NumberFormat numberFormat = field.getAnnotation(NumberFormat.class); - if (numberFormat != null) { - excelContentPropertyData.setConverter(DefaultConverterLoader.loadAllConverter() - .get(ConverterKeyBuild.buildKey(field.getType(), CellDataTypeEnum.STRING))); - } - } } } diff --git a/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java index 9a9261db..23292f6c 100644 --- a/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java @@ -42,7 +42,7 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl } WriteCellStyle headCellStyle = headCellStyle(head); if (headCellStyle == null) { - headCellStyleCache.put(columnIndex, null); + headCellStyleCache.put(columnIndex, StyleUtil.buildHeadCellStyle(workbook, null)); } else { CellStyle cellStyle = StyleUtil.buildHeadCellStyle(workbook, headCellStyle); headCellStyleCache.put(columnIndex, cellStyle); @@ -65,7 +65,7 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl } WriteCellStyle contentCellStyle = contentCellStyle(cell, head, relativeRowIndex); if (contentCellStyle == null) { - contentCellStyleCache.put(columnIndex, null); + contentCellStyleCache.put(columnIndex, StyleUtil.buildContentCellStyle(workbook, null)); } else { CellStyle cellStyle = StyleUtil.buildContentCellStyle(workbook, contentCellStyle); contentCellStyleCache.put(columnIndex, cellStyle); diff --git a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java index 7e8fbe4a..c8914f55 100644 --- a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java @@ -39,7 +39,7 @@ public class HorizontalCellStyleStrategy extends AbstractVerticalCellStyleStrate @Override protected WriteCellStyle contentCellStyle(Cell cell, Head head, Integer relativeRowIndex) { if (CollectionUtils.isEmpty(contentWriteCellStyleList)) { - return null; + return new WriteCellStyle(); } return contentWriteCellStyleList.get(relativeRowIndex % contentWriteCellStyleList.size()); } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationData.java b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationData.java index f1e91197..d1c2a4f7 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationData.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationData.java @@ -9,7 +9,6 @@ import com.alibaba.excel.annotation.format.NumberFormat; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.HeadRowHeight; -import com.alibaba.excel.converters.doubleconverter.DoubleStringConverter; import lombok.Data; @@ -24,7 +23,7 @@ public class AnnotationData { @ExcelProperty("日期") @DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒") private Date date; - @ExcelProperty(value = "数字", converter = DoubleStringConverter.class) + @ExcelProperty(value = "数字") @NumberFormat("#.##%") private Double number; @ExcelIgnore diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataData.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataData.java index a4e624fb..ac928ec1 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataData.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataData.java @@ -17,5 +17,5 @@ public class CellDataData { private CellData date; private CellData integer1; private Integer integer2; - private CellData formulaValue; + private CellData formulaValue; } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java index 4615cdbc..ad8cbf13 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java @@ -55,7 +55,7 @@ public class CellDataDataTest { private List data() throws Exception { List list = new ArrayList(); CellDataData cellDataData = new CellDataData(); - cellDataData.setDate(new CellData(DateUtils.parseDate("2020-01-01 01:01:01"))); + cellDataData.setDate(new CellData<>(DateUtils.parseDate("2020-01-01 01:01:01"))); CellData integer1 = new CellData(); integer1.setType(CellDataTypeEnum.NUMBER); integer1.setNumberValue(BigDecimal.valueOf(2L)); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java index 88469470..fdff30e3 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java @@ -34,5 +34,5 @@ public class ConverterData { @ExcelProperty("字符串") private String string; @ExcelProperty("自定义") - private CellData cellData; + private CellData cellData; } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java index a6ff2683..1a0cf088 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java @@ -7,6 +7,7 @@ import java.util.Map; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.util.DateUtils; import org.junit.Assert; import org.junit.BeforeClass; @@ -34,35 +35,40 @@ public class NoModelDataTest { } @Test - public void t01ReadAndWrite07() { + public void t01ReadAndWrite07() throws Exception { readAndWrite(file07, fileRepeat07); } @Test - public void t02ReadAndWrite03() { + public void t02ReadAndWrite03() throws Exception { readAndWrite(file03, fileRepeat03); } - private void readAndWrite(File file, File fileRepeat) { + private void readAndWrite(File file, File fileRepeat) throws Exception { EasyExcel.write(file).sheet().doWrite(data()); List> result = EasyExcel.read(file).headRowNumber(0).sheet().doReadSync(); Assert.assertEquals(10, result.size()); Map data10 = result.get(9); Assert.assertEquals("string19", data10.get(0)); + Assert.assertEquals("109", data10.get(1)); + Assert.assertEquals("2020-01-01 01:01:01", data10.get(2)); + EasyExcel.write(fileRepeat).sheet().doWrite(result); result = EasyExcel.read(fileRepeat).headRowNumber(0).sheet().doReadSync(); Assert.assertEquals(10, result.size()); data10 = result.get(9); Assert.assertEquals("string19", data10.get(0)); + Assert.assertEquals("109", data10.get(1)); + Assert.assertEquals("2020-01-01 01:01:01", data10.get(2)); } - private List> data() { - List> list = new ArrayList<>(); + private List> data() throws Exception { + List> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { - List data = new ArrayList<>(); + List data = new ArrayList<>(); data.add("string1" + i); - data.add("string2" + i); - data.add("string3" + i); + data.add(100 + i); + data.add(DateUtils.parseDate("2020-01-01 01:01:01")); list.add(data); } return list; diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java index 7a0e92e5..ffa8280c 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/fill/FillTest.java @@ -2,6 +2,7 @@ package com.alibaba.easyexcel.test.demo.fill; import java.io.File; import java.util.ArrayList; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -205,7 +206,9 @@ public class FillTest { excelWriter.fill(new FillWrapper("data3", data()), writeSheet); Map map = new HashMap(); - map.put("date", "2019年10月9日13:28:28"); + //map.put("date", "2019年10月9日13:28:28"); + map.put("date", new Date()); + excelWriter.fill(map, writeSheet); // 别忘记关闭流 diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/poi/TestCell.java b/src/test/java/com/alibaba/easyexcel/test/temp/poi/TestCell.java index 3c4e0ab6..bb12c220 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/poi/TestCell.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/poi/TestCell.java @@ -13,6 +13,6 @@ import lombok.Data; **/ @Data public class TestCell { - private CellData c1; + private CellData c1; private CellData> c2; } From fba858f46abdb383f6659eae5a1cba7756c58cf9 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Tue, 13 Apr 2021 15:09:58 +0800 Subject: [PATCH 047/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=A4=9A=E4=B8=AA?= =?UTF-8?q?=E8=A1=A8=E5=8D=95=E5=8F=AF=E8=83=BD=E6=A0=B7=E5=BC=8F=E9=87=8D?= =?UTF-8?q?=E5=A4=8D=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../style/AbstractCellStyleStrategy.java | 38 ++++++++++++++-- .../AbstractVerticalCellStyleStrategy.java | 45 +++++++++++++------ 2 files changed, 66 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java index 2e88cc84..f131c456 100644 --- a/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java @@ -35,9 +35,9 @@ public abstract class AbstractCellStyleStrategy implements CellWriteHandler, Wor return; } if (isHead) { - setHeadCellStyle(cell, head, relativeRowIndex); + setHeadCellStyle(writeSheetHolder, writeTableHolder, cell, head, relativeRowIndex); } else { - setContentCellStyle(cell, head, relativeRowIndex); + setContentCellStyle(writeSheetHolder, writeTableHolder, cell, head, relativeRowIndex); } } @@ -57,11 +57,27 @@ public abstract class AbstractCellStyleStrategy implements CellWriteHandler, Wor /** * Sets the cell style of header * + * @param writeSheetHolder + * @param writeTableHolder * @param cell * @param head * @param relativeRowIndex */ - protected abstract void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex); + protected void setHeadCellStyle(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, + Cell cell, Head head, Integer relativeRowIndex) { + setHeadCellStyle(cell, head, relativeRowIndex); + } + + /** + * Sets the cell style of header + * + * @param cell + * @param head + * @param relativeRowIndex + */ + protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) { + throw new UnsupportedOperationException("Custom styles must override the setHeadCellStyle method."); + } /** * Sets the cell style of content @@ -70,6 +86,20 @@ public abstract class AbstractCellStyleStrategy implements CellWriteHandler, Wor * @param head * @param relativeRowIndex */ - protected abstract void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex); + protected void setContentCellStyle(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, + Cell cell, Head head, Integer relativeRowIndex) { + setContentCellStyle(cell, head, relativeRowIndex); + } + + /** + * Sets the cell style of content + * + * @param cell + * @param head + * @param relativeRowIndex + */ + protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) { + throw new UnsupportedOperationException("Custom styles must override the setContentCellStyle method."); + } } diff --git a/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java index 23292f6c..4ae5ac6a 100644 --- a/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java @@ -1,10 +1,12 @@ package com.alibaba.excel.write.style; -import java.util.HashMap; import java.util.Map; 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.write.metadata.style.WriteCellStyle; import org.apache.poi.ss.usermodel.Cell; @@ -19,8 +21,8 @@ import org.apache.poi.ss.usermodel.Workbook; public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyleStrategy { private Workbook workbook; - private Map headCellStyleCache = new HashMap(); - private Map contentCellStyleCache = new HashMap(); + private final Map>> headCellStyleCache = MapUtils.newHashMap(); + private final Map>> contentCellStyleCache = MapUtils.newHashMap(); @Override protected void initCellStyle(Workbook workbook) { @@ -28,13 +30,16 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl } @Override - protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) { + protected void setHeadCellStyle(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, + Head head, Integer relativeRowIndex) { if (head == null) { return; } + Map styleMap = getStyleMap(headCellStyleCache, writeSheetHolder, writeTableHolder); + int columnIndex = head.getColumnIndex(); - if (headCellStyleCache.containsKey(columnIndex)) { - CellStyle cellStyle = headCellStyleCache.get(columnIndex); + if (styleMap.containsKey(columnIndex)) { + CellStyle cellStyle = styleMap.get(columnIndex); if (cellStyle != null) { cell.setCellStyle(cellStyle); } @@ -42,22 +47,25 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl } WriteCellStyle headCellStyle = headCellStyle(head); if (headCellStyle == null) { - headCellStyleCache.put(columnIndex, StyleUtil.buildHeadCellStyle(workbook, null)); + styleMap.put(columnIndex, StyleUtil.buildHeadCellStyle(workbook, null)); } else { CellStyle cellStyle = StyleUtil.buildHeadCellStyle(workbook, headCellStyle); - headCellStyleCache.put(columnIndex, cellStyle); + styleMap.put(columnIndex, cellStyle); cell.setCellStyle(cellStyle); } } @Override - protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) { + protected void setContentCellStyle(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, + Head head, Integer relativeRowIndex) { if (head == null) { return; } + Map styleMap = getStyleMap(contentCellStyleCache, writeSheetHolder, writeTableHolder); + int columnIndex = head.getColumnIndex(); - if (contentCellStyleCache.containsKey(columnIndex)) { - CellStyle cellStyle = contentCellStyleCache.get(columnIndex); + if (styleMap.containsKey(columnIndex)) { + CellStyle cellStyle = styleMap.get(columnIndex); if (cellStyle != null) { cell.setCellStyle(cellStyle); } @@ -65,10 +73,10 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl } WriteCellStyle contentCellStyle = contentCellStyle(cell, head, relativeRowIndex); if (contentCellStyle == null) { - contentCellStyleCache.put(columnIndex, StyleUtil.buildContentCellStyle(workbook, null)); + styleMap.put(columnIndex, StyleUtil.buildContentCellStyle(workbook, null)); } else { CellStyle cellStyle = StyleUtil.buildContentCellStyle(workbook, contentCellStyle); - contentCellStyleCache.put(columnIndex, cellStyle); + styleMap.put(columnIndex, cellStyle); cell.setCellStyle(cellStyle); } } @@ -105,4 +113,15 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl + "'contentCellStyle(Head head)' must be implemented."); } + private Map getStyleMap(Map>> cellStyleCache, + WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder) { + Map> tableStyleMap = cellStyleCache.computeIfAbsent( + writeSheetHolder.getSheetNo(), key -> MapUtils.newHashMap()); + Integer tableNo = 0; + if (writeTableHolder != null) { + tableNo = writeTableHolder.getTableNo(); + } + return tableStyleMap.computeIfAbsent(tableNo, key -> MapUtils.newHashMap()); + } + } From 269240d8e91c7e66d5c322f379bb372fc039eaa8 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Tue, 13 Apr 2021 15:45:39 +0800 Subject: [PATCH 048/129] =?UTF-8?q?`Converter`=E6=94=AF=E6=8C=81null?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=20[Issue=20#1776]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/converters/NullableObjectConverter.java | 10 ++++++++++ .../write/executor/AbstractExcelWriteExecutor.java | 14 +++++++------- update.md | 2 ++ 3 files changed, 19 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/converters/NullableObjectConverter.java diff --git a/src/main/java/com/alibaba/excel/converters/NullableObjectConverter.java b/src/main/java/com/alibaba/excel/converters/NullableObjectConverter.java new file mode 100644 index 00000000..fe24f63d --- /dev/null +++ b/src/main/java/com/alibaba/excel/converters/NullableObjectConverter.java @@ -0,0 +1,10 @@ +package com.alibaba.excel.converters; + +/** + * When implementing convertToExcelData method, pay attention to the reference value may be + * null + * + * @author JiaJu Zhuang + **/ +public interface NullableObjectConverter extends Converter { +} diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index b20305f6..b45082c0 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -3,6 +3,7 @@ package com.alibaba.excel.write.executor; 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.enums.CellDataTypeEnum; import com.alibaba.excel.exception.ExcelDataConvertException; import com.alibaba.excel.metadata.CellData; @@ -33,10 +34,9 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { protected CellData converterAndSet(WriteHolder currentWriteHolder, Class clazz, CellDataTypeEnum targetType, Cell cell, Object value, ExcelContentProperty excelContentProperty, Head head, Integer relativeRowIndex) { - if (value == null) { - return new CellData<>(CellDataTypeEnum.EMPTY); - } - if (value instanceof String && currentWriteHolder.globalConfiguration().getAutoTrim()) { + 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); @@ -75,9 +75,6 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { protected CellData convert(WriteHolder currentWriteHolder, Class clazz, CellDataTypeEnum targetType, Cell cell, Object value, ExcelContentProperty excelContentProperty) { - if (value == null) { - return new CellData<>(CellDataTypeEnum.EMPTY); - } // This means that the user has defined the data. if (value instanceof CellData) { CellData cellDataValue = (CellData)value; @@ -115,6 +112,9 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { new CellData<>(CellDataTypeEnum.EMPTY), excelContentProperty, "Can not find 'Converter' support class " + clazz.getSimpleName() + "."); } + if (value == null && !(converter instanceof NullableObjectConverter)) { + return new CellData<>(CellDataTypeEnum.EMPTY); + } CellData cellData; try { cellData = converter.convertToExcelData(value, excelContentProperty, currentWriteHolder); diff --git a/update.md b/update.md index 09ca62ac..db5c7cb7 100644 --- a/update.md +++ b/update.md @@ -40,6 +40,8 @@ * 修复填充的时候,最后一行中间有空行会创建失败的bug * 修复`includeColumnIndexes`不包含第列 会无法导出数据的bug [Issue #1346](https://github.com/alibaba/easyexcel/issues/1346) * 修复`@NumberFormat`注解转换double时可能会丢失精度 [Issue #1306](https://github.com/alibaba/easyexcel/issues/1306) +* `Converter`支持null转换 [Issue #1776](https://github.com/alibaba/easyexcel/issues/1776) + # 2.2.3 * 修改填充数据空数据的bug [Issue #1274](https://github.com/alibaba/easyexcel/issues/1274) From a00bae3f4cf2467b40e5449130f87e0bf858d4cf Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Tue, 13 Apr 2021 15:47:20 +0800 Subject: [PATCH 049/129] =?UTF-8?q?`Converter`=E6=94=AF=E6=8C=81null?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=20[Issue=20#1776]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- update.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/update.md b/update.md index db5c7cb7..95fed3b3 100644 --- a/update.md +++ b/update.md @@ -13,7 +13,7 @@ * 兼容一些非官方excel的情况 [Issue #1527](https://github.com/alibaba/easyexcel/issues/1527) * 修改读的关闭流无效 [Issue #1840](https://github.com/alibaba/easyexcel/issues/1840) * 写入支持Collection [Issue #1834](https://github.com/alibaba/easyexcel/issues/1834) - +* `Converter`支持null转换 [Issue #1776](https://github.com/alibaba/easyexcel/issues/1776) # 2.2.8 * 兼容07在特殊的excel的情况下,读取数据异常 @@ -40,8 +40,6 @@ * 修复填充的时候,最后一行中间有空行会创建失败的bug * 修复`includeColumnIndexes`不包含第列 会无法导出数据的bug [Issue #1346](https://github.com/alibaba/easyexcel/issues/1346) * 修复`@NumberFormat`注解转换double时可能会丢失精度 [Issue #1306](https://github.com/alibaba/easyexcel/issues/1306) -* `Converter`支持null转换 [Issue #1776](https://github.com/alibaba/easyexcel/issues/1776) - # 2.2.3 * 修改填充数据空数据的bug [Issue #1274](https://github.com/alibaba/easyexcel/issues/1274) From f56f6a04f09802f2dcd6a817b5559d93e20bed40 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Tue, 13 Apr 2021 16:15:32 +0800 Subject: [PATCH 050/129] =?UTF-8?q?`Converter`=E6=94=AF=E6=8C=81null?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=20[Issue=20#1776]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/write/executor/AbstractExcelWriteExecutor.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index b45082c0..55b4b5cd 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -73,8 +73,7 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { } protected CellData convert(WriteHolder currentWriteHolder, Class clazz, CellDataTypeEnum targetType, - Cell cell, - Object value, ExcelContentProperty excelContentProperty) { + Cell cell, Object value, ExcelContentProperty excelContentProperty) { // This means that the user has defined the data. if (value instanceof CellData) { CellData cellDataValue = (CellData)value; From de4ec6d40013e2d12b5aa43d36973cca2f035c71 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Tue, 13 Apr 2021 23:17:49 +0800 Subject: [PATCH 051/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E9=83=A8=E5=88=86=E5=9B=BE=E7=89=87=E7=AD=89=E5=AF=BC=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lombok.config | 2 + .../alibaba/excel/enums/CellDataTypeEnum.java | 6 +- .../exception/ExcelDataConvertException.java | 4 +- .../alibaba/excel/metadata/AbstractCell.java | 19 +- .../excel/metadata/AbstractHolder.java | 45 +---- .../com/alibaba/excel/metadata/CellData.java | 103 ++-------- .../excel/metadata/ClientAnchorData.java | 139 +++++++++++++ .../alibaba/excel/metadata/CommentData.java | 28 +++ .../alibaba/excel/metadata/DataFormat.java | 20 ++ .../alibaba/excel/metadata/FormulaData.java | 16 ++ .../alibaba/excel/metadata/HyperlinkData.java | 10 + .../com/alibaba/excel/metadata/ImageData.java | 58 ++++++ .../alibaba/excel/metadata/ReadCellData.java | 13 ++ .../excel/metadata/RichTextStringData.java | 59 ++++++ .../alibaba/excel/metadata/WriteCellData.java | 42 ++++ .../metadata/property/ExcelHeadProperty.java | 78 ++------ .../metadata/holder/AbstractReadHolder.java | 27 +-- .../write/executor/ExcelWriteAddExecutor.java | 4 +- .../metadata/holder/AbstractWriteHolder.java | 4 + .../metadata/holder/WriteSheetHolder.java | 6 +- .../metadata/holder/WriteWorkbookHolder.java | 4 +- .../write/metadata/style/WriteCellStyle.java | 186 +----------------- .../excel/write/metadata/style/WriteFont.java | 74 +------ 23 files changed, 450 insertions(+), 497 deletions(-) create mode 100644 lombok.config create mode 100644 src/main/java/com/alibaba/excel/metadata/ClientAnchorData.java create mode 100644 src/main/java/com/alibaba/excel/metadata/CommentData.java create mode 100644 src/main/java/com/alibaba/excel/metadata/DataFormat.java create mode 100644 src/main/java/com/alibaba/excel/metadata/FormulaData.java create mode 100644 src/main/java/com/alibaba/excel/metadata/HyperlinkData.java create mode 100644 src/main/java/com/alibaba/excel/metadata/ImageData.java create mode 100644 src/main/java/com/alibaba/excel/metadata/ReadCellData.java create mode 100644 src/main/java/com/alibaba/excel/metadata/RichTextStringData.java create mode 100644 src/main/java/com/alibaba/excel/metadata/WriteCellData.java diff --git a/lombok.config b/lombok.config new file mode 100644 index 00000000..50dfe616 --- /dev/null +++ b/lombok.config @@ -0,0 +1,2 @@ +lombok.toString.callSuper = CALL +lombok.equalsAndHashCode.callSuper= CALL \ No newline at end of file diff --git a/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java b/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java index 6220340a..a7a667f0 100644 --- a/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java +++ b/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java @@ -37,13 +37,17 @@ public enum CellDataTypeEnum { */ ERROR, /** - * Images are currently supported only when writing + * image. Support only when writing. */ IMAGE, /** * date.Support only when writing. */ DATE, + /** + * rich text string.Support only when writing. + */ + RICH_TEXT_STRING, ; private static final Map TYPE_ROUTING_MAP = new HashMap(16); diff --git a/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java b/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java index 7231afd9..3cd9077b 100644 --- a/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java +++ b/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java @@ -4,6 +4,7 @@ import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.write.builder.ExcelWriterBuilder; +import lombok.Data; import lombok.Getter; import lombok.Setter; @@ -12,8 +13,7 @@ import lombok.Setter; * * @author Jiaju Zhuang */ -@Getter -@Setter +@Data public class ExcelDataConvertException extends RuntimeException { /** * NotNull. diff --git a/src/main/java/com/alibaba/excel/metadata/AbstractCell.java b/src/main/java/com/alibaba/excel/metadata/AbstractCell.java index 5cea37cf..6647cf0c 100644 --- a/src/main/java/com/alibaba/excel/metadata/AbstractCell.java +++ b/src/main/java/com/alibaba/excel/metadata/AbstractCell.java @@ -1,10 +1,13 @@ package com.alibaba.excel.metadata; +import lombok.Data; + /** * cell * * @author Jiaju Zhuang **/ +@Data public class AbstractCell implements Cell { /** * Row index @@ -14,20 +17,4 @@ public class AbstractCell implements Cell { * Column index */ private Integer columnIndex; - - public Integer getRowIndex() { - return rowIndex; - } - - public void setRowIndex(Integer rowIndex) { - this.rowIndex = rowIndex; - } - - public Integer getColumnIndex() { - return columnIndex; - } - - public void setColumnIndex(Integer columnIndex) { - this.columnIndex = columnIndex; - } } diff --git a/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java b/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java index 548503d0..d8b4ec43 100644 --- a/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java +++ b/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java @@ -6,11 +6,16 @@ import java.util.Map; import com.alibaba.excel.converters.Converter; +import lombok.Data; +import lombok.NoArgsConstructor; + /** * Write/read holder * * @author Jiaju Zhuang */ +@Data +@NoArgsConstructor public abstract class AbstractHolder implements ConfigurationHolder { /** * Record whether it's new or from cache @@ -71,46 +76,6 @@ public abstract class AbstractHolder implements ConfigurationHolder { } - public Boolean getNewInitialization() { - return newInitialization; - } - - public void setNewInitialization(Boolean newInitialization) { - this.newInitialization = newInitialization; - } - - public List> getHead() { - return head; - } - - public void setHead(List> head) { - this.head = head; - } - - public Class getClazz() { - return clazz; - } - - public void setClazz(Class clazz) { - this.clazz = clazz; - } - - public GlobalConfiguration getGlobalConfiguration() { - return globalConfiguration; - } - - public void setGlobalConfiguration(GlobalConfiguration globalConfiguration) { - this.globalConfiguration = globalConfiguration; - } - - public Map> getConverterMap() { - return converterMap; - } - - public void setConverterMap(Map> converterMap) { - this.converterMap = converterMap; - } - @Override public Map> converterMap() { return getConverterMap(); diff --git a/src/main/java/com/alibaba/excel/metadata/CellData.java b/src/main/java/com/alibaba/excel/metadata/CellData.java index 5621ed6e..604df146 100644 --- a/src/main/java/com/alibaba/excel/metadata/CellData.java +++ b/src/main/java/com/alibaba/excel/metadata/CellData.java @@ -1,14 +1,18 @@ package com.alibaba.excel.metadata; import java.math.BigDecimal; -import com.alibaba.excel.annotation.write.style.ImagePosition; import java.util.Date; + +import com.alibaba.excel.annotation.write.style.ImagePosition; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.property.ImagePositionProperty; import com.alibaba.excel.util.StringUtils; +import com.alibaba.excel.write.metadata.style.WriteCellStyle; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; +import org.apache.poi.ss.usermodel.Comment; +import org.apache.poi.ss.usermodel.Hyperlink; +import org.apache.poi.ss.usermodel.RichTextString; /** * Excel internal cell data. @@ -17,8 +21,7 @@ import lombok.Setter; * * @author Jiaju Zhuang */ -@Getter -@Setter +@Data public class CellData extends AbstractCell { private CellDataTypeEnum type; /** @@ -33,52 +36,20 @@ public class CellData extends AbstractCell { * {@link CellDataTypeEnum#BOOLEAN} */ private Boolean booleanValue; - private Boolean formula; - private String formulaValue; - private byte[] imageValue; /** - * Keep the information of image position in annotation. + * The resulting converted data. */ - private ImagePositionProperty imagePositionProperty; + private T data; /** - * It will be set true when using annotation to set the image's position. - */ - private Boolean useImagePositionProperty = false; - /** - * Support only when writing. - */ - private Date dateValue; - /** - * The number formatting. - */ - private Short dataFormat; - /** - * The string of number formatting. + * formula */ - private String dataFormatString; + private FormulaData formulaData; /** - * The resulting converted data. + * data format */ - private T data; - - public CellData(CellData other) { - this.type = other.type; - this.numberValue = other.numberValue; - this.stringValue = other.stringValue; - this.booleanValue = other.booleanValue; - this.formula = other.formula; - this.formulaValue = other.formulaValue; - this.imageValue = other.imageValue; - this.imagePositionProperty = other.imagePositionProperty; - this.useImagePositionProperty = other.useImagePositionProperty; - this.dataFormat = other.dataFormat; - this.dataFormatString = other.dataFormatString; - this.data = other.data; - setRowIndex(other.getRowIndex()); - setColumnIndex(other.getColumnIndex()); - } + private DataFormat dataFormat; public CellData() {} @@ -86,12 +57,6 @@ public class CellData extends AbstractCell { this.data = data; } - public CellData(T data, String formulaValue) { - this.data = data; - this.formula = Boolean.TRUE; - this.formulaValue = formulaValue; - } - public CellData(String stringValue) { this(CellDataTypeEnum.STRING, stringValue); } @@ -105,7 +70,6 @@ public class CellData extends AbstractCell { } this.type = type; this.stringValue = stringValue; - this.formula = Boolean.FALSE; } public CellData(BigDecimal numberValue) { @@ -114,7 +78,6 @@ public class CellData extends AbstractCell { } this.type = CellDataTypeEnum.NUMBER; this.numberValue = numberValue; - this.formula = Boolean.FALSE; } public CellData(byte[] imageValue) { @@ -123,7 +86,6 @@ public class CellData extends AbstractCell { } this.type = CellDataTypeEnum.IMAGE; this.imageValue = imageValue; - this.formula = Boolean.FALSE; } public CellData(byte[] imageValue, ImagePosition imagePosition) { @@ -146,7 +108,6 @@ public class CellData extends AbstractCell { } this.type = CellDataTypeEnum.BOOLEAN; this.booleanValue = booleanValue; - this.formula = Boolean.FALSE; } public CellData(Date dateValue) { @@ -158,7 +119,6 @@ public class CellData extends AbstractCell { this.formula = Boolean.FALSE; } - public CellData(CellDataTypeEnum type) { if (type == null) { throw new IllegalArgumentException("Type can not be null"); @@ -230,39 +190,4 @@ public class CellData extends AbstractCell { return cellData; } - @Override - public String toString() { - if (type == null) { - return StringUtils.EMPTY; - } - switch (type) { - case NUMBER: - if (numberValue == null) { - return StringUtils.EMPTY; - } - return numberValue.toString(); - case BOOLEAN: - if (booleanValue == null) { - return StringUtils.EMPTY; - } - return booleanValue.toString(); - case DIRECT_STRING: - case STRING: - case ERROR: - return stringValue; - case DATE: - if (dateValue == null) { - return StringUtils.EMPTY; - } - return dateValue.toString(); - case IMAGE: - if (imageValue == null) { - return StringUtils.EMPTY; - } - return "image[" + imageValue.length + "]"; - default: - return StringUtils.EMPTY; - } - } - } diff --git a/src/main/java/com/alibaba/excel/metadata/ClientAnchorData.java b/src/main/java/com/alibaba/excel/metadata/ClientAnchorData.java new file mode 100644 index 00000000..cf215e6f --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/ClientAnchorData.java @@ -0,0 +1,139 @@ +package com.alibaba.excel.metadata; + +import lombok.Data; +import org.apache.poi.ss.usermodel.ClientAnchor; +import org.apache.poi.util.Internal; + +/** + * A client anchor is attached to an excel worksheet. It anchors against + * absolute coordinates, a top-left cell and fixed height and width, or + * a top-left and bottom-right cell, depending on the {@link ClientAnchorData.AnchorType}: + *
    + *
  1. {@link ClientAnchor.AnchorType#DONT_MOVE_AND_RESIZE} == absolute top-left coordinates and width/height, no + * cell references + *
  2. {@link ClientAnchor.AnchorType#MOVE_DONT_RESIZE} == fixed top-left cell reference, absolute width/height + *
  3. {@link ClientAnchor.AnchorType#MOVE_AND_RESIZE} == fixed top-left and bottom-right cell references, dynamic + * width/height + *
+ * Note this class only reports the current values for possibly calculated positions and sizes. + * If the sheet row/column sizes or positions shift, this needs updating via external calculations. + * + * @author Jiaju Zhuang + */ +@Data +public class ClientAnchorData { + + /** + * The x coordinate within the first cell. + */ + private int dx1; + + /** + * The y coordinate within the first cell. + */ + private int dy1; + + /** + * The x coordinate within the second cell. + */ + private int dx2; + + /** + * The y coordinate within the second cell + */ + private int dy2; + + /** + * 0-based column of the first cell. + */ + private short col1; + + /** + * 0-based row of the first cell. + */ + private int row1; + + /** + * 0-based column of the second cell. + */ + private short col2; + + /** + * 0-based row of the second cell. + */ + private int row2; + /** + * anchor type + */ + private AnchorType anchorType; + + public enum AnchorType { + /** + * Move and Resize With Anchor Cells (0) + *

+ * Specifies that the current drawing shall move and + * resize to maintain its row and column anchors (i.e. the + * object is anchored to the actual from and to row and column) + *

+ */ + MOVE_AND_RESIZE(0), + + /** + * Don't Move but do Resize With Anchor Cells (1) + *

+ * Specifies that the current drawing shall not move with its + * row and column, but should be resized. This option is not normally + * used, but is included for completeness. + *

+ * Note: Excel has no setting for this combination, nor does the ECMA standard. + */ + DONT_MOVE_DO_RESIZE(1), + + /** + * Move With Cells but Do Not Resize (2) + *

+ * Specifies that the current drawing shall move with its + * row and column (i.e. the object is anchored to the + * actual from row and column), but that the size shall remain absolute. + *

+ *

+ * If additional rows/columns are added between the from and to locations of the drawing, + * the drawing shall move its to anchors as needed to maintain this same absolute size. + *

+ */ + MOVE_DONT_RESIZE(2), + + /** + * Do Not Move or Resize With Underlying Rows/Columns (3) + *

+ * Specifies that the current start and end positions shall + * be maintained with respect to the distances from the + * absolute start point of the worksheet. + *

+ *

+ * If additional rows/columns are added before the + * drawing, the drawing shall move its anchors as needed + * to maintain this same absolute position. + *

+ */ + DONT_MOVE_AND_RESIZE(3); + + public final short value; + + // disallow non-sequential enum instance creation + private AnchorType(int value) { + this.value = (short)value; + } + + /** + * return the AnchorType corresponding to the code + * + * @param value the anchor type code + * @return the anchor type enum + */ + @Internal + public static ClientAnchorData.AnchorType byId(int value) { + return values()[value]; + } + } +} diff --git a/src/main/java/com/alibaba/excel/metadata/CommentData.java b/src/main/java/com/alibaba/excel/metadata/CommentData.java new file mode 100644 index 00000000..94c1b675 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/CommentData.java @@ -0,0 +1,28 @@ +package com.alibaba.excel.metadata; + +import lombok.Data; + +/** + * TODO + * + * @author Jiaju Zhuang + */ +@Data +public class CommentData { + /** + * Row index + */ + private Integer rowIndex; + /** + * Column index + */ + private Integer columnIndex; + /** + * Name of the original comment author + */ + private String author; + /** + * rich text string + */ + private RichTextStringData richTextStringData; +} diff --git a/src/main/java/com/alibaba/excel/metadata/DataFormat.java b/src/main/java/com/alibaba/excel/metadata/DataFormat.java new file mode 100644 index 00000000..fdaa5236 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/DataFormat.java @@ -0,0 +1,20 @@ +package com.alibaba.excel.metadata; + +import lombok.Data; + +/** + * data format + * + * @author Jiaju Zhuang + */ +@Data +public class DataFormat { + /** + * index + */ + private Short index; + /** + * format + */ + private String format; +} diff --git a/src/main/java/com/alibaba/excel/metadata/FormulaData.java b/src/main/java/com/alibaba/excel/metadata/FormulaData.java new file mode 100644 index 00000000..8f3c4f15 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/FormulaData.java @@ -0,0 +1,16 @@ +package com.alibaba.excel.metadata; + +import lombok.Data; + +/** + * formula + * + * @author Jiaju Zhuang + */ +@Data +public class FormulaData { + /** + * formula + */ + private String formulaValue; +} diff --git a/src/main/java/com/alibaba/excel/metadata/HyperlinkData.java b/src/main/java/com/alibaba/excel/metadata/HyperlinkData.java new file mode 100644 index 00000000..f3453c64 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/HyperlinkData.java @@ -0,0 +1,10 @@ +package com.alibaba.excel.metadata; + +/** + * TODO + * + * @author Jiaju Zhuang + */ +public class HyperlinkData { + +} diff --git a/src/main/java/com/alibaba/excel/metadata/ImageData.java b/src/main/java/com/alibaba/excel/metadata/ImageData.java new file mode 100644 index 00000000..e1bb30fa --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/ImageData.java @@ -0,0 +1,58 @@ +package com.alibaba.excel.metadata; + +import lombok.Data; + +/** + * image + * + * @author Jiaju Zhuang + */ +@Data +public class ImageData extends ClientAnchorData { + + /** + * image + */ + private byte[] image; + + /** + * image type + */ + private ImageType imageType; + + public enum ImageType { + /** + * Extended windows meta file + */ + PICTURE_TYPE_EMF(2), + /** + * Windows Meta File + */ + PICTURE_TYPE_WMF(3), + /** + * Mac PICT format + */ + PICTURE_TYPE_PICT(4), + /** + * JPEG format + */ + PICTURE_TYPE_JPEG(5), + /** + * PNG format + */ + PICTURE_TYPE_PNG(6), + /** + * Device independent bitmap + */ + PICTURE_TYPE_DIB(7), + + ; + + public final int value; + + ImageType(int value) { + this.value = value; + } + } + +} diff --git a/src/main/java/com/alibaba/excel/metadata/ReadCellData.java b/src/main/java/com/alibaba/excel/metadata/ReadCellData.java new file mode 100644 index 00000000..cf9ad233 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/ReadCellData.java @@ -0,0 +1,13 @@ +package com.alibaba.excel.metadata; + +import lombok.Data; + +/** + * TODO + * + * @author Jiaju Zhuang + */ +@Data +public class ReadCellData extends CellData{ + +} diff --git a/src/main/java/com/alibaba/excel/metadata/RichTextStringData.java b/src/main/java/com/alibaba/excel/metadata/RichTextStringData.java new file mode 100644 index 00000000..eabb85c3 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/RichTextStringData.java @@ -0,0 +1,59 @@ +package com.alibaba.excel.metadata; + +import java.util.List; + +import com.alibaba.excel.util.ListUtils; +import com.alibaba.excel.write.metadata.style.WriteFont; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * TODO + * + * @author Jiaju Zhuang + */ +@Data +@NoArgsConstructor +public class RichTextStringData { + private String textString; + private WriteFont writeFont; + private List intervalFontList; + + public RichTextStringData(String textString) { + this.textString = textString; + } + + @Data + @AllArgsConstructor + public static class IntervalFont { + private Integer startIndex; + private Integer endIndex; + private WriteFont writeFont; + } + + /** + * Applies a font to the specified characters of a string. + * + * @param startIndex The start index to apply the font to (inclusive) + * @param endIndex The end index to apply to font to (exclusive) + * @param writeFont The font to use. + */ + public void applyFont(int startIndex, int endIndex, WriteFont writeFont) { + if (intervalFontList == null) { + intervalFontList = ListUtils.newArrayList(); + } + intervalFontList.add(new IntervalFont(startIndex, endIndex, writeFont)); + } + + /** + * Sets the font of the entire string. + * + * @param writeFont The font to use. + */ + public void applyFont(WriteFont writeFont) { + this.writeFont = writeFont; + } + +} diff --git a/src/main/java/com/alibaba/excel/metadata/WriteCellData.java b/src/main/java/com/alibaba/excel/metadata/WriteCellData.java new file mode 100644 index 00000000..901aa916 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/WriteCellData.java @@ -0,0 +1,42 @@ +package com.alibaba.excel.metadata; + +import java.util.Date; + +import com.alibaba.excel.enums.CellDataTypeEnum; +import com.alibaba.excel.write.metadata.style.WriteCellStyle; + +import lombok.Data; + +/** + * TODO + * + * @author Jiaju Zhuang + */ +@Data +public class WriteCellData extends CellData { + /** + * Support only when writing.{@link CellDataTypeEnum#DATE} + */ + private Date dateValue; + /** + * {@link CellDataTypeEnum#IMAGE} + */ + private ImageData imageDataValue; + /** + * rich text.{@link CellDataTypeEnum#RICH_TEXT_STRING} + */ + private RichTextStringData richTextStringDataValue; + + /** + * comment + */ + private CommentData commentData; + /** + * hyper link + */ + private HyperlinkData hyperlinkData; + /** + * sytle + */ + private WriteCellStyle writeCellStyle; +} diff --git a/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java b/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java index 5915cf06..34c9d4d0 100644 --- a/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java +++ b/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java @@ -1,19 +1,13 @@ package com.alibaba.excel.metadata.property; import java.lang.reflect.Field; -import java.util.AbstractMap; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; -import org.apache.commons.collections4.CollectionUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.format.DateTimeFormat; import com.alibaba.excel.annotation.format.NumberFormat; @@ -27,11 +21,17 @@ import com.alibaba.excel.util.ClassUtils; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.write.metadata.holder.AbstractWriteHolder; +import lombok.Data; +import org.apache.commons.collections4.CollectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Define the header attribute of excel * * @author jipengfei */ +@Data public class ExcelHeadProperty { private static final Logger LOGGER = LoggerFactory.getLogger(ExcelHeadProperty.class); @@ -64,7 +64,7 @@ public class ExcelHeadProperty { */ private Map ignoreMap; - public ExcelHeadProperty(Holder holder, Class headClazz, List> head, Boolean convertAllField) { + public ExcelHeadProperty(Holder holder, Class headClazz, List> head, Boolean convertAllFiled) { this.headClazz = headClazz; headMap = new TreeMap(); contentPropertyMap = new TreeMap(); @@ -87,7 +87,7 @@ public class ExcelHeadProperty { headKind = HeadKindEnum.STRING; } // convert headClazz to head - initColumnProperties(holder, convertAllField); + initColumnProperties(holder, convertAllFiled); initHeadRowNumber(); if (LOGGER.isDebugEnabled()) { @@ -115,7 +115,7 @@ public class ExcelHeadProperty { } } - private void initColumnProperties(Holder holder, Boolean convertAllField) { + private void initColumnProperties(Holder holder, Boolean convertAllFiled) { if (headClazz == null) { return; } @@ -124,9 +124,9 @@ public class ExcelHeadProperty { Map indexFiledMap = new TreeMap(); boolean needIgnore = (holder instanceof AbstractWriteHolder) && ( - !CollectionUtils.isEmpty(((AbstractWriteHolder) holder).getExcludeColumnFiledNames()) || !CollectionUtils + !CollectionUtils.isEmpty(((AbstractWriteHolder) holder).getExcludeColumnFieldNames()) || !CollectionUtils .isEmpty(((AbstractWriteHolder) holder).getExcludeColumnIndexes()) || !CollectionUtils - .isEmpty(((AbstractWriteHolder) holder).getIncludeColumnFiledNames()) || !CollectionUtils + .isEmpty(((AbstractWriteHolder) holder).getIncludeColumnFieldNames()) || !CollectionUtils .isEmpty(((AbstractWriteHolder) holder).getIncludeColumnIndexes())); ClassUtils.declaredFields(headClazz, sortedAllFiledMap, indexFiledMap, ignoreMap, convertAllFiled, needIgnore, holder); @@ -134,6 +134,7 @@ public class ExcelHeadProperty { for (Map.Entry entry : sortedAllFiledMap.entrySet()) { initOneColumnProperty(entry.getKey(), entry.getValue(), indexFiledMap.containsKey(entry.getKey())); } + headKind = HeadKindEnum.CLASS; } /** @@ -182,63 +183,8 @@ public class ExcelHeadProperty { fieldNameContentPropertyMap.put(field.getName(), excelContentProperty); } - public Class getHeadClazz() { - return headClazz; - } - - public void setHeadClazz(Class headClazz) { - this.headClazz = headClazz; - } - - public HeadKindEnum getHeadKind() { - return headKind; - } - - public void setHeadKind(HeadKindEnum headKind) { - this.headKind = headKind; - } - public boolean hasHead() { return headKind != HeadKindEnum.NONE; } - public int getHeadRowNumber() { - return headRowNumber; - } - - public void setHeadRowNumber(int headRowNumber) { - this.headRowNumber = headRowNumber; - } - - public Map getHeadMap() { - return headMap; - } - - public void setHeadMap(Map headMap) { - this.headMap = headMap; - } - - public Map getContentPropertyMap() { - return contentPropertyMap; - } - - public void setContentPropertyMap(Map contentPropertyMap) { - this.contentPropertyMap = contentPropertyMap; - } - - public Map getFieldNameContentPropertyMap() { - return fieldNameContentPropertyMap; - } - - public void setFieldNameContentPropertyMap(Map fieldNameContentPropertyMap) { - this.fieldNameContentPropertyMap = fieldNameContentPropertyMap; - } - - public Map getIgnoreMap() { - return ignoreMap; - } - - public void setIgnoreMap(Map ignoreMap) { - this.ignoreMap = ignoreMap; - } } diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java index 95bf6f89..396fa55a 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java @@ -15,14 +15,14 @@ import com.alibaba.excel.read.metadata.ReadWorkbook; import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty; import com.alibaba.excel.util.ListUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.Data; /** * Read Holder * * @author Jiaju Zhuang */ +@Data public abstract class AbstractReadHolder extends AbstractHolder implements ReadHolder { /** * Count the number of added heads when read sheet. @@ -112,29 +112,6 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH } } - public List getReadListenerList() { - return readListenerList; - } - - public void setReadListenerList(List readListenerList) { - this.readListenerList = readListenerList; - } - - public ExcelReadHeadProperty getExcelReadHeadProperty() { - return excelReadHeadProperty; - } - - public void setExcelReadHeadProperty(ExcelReadHeadProperty excelReadHeadProperty) { - this.excelReadHeadProperty = excelReadHeadProperty; - } - - public Integer getHeadRowNumber() { - return headRowNumber; - } - - public void setHeadRowNumber(Integer headRowNumber) { - this.headRowNumber = headRowNumber; - } @Override public List readListenerList() { diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 4d96e8c4..c4b3e45e 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -179,9 +179,9 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { } WriteWorkbookHolder writeWorkbookHolder = writeContext.writeWorkbookHolder(); boolean needIgnore = - !CollectionUtils.isEmpty(writeWorkbookHolder.getExcludeColumnFiledNames()) || !CollectionUtils + !CollectionUtils.isEmpty(writeWorkbookHolder.getExcludeColumnFieldNames()) || !CollectionUtils .isEmpty(writeWorkbookHolder.getExcludeColumnIndexes()) || !CollectionUtils - .isEmpty(writeWorkbookHolder.getIncludeColumnFiledNames()) || !CollectionUtils + .isEmpty(writeWorkbookHolder.getIncludeColumnFieldNames()) || !CollectionUtils .isEmpty(writeWorkbookHolder.getIncludeColumnIndexes()); ClassUtils.declaredFields(clazz, sortedAllFiledMap, writeWorkbookHolder.getWriteWorkbook().getConvertAllFiled(), needIgnore, writeWorkbookHolder); diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java index e7132481..54c31245 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java @@ -9,6 +9,8 @@ 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; @@ -50,6 +52,8 @@ import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy; * * @author Jiaju Zhuang */ +@Data +@NoArgsConstructor public abstract class AbstractWriteHolder extends AbstractHolder implements WriteHolder { /** * Need Head diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java index afae52b8..57f13584 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java @@ -8,7 +8,9 @@ import com.alibaba.excel.enums.WriteLastRowTypeEnum; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.write.metadata.WriteSheet; +import lombok.Data; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.Setter; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.ss.usermodel.Sheet; @@ -20,8 +22,8 @@ import org.apache.poi.xssf.usermodel.XSSFSheet; * * @author Jiaju Zhuang */ -@Getter -@Setter +@Data +@NoArgsConstructor public class WriteSheetHolder extends AbstractWriteHolder { /** * current param diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java index 19e4622b..671b96f7 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java @@ -20,6 +20,7 @@ import com.alibaba.excel.util.MapUtils; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.write.metadata.WriteWorkbook; +import lombok.Data; import lombok.Getter; import lombok.Setter; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -33,8 +34,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook; * * @author Jiaju Zhuang */ -@Getter -@Setter +@Data public class WriteWorkbookHolder extends AbstractWriteHolder { /*** * Current poi Workbook.This is only for writing, and there may be no data in version 07 when template data needs to diff --git a/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java b/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java index 81c85e83..330aa51a 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java +++ b/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java @@ -1,5 +1,10 @@ package com.alibaba.excel.write.metadata.style; +import com.alibaba.excel.metadata.property.FontProperty; +import com.alibaba.excel.metadata.property.StyleProperty; +import com.alibaba.excel.util.StringUtils; + +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,15 +13,12 @@ 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.metadata.property.FontProperty; -import com.alibaba.excel.metadata.property.StyleProperty; -import com.alibaba.excel.util.StringUtils; - /** * Cell style when writing * * @author Jiaju Zhuang */ +@Data public class WriteCellStyle { /** * Set the data format (must be a valid format). Built in formats are defined at {@link BuiltinFormats}. @@ -213,180 +215,4 @@ public class WriteCellStyle { return writeCellStyle; } - - 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; - } } diff --git a/src/main/java/com/alibaba/excel/write/metadata/style/WriteFont.java b/src/main/java/com/alibaba/excel/write/metadata/style/WriteFont.java index 6ed4c2a7..38c65539 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/style/WriteFont.java +++ b/src/main/java/com/alibaba/excel/write/metadata/style/WriteFont.java @@ -1,5 +1,6 @@ package com.alibaba.excel.write.metadata.style; +import lombok.Data; import org.apache.poi.common.usermodel.fonts.FontCharset; import org.apache.poi.hssf.usermodel.HSSFPalette; import org.apache.poi.ss.usermodel.Font; @@ -10,6 +11,7 @@ import org.apache.poi.ss.usermodel.IndexedColors; * * @author jipengfei */ +@Data public class WriteFont { /** * The name for the font (i.e. Arial) @@ -68,76 +70,4 @@ public class WriteFont { * Bold */ private Boolean bold; - - public String getFontName() { - return fontName; - } - - public void setFontName(String fontName) { - this.fontName = fontName; - } - - public Short getFontHeightInPoints() { - return fontHeightInPoints; - } - - public void setFontHeightInPoints(Short fontHeightInPoints) { - this.fontHeightInPoints = fontHeightInPoints; - } - - public Boolean getItalic() { - return italic; - } - - public void setItalic(Boolean italic) { - this.italic = italic; - } - - public Boolean getStrikeout() { - return strikeout; - } - - public void setStrikeout(Boolean strikeout) { - this.strikeout = strikeout; - } - - public Short getColor() { - return color; - } - - public void setColor(Short color) { - this.color = color; - } - - public Short getTypeOffset() { - return typeOffset; - } - - public void setTypeOffset(Short typeOffset) { - this.typeOffset = typeOffset; - } - - public Byte getUnderline() { - return underline; - } - - public void setUnderline(Byte underline) { - this.underline = underline; - } - - public Integer getCharset() { - return charset; - } - - public void setCharset(Integer charset) { - this.charset = charset; - } - - public Boolean getBold() { - return bold; - } - - public void setBold(Boolean bold) { - this.bold = bold; - } } From 3b89f724dd45bbeb864ce8a93cd88cdfec32c558 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=84=A6=E6=9D=BE?= Date: Thu, 15 Apr 2021 17:26:45 +0800 Subject: [PATCH 052/129] Fix bug list classType not same with head type when write --- .../write/executor/ExcelWriteAddExecutor.java | 4 +- .../easyexcel/test/temp/bug/DataType.java | 33 ++++++++++++++++ .../easyexcel/test/temp/bug/ExcelCreat.java | 38 +++++++++++++++++++ .../easyexcel/test/temp/bug/HeadType.java | 28 ++++++++++++++ 4 files changed, 101 insertions(+), 2 deletions(-) create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/bug/DataType.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/bug/ExcelCreat.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/bug/HeadType.java diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 9f229029..4a148ac1 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -149,7 +149,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { Map ignoreMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getIgnoreMap(); initSortedAllFiledMapFieldList(oneRowData.getClass(), sortedAllFiledMap); for (Map.Entry entry : sortedAllFiledMap.entrySet()) { - cellIndex = entry.getKey(); + // cellIndex = entry.getKey(); Field field = entry.getValue(); String filedName = field.getName(); boolean uselessData = !beanMap.containsKey(filedName) || beanMapHandledSet.contains(filedName) @@ -158,7 +158,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { continue; } Object value = beanMap.get(filedName); - WriteHandlerUtils.beforeCellCreate(writeContext, row, null, cellIndex, relativeRowIndex, Boolean.FALSE); + 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(), cell, diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/bug/DataType.java b/src/test/java/com/alibaba/easyexcel/test/temp/bug/DataType.java new file mode 100644 index 00000000..37b8dc2b --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/bug/DataType.java @@ -0,0 +1,33 @@ +package com.alibaba.easyexcel.test.temp.bug; + +import com.alibaba.excel.annotation.ExcelProperty; +import lombok.Data; + +/** + * @author jiaosong + * @desc + * @date 2021/4/6 + */ +@Data +public class DataType { + /** + * 任务id + */ + @ExcelProperty("任务ID") + private Integer id; + + @ExcelProperty("多余字段1") + private String firstSurplus; + + @ExcelProperty("多余字段2") + private String secSurplus; + + @ExcelProperty("多余字段3") + private String thirdSurplus; + + @ExcelProperty(value = "备注1") + private String firstRemark; + + @ExcelProperty(value = "备注2") + private String secRemark; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/bug/ExcelCreat.java b/src/test/java/com/alibaba/easyexcel/test/temp/bug/ExcelCreat.java new file mode 100644 index 00000000..f9d97463 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/bug/ExcelCreat.java @@ -0,0 +1,38 @@ +package com.alibaba.easyexcel.test.temp.bug; + +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.ExcelWriter; +import com.alibaba.excel.write.metadata.WriteSheet; + +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.util.Collections; +import java.util.List; + +/** + * @author jiaosong + * @desc + * @date 2020/4/6 + */ +public class ExcelCreat { + + + public static void main(String[] args) throws FileNotFoundException { + List data = getData(); + ExcelWriter excelWriter = null; + excelWriter = EasyExcel.write(new FileOutputStream("all.xlsx")).build(); + WriteSheet writeSheet = EasyExcel.writerSheet(1, "test") + .head(HeadType.class) + .build(); + excelWriter.write(data, writeSheet); + excelWriter.finish(); + } + + private static List getData() { + DataType vo = new DataType(); + vo.setId(738); + vo.setFirstRemark("1222"); + vo.setSecRemark("22222"); + return Collections.singletonList(vo); + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/bug/HeadType.java b/src/test/java/com/alibaba/easyexcel/test/temp/bug/HeadType.java new file mode 100644 index 00000000..15ee006d --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/bug/HeadType.java @@ -0,0 +1,28 @@ +package com.alibaba.easyexcel.test.temp.bug; + +import com.alibaba.excel.annotation.ExcelProperty; +import lombok.Data; + +/** + * @author jiaosong + * @desc + * @date 2021/4/6 + */ +@Data +public class HeadType { + + + /** + * 任务id + */ + @ExcelProperty("任务ID") + private Integer id; + + + @ExcelProperty(value = "备注1") + private String firstRemark; + + @ExcelProperty(value = "备注2") + private String secRemark; + +} From b3c8a699d4b7455f52dbaa9c7b58e4f3fac753e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=84=A6=E6=9D=BE?= Date: Thu, 15 Apr 2021 17:48:38 +0800 Subject: [PATCH 053/129] Remove commented code --- .../com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 4a148ac1..98dc4f9a 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -149,7 +149,6 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { Map ignoreMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getIgnoreMap(); initSortedAllFiledMapFieldList(oneRowData.getClass(), sortedAllFiledMap); for (Map.Entry entry : sortedAllFiledMap.entrySet()) { - // cellIndex = entry.getKey(); Field field = entry.getValue(); String filedName = field.getName(); boolean uselessData = !beanMap.containsKey(filedName) || beanMapHandledSet.contains(filedName) From 4d04fe3163718c47fb627909359474898327a0df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=84=A6=E6=9D=BE?= Date: Fri, 16 Apr 2021 14:24:39 +0800 Subject: [PATCH 054/129] Fix bug: sort map no head --- .../write/executor/ExcelWriteAddExecutor.java | 30 +++++++------------ 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 98dc4f9a..1168bde3 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -1,16 +1,5 @@ package com.alibaba.excel.write.executor; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; - import com.alibaba.excel.context.WriteContext; import com.alibaba.excel.enums.HeadKindEnum; import com.alibaba.excel.metadata.CellData; @@ -20,13 +9,15 @@ import com.alibaba.excel.util.ClassUtils; import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.WorkBookUtil; import com.alibaba.excel.util.WriteHandlerUtils; -import com.alibaba.excel.write.metadata.WriteWorkbook; -import com.alibaba.excel.write.metadata.holder.AbstractWriteHolder; import com.alibaba.excel.write.metadata.holder.WriteHolder; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; - import net.sf.cglib.beans.BeanMap; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; + +import java.lang.reflect.Field; +import java.util.*; /** * Add the data into excel @@ -59,7 +50,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { } private void addOneRowOfDataToExcel(Object oneRowData, int n, int relativeRowIndex, - Map sortedAllFiledMap) { + Map sortedAllFiledMap) { if (oneRowData == null) { return; } @@ -103,7 +94,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { } private void doAddBasicTypeToExcel(List oneRowData, Head head, Row row, int relativeRowIndex, int dataIndex, - int cellIndex) { + 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); @@ -114,7 +105,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { } private void addJavaObjectToExcel(Object oneRowData, Row row, int relativeRowIndex, - Map sortedAllFiledMap) { + Map sortedAllFiledMap) { WriteHolder currentWriteHolder = writeContext.currentWriteHolder(); BeanMap beanMap = BeanMap.create(oneRowData); Set beanMapHandledSet = new HashSet(); @@ -141,6 +132,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE); beanMapHandledSet.add(name); } + cellIndex++; } // Finish if (beanMapHandledSet.size() == beanMap.size()) { @@ -157,8 +149,8 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { continue; } Object value = beanMap.get(filedName); - WriteHandlerUtils.beforeCellCreate(writeContext, row, null, cellIndex++, relativeRowIndex, Boolean.FALSE); - Cell cell = WorkBookUtil.createCell(row, cellIndex); + 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(), cell, value, null, null, relativeRowIndex); From 0aa3dbbc4b98713a84f8d5812f9dcf7cd4e40701 Mon Sep 17 00:00:00 2001 From: JackeyXps <599591947@qq.com> Date: Sat, 17 Apr 2021 16:56:09 +0800 Subject: [PATCH 055/129] fixed write with only one head without Model issue1702 --- .../write/executor/ExcelWriteAddExecutor.java | 2 +- .../easyexcel/test/demo/write/WriteTest.java | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 9f229029..84b9821d 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -93,7 +93,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { if (dataIndex >= oneRowData.size()) { return; } - if (cellIndex != 0) { + if (headMap.size() != 0) { cellIndex++; } int size = oneRowData.size() - dataIndex; diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java index 4bce5127..15811fcf 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java @@ -502,6 +502,22 @@ public class WriteTest { EasyExcel.write(fileName, ConverterData.class).head(variableTitleHead()).sheet("模板").doWrite(data()); } + @Test + public void noModelSimpleWriteWithOneHead() { + // 写法1 + String fileName = TestFileUtil.getPath() + "noModelSimpleWrite" + System.currentTimeMillis() + ".xlsx"; + // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 + EasyExcel.write(fileName).head(noModelSimpleOneHead()).sheet("模板").doWrite(dataList()); + } + + private List> noModelSimpleOneHead() { + List> list = new ArrayList>(); + List head0 = new ArrayList(); + head0.add("表头1"); + list.add(head0); + return list; + } + /** * 不创建对象的写 */ From 937dee76ff8989e5dc1c7e175ceefe71a59ae363 Mon Sep 17 00:00:00 2001 From: JackeyXps <599591947@qq.com> Date: Sat, 17 Apr 2021 17:17:01 +0800 Subject: [PATCH 056/129] =?UTF-8?q?fix=20issue1702=20=E4=B8=8D=E5=88=9B?= =?UTF-8?q?=E5=BB=BA=E5=AF=B9=E8=B1=A1=E7=9A=84=E5=86=99=EF=BC=8C=E6=97=A0?= =?UTF-8?q?=E6=B3=95=E6=AD=A3=E5=B8=B8=E5=86=99=E5=85=A5=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/excel/write/executor/ExcelWriteAddExecutor.java | 2 +- .../com/alibaba/easyexcel/test/demo/write/WriteTest.java | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 84b9821d..63ed5ce3 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -93,7 +93,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { if (dataIndex >= oneRowData.size()) { return; } - if (headMap.size() != 0) { + if (dataIndex != 0) { cellIndex++; } int size = oneRowData.size() - dataIndex; diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java index 15811fcf..f914f87d 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java @@ -503,14 +503,14 @@ public class WriteTest { } @Test - public void noModelSimpleWriteWithOneHead() { + public void noModelWriteWithOneHead() { // 写法1 String fileName = TestFileUtil.getPath() + "noModelSimpleWrite" + System.currentTimeMillis() + ".xlsx"; // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - EasyExcel.write(fileName).head(noModelSimpleOneHead()).sheet("模板").doWrite(dataList()); + EasyExcel.write(fileName).head(noModelOneHead()).sheet("模板").doWrite(dataList()); } - private List> noModelSimpleOneHead() { + private List> noModelOneHead() { List> list = new ArrayList>(); List head0 = new ArrayList(); head0.add("表头1"); From ec77c3e7400003f3be1a6e0d61f2689e74106426 Mon Sep 17 00:00:00 2001 From: smireg <402809775@qq.com> Date: Sun, 18 Apr 2021 00:15:58 +0800 Subject: [PATCH 057/129] fix #1702 --- .../write/executor/ExcelWriteAddExecutor.java | 5 +- .../test/demo/Test1702/Date1702.java | 35 +++++++++++++ .../test/demo/Test1702/Date1702.xlsx | Bin 0 -> 3557 bytes .../test/demo/Test1702/Issue1702.java | 47 ++++++++++++++++++ 4 files changed, 83 insertions(+), 4 deletions(-) create mode 100644 src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.xlsx create mode 100644 src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Issue1702.java diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 9f229029..e75b333e 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -87,15 +87,12 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { } cellIndex = entry.getKey(); Head head = entry.getValue(); - doAddBasicTypeToExcel(oneRowData, head, row, relativeRowIndex, dataIndex++, cellIndex); + doAddBasicTypeToExcel(oneRowData, head, row, relativeRowIndex, dataIndex++, cellIndex++); } // Finish if (dataIndex >= oneRowData.size()) { return; } - if (cellIndex != 0) { - cellIndex++; - } int size = oneRowData.size() - dataIndex; for (int i = 0; i < size; i++) { doAddBasicTypeToExcel(oneRowData, null, row, relativeRowIndex, dataIndex++, cellIndex++); diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.java b/src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.java new file mode 100644 index 00000000..c2bd7314 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.java @@ -0,0 +1,35 @@ +package com.alibaba.easyexcel.test.demo.Test1702; + +import com.alibaba.excel.annotation.ExcelProperty; + +import java.util.Date; + +public class Date1702 { + @ExcelProperty(index = 0) + private String str; + @ExcelProperty(index = 1) + private Date date; + @ExcelProperty(index = 2) + private double r; + public void setStr(String str) { + this.str = str; + } + public void setDate(Date date) { + this.date = date; + } + public void setR(double r) { + this.r = r; + } + + public String getStr() { + return str; + } + + public Date getDate(){ + return date; + } + public double getR(){ + return r; + } +} + diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.xlsx b/src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..66cd1a2f361b792492007e460b335908f3aa95af GIT binary patch literal 3557 zcmaJ@c|25Y8>Yd`kdP%?*;RP6h9a^yvP;>@Hiogzf-;t|HX;UDix!ORh3rh4RI(&X zA~MO6tz^we^3CY`US8i@_xYVO=Z|wgbKloAetY$lN;{e8<7Klw>BUUpmC~X?ld=P3ONd45^cuTgyewpd{RjHIZ~oL zfJjJvfBiuCo-`ci^TBCVV2bT0`@@xD-v}z+LB&g^Oj(M3-Fz?4)G+x!eV@#mad@K> z6YO*-GqyB7LAMD!@n9)!pO*tb&*tUh3_9ZHinYrqFCoQ#W25ON7@Q{-|6Zz(p>4GA zqGG*`Tt(J2;%t9H4gh?T>qm|~X!?=RK*%05Lm((WE|54z?c87w9i7>4vEihCVW)%e z@q_vJIap$lFyBkZ0=&Jd&b9kIm1F;r`m$e2dD-kdcesvF3s2!P;9^j+HAUiK_WbH4 zplXUm3^QsG>gwid_06RkRc))I%^BSMBKVoqycB$_0T&`;KNEDpDb3zcKwYT=sGMoS zGX%0WFKofBoM-`xn5~S6FS3(3dvN0}_n|YoDIQ1F*lTjTZ<~?a=Ic83B8?B5cD1Fx z>KmJT3{f$90gu0N(;}v-|4hz`ed6IV05FJi0S77xBqz2#5YSGFQ53|pwBMW|!;iJX zDOQzT)%xN4JSGaFbjySjd0hq-~4El{MZ8 zMe%+Mea9vo>%=F7zVJR1Kt=< zVx|JG`!!;d9gV07WKUAc6OK3>)Wrsxe#>;r7;<5HGBY_ai|^BdWzBcJMtRtQg4Blk zq&=;;?(Rpa3F~<$+e{ED9uN^{=V+T0;KYT_js=FqFLC7Y`VPyqqvD9#XUkD?#+{=l z2GY+s52(DNN5TjkEmGKUi(-uz&uyCZv{$>i2)sU4jGM%WyOBSs@zuby-2r+sRXJV_=Kf3j4$O{M9wZSFW|J|{ z2QfV>VU-u++bn9fANhpCfBuODlcv{cmG7azG#814#}0+=w|WY#Yil_o^M^9mVQYl` zrGAN?diBCOzax93_A{yn4-CA#vS@wL{&q)q1yujH~vIPVkEszd7O^PX59?Ctns zS!a=hH=2i6I!a$l{3xvZ$w0#}E)_7tNF_xX_5MAETvQALykvdhPH33RIX|?!kDD(I z##3=xG-A+wjR*w=)x;dqCAhOi$aVpv{Ji(Pl5|xWU3%3zCf6Ldq~bjjnF^I;X(5Ga zFJfXUZ38ssqFFk6u__AJ7weL&rwno_J^|~#ciHVgq7y~O*TY&D5?L%%9$rjN#{2hO zl&Zf9$RQZtjXN3$e5*jCM@mWKE@a_qxmC}4Y# zg^fgELlb&r<$*3$d>1V3z(Z5fyLiyg~xs%mCY>j`rw?HgfanF z#0Q(p*!rjLq)g2`vC;-?#wT@GIXkdhyXr_^!l1JCncfM9Zg3GZed(FHiAzHI4~-#& zZ}x^+N?HE4@*MjzxO%Ty?l)vpBtxgwlad>S&f{va5*rRR0TZE`&RLFWp6sKNWg6AK zMKu{S*%F0?WR>i@kb)NX*iE-A$;?X7PtTfhV#TY?wzR!pK5we6TsCjISbXLBEjj43 z6I_D>p5Oq1I<|YneI)&RQe_)z5?YwWRt4WMr$J^!)}%jtn7@W((c{_v)x7bkoGY{{ zdT`7a67>L~v+$azQ3>sIuCJIdF2Qb%AIbTJSqhcu5XL{To$VK8t{~8!&Ip7jjp*@s zEt6)dUaUgilWv`=0)Vu*@&%&a9K8ON>@OMLH-L9FYKK{ujq$v{Kl#Lf+wooM%E|}z zO^>y?pz<@$2O@FK*{2=L%27_mA7LAQ{%q~v7jsVP4thJkkLduu?aEV1v8edcC1C%I zUdLw;LM8~hOJjtUSg%}bU0t*-RGW@xK`Ny9;l-*;A5nO}WVR%l?0-roG^VMk$h~Q5 zzhj^z>9laq=Xm9PHwGIk=+eymlh6^~tL3dBj#Of>dUA)33pQya2z?MP z@QY`%J+2~rADar5=li61BGhtoOH&nj?G`4e{oDUh5BPr}^vl2O#OarpNiz1NdYRLk zvE3o49ujY^k1Vun_U#58R2l^rT z2{YowSohhlnyRci>Ymcml+Ok@5BR)&t%@nt6pyzt(o0l@6s?hL!C*I8RyRWZbX|x2 z?4!NP>&SV);Q1l)J9KB5MDORE$cpO+Gl;T)B7nhT$KY;@c0%Du{Ylp!32E!ty_A<9 zz4d!oE;ocl5(OWfyxu())&G!k|7Tv)MqeoM1VsDIIn2S~Dnl$oK5s+qw@)lI!NCF4 zlHO1|SNx-S;oWABFB}H*^QFor^+%pYBYz8$&yd_+B5+C*B-LdnYGb0HQgx|PAmWRe zqjfczJG1)g;0+P^R*le<2Ibl6Lk#mVfe8tO#i6@8ukj<1sOphcZ8TFgx~klp6dL@Y zQxR)t-?5myWSR{)t6p&3o`149 zqj1Sy8sqCHo!BU409J?DNaPdr^xx(Z)mA^FasBKgHe5dYaC zmt*Nm;!q2p8-B?$n>w2mql6&UG<3P`MPfL?s3a#l&E@U z>CAKFW%*Z5S#{||_DXmDSZd7Y9j0Uo^sjus+vY&qHm2{uR1}rYkz3nFzlV!%+mY|| zqclhU&)DJ5%?$sUxYJD0?CN$1Qvd2-% list = EasyExcelFactory.read(inputStream).head(Date1702.class).sheet(0).doReadSync(); + Assert.assertEquals("字符串",list.get(0).getStr()); + } + + + private List> head() { + List> list = new ArrayList>(); + List head0 = new ArrayList(); + head0.add("表头"); + list.add(head0); + return list; + } + + private List> dataList() { + List> list = new ArrayList>(); + List data = new ArrayList(); + data.add("字符串"); + data.add(new Date()); + data.add(0.56); + list.add(data); + return list; + } +} From 6b46e7a47d7fea79d7df0b8be7d246cd3326a1de Mon Sep 17 00:00:00 2001 From: Shaofeng Zhang <11811522@mail.sustech.edu.cn> Date: Sun, 18 Apr 2021 16:00:27 +0800 Subject: [PATCH 058/129] fix issue-1663. Skip fill when variable does not exit. --- .../executor/ExcelWriteFillExecutor.java | 5 ++ .../test/temp/issue1663/FillData.java | 9 ++++ .../test/temp/issue1663/FillTest.java | 47 ++++++++++++++++++ src/test/resources/issue1663/template.xlsx | Bin 0 -> 10025 bytes 4 files changed, 61 insertions(+) create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/issue1663/FillData.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/issue1663/FillTest.java create mode 100644 src/test/resources/issue1663/template.xlsx diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 5930a311..df0fe70e 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -188,6 +188,11 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { WriteSheetHolder writeSheetHolder = writeContext.writeSheetHolder(); Map fieldNameContentPropertyMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getFieldNameContentPropertyMap(); + + if (analysisCellList == null ){ + return; + } + for (AnalysisCell analysisCell : analysisCellList) { Cell cell = getOneCell(analysisCell, fillConfig); if (analysisCell.getOnlyOneVariable()) { diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/issue1663/FillData.java b/src/test/java/com/alibaba/easyexcel/test/temp/issue1663/FillData.java new file mode 100644 index 00000000..57b54107 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/issue1663/FillData.java @@ -0,0 +1,9 @@ +package com.alibaba.easyexcel.test.temp.issue1663; + +import lombok.Data; + +@Data +public class FillData { + private String name; + private double number; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/issue1663/FillTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/issue1663/FillTest.java new file mode 100644 index 00000000..ddcdf45a --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/issue1663/FillTest.java @@ -0,0 +1,47 @@ +package com.alibaba.easyexcel.test.temp.issue1663; + +import com.alibaba.easyexcel.test.demo.fill.FillData; +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.ExcelWriter; +import com.alibaba.excel.enums.WriteDirectionEnum; +import com.alibaba.excel.write.metadata.WriteSheet; +import com.alibaba.excel.write.metadata.fill.FillConfig; +import com.alibaba.excel.write.metadata.fill.FillWrapper; +import org.junit.Test; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FillTest { + @Test + public void TestFillNullPoint(){ + String templateFileName = + TestFileUtil.getPath() + "issue1663" + File.separator + "template.xlsx"; + + String fileName = TestFileUtil.getPath() + "issue1663" + File.separator + "issue1663.xlsx"; + ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build(); + WriteSheet writeSheet = EasyExcel.writerSheet().build(); + FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.VERTICAL).build(); + excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet); + + Map map = new HashMap(); + // Variable {date} does not exist in the template.xlsx, which should be ignored instead of reporting an error. + map.put("date", "2019年10月9日13:28:28"); + excelWriter.fill(map, writeSheet); + excelWriter.finish(); + } + private List data() { + List list = new ArrayList(); + for (int i = 0; i < 10; i++) { + com.alibaba.easyexcel.test.demo.fill.FillData fillData = new FillData(); + list.add(fillData); + fillData.setName("张三"); + fillData.setNumber(5.2); + } + return list; + } +} diff --git a/src/test/resources/issue1663/template.xlsx b/src/test/resources/issue1663/template.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..a968ff4151813d9eec2a251185b4f7dda603c4c5 GIT binary patch literal 10025 zcmeHtbx@qm(k}#u5FCQLFU}GO?oNq2$5SAczFJMAb>v@+8D^&+t@lV$%Dx- z!9T$NB)dX#yXS_4fUtQ20fG8=GCf;cMprA#jM!l*C>G413;!e3s`8zv(D)Qg!R`pv ziiW5ZZYy0XgwNACXKD-esGd-7S|a?T^o*Z4(KXn)#5!<#Qd6Xr?u7$UM>*5JgW99n zD(0|y7#+N;If)4zg7YkM=uAkr@CEqdZaijrI8pqblDx&jc4#3xQ6iNu&sK3owZhLB z3sP6$3C_1QGGkAF>7^4u$wKrj3c3Wr60*C^2FcAlo#S+QtYaq;#RdnT*w4s$)yt?R zw_Z^jkC31tc4k&xI3cVhMa$Q`cO(IUraHI)+0@=I$1U`GZ~7u_U>(O+1frN)_?Z=e z@THbp9tpp8*77nDf0i~Y+O6Yszjsafa8A0TAB}T>mEdY<593OQJdCUI7v*dnUuv(f zk)$hB>3diZ5!ap?V_)#@ttiLtiVic#mQl!#Z z^nkQi3`nYz88i3@W;tiQMRshMOL*RIpo{=s1@lPAz78v`h5}@L!RPPFvMlIHYZs+A z?c|i}ihIYe)8c?0flYTo)IL)(%90ByNMx$eCo`h&m=SqPdQ!5ce$q6G`kqpiUFsPM znF6cA^LlnsgdQW^=F~g}45N3OUlN`g&~IkfBku;6b(-m6x}1TAZ2P-;vml=#;OfFe zN*{7ALEKi6=VH@}h5(3VmLT%lq63~B016t8m<m=rR6)-pRqy#_9q5{1{n_ z00GqCqoBJGqoW3$R8#o?5PW_JcB*@llPvUN!XnU$=JseYx*$J9dv5L9vk@M)xDuUS zNP-}a=2%(^zF+}~vN`QTrOT$`Cio`?__G`Vv1CEidS72QHcJxKrUuqEGq;iENv^cd znFU3!z_D=jxKuhyemI>`eY4A}s5R}NK*tv)q%OjuO~Qv?EM{}v(T-%}RO2IB7oK$> z)66X^_d=R)g?coi&PM4{C0JA~nDca-gOSI-zvr!5)2VGB%i?Hm`1b>D=<&}fLL_OR zQt$iIuN4PF2gZjXb=Y$`QO-aark>q*tI_U(mxsZ8?d|@Q+uSmvlPg&q`{oXBCir{S zIBDREpKGAwRit;bkJw=W>HxVQR+84)?C&2LqlWk(9&r6<7Xt;x)z$K+bNOe2XTJzs zZ0s!@OpS~jA3Gvt;eIk$uz`MnB|ZNS+Mg^e50;9ETecZzM(tgWxg-X(GRgJm)=05N zBqC5mQw>C!On+uq$(Wf*GF~g+N(bc26P+7pF=gF&Gr3$13tP-UdXCo7yC&wP3x2T7 zZ`5jU^=fW(9aIyTRUVsphIj|>w;a!;vmS7EGYUaME`)=)MADFtDhM1Mh*pIoY@V3< zgub)uLdJFhL(*uKSl*;do&luX}`Q5HNDHWLaMdvr#4CSY2J6OUNs zj#<_kgGtlVaR&}ypV9<|iv?A4KGCqaU^yla8tWs%AXA{5fK&Bjf$_-#X$EB(#JCoq zud1${@=Q14_iip#Bbv|RYpQ)0elvsV*}gS{!|e&tY!Th1X=m)g-VpH07D9MOVP&7< zn$f`qPK-^kBOuOBzj}j`R)xhC|NR<1=!qzbQR-VLNu^h~6UjboRR+N%=avR^o9oZ` zq+7?ebYabN3;Ka3-ecUEpaz!f)ap{vYu@jrISi2K2~_2r#iiX>Lf&L9P&3?{c~GsO zR#V!K)KeC7A$G`!hb7`nz#dqcipCi9dGCe!lNWy;aNt?{&L{8zH~HW94(qSIBWp9k z3_j%&Ki~#0dems*OJiS~zMlu!^drmK`kbwM#w7-56Ec>~uT*a_MCE z-IUz}f*5lyw!A8xtpdm~;7oaM*V=g5rAA_g{}CkApGER5ZTBEeU&IHV7ot+4B4?d9 zrV*QLg7-NttD~;L2T>b}?unl}N0J|xVQJ$^TraQ6lS=bunz_PC8CjzQ4l2<&6pn#* z7p2)=FNc?-d=;o2X*VT064rIFz;&XMWODtkh!@t9wipzuHg^?oQF&(~rU`n?ms0Ia<)Q!-|Vb?UE3#5^vrj}Cl7n3cvmEtIa3hTRf zc2h#?*0bL5U@P5x@MlTyvTQiwUDY%9w35nvMKUV?D$Rt|n@AT*of;9T^_B0cL`is( zYtB)uur;qmc0xb_@~%!%PRqJQ%S6lCCCuw-rJC&xg*A4$i9JKO<-DVKWEo-nk@ZLvMfQ{U=e=>DwrqnBB=8Ym^{F`YvKXV%QewzRWmnVNQvuG75@oz~*y?uSo0V&9 zlAT|ppy(3t5EN?q=Ibk&293U!m1AJ~)a?F=&b&*KgG0`Nil48jvV)1wkK5bZYm2Sb zd~P)18xe_twSqUiI>)GCUVM3Wqo>xVjaySZ6j+fV$;Zj;&9pH~`4Jb(jiJ-Z5@i0m zUVv%4aij#Psied_lup&mErc*V>n_nitfp{XGn#LZqY*P>_W4x}n0j~~G(Bk1&3t$Y zS=n3scc&-C;;jo_5I##{J?}ex6-x4mzNKuNJ?m04t?0B@iPL@ymMzmQS0LybH)|{A0xR$rQE-ac-nNBVb*% zY{YDV{Z=c5n3Y3GSpz0VrG*b}{qRXtZs*zvPYfJ!umto&EDq+dnT_&_e`Qtj(B;SE;?6kZ$d6wKGmcL&2v5r zN7C`S?I+e*5N+kZI+^So891&Ay+3P&8}YfTA%MqakK69vit_QezU+PaBc&LP91VJ`0k)L%BbJ@BfiQK1LV*TBcHquc>(nWKHDnk7X1iWW~vQ?bU|$=|3yn#h~jayZ!n)Hpy&r zW5J!77D9CKA+2D8ASiT?URvK&epluCPwNuF_1+vTlgm5dRcG0PZUwK*NDAb|I6Dx20rT$PN{(kUc3;| zeK`B4q~RdOH%8wG4~;{;;rPG0<}}(UuGZgN3fTt0MoLsefY>k;RtETIuHB2`$zUEF~Nid_qW5RXedHrk#3gd*6ZH97KK0=vR`woV%pF?SeIT zGxBCz^t0!=lbcF-j?`Xo*ZEw*_egAxCGr8)SF*UD>12->^q}yZ_2kRhOkTwjcg3O- zIZ;7D!QsGLPLZ@vioXtOMx`G8^oCcKBARwbAU9B&lPPsYaSjiqxwY!Ua06e+%m8WS z+=?)FQ*KE0nwVUV1XePeRgbAC1}ANG0ursl=z(mqa;-e|rV21OC3o9)Pt`dsGX3bk(uYqy{`bKhS zr6I_$Ud}u{<}lXCvgZu-8C{a1&b2W6tVhieNmcNfZU}{hvf|h{adF+-**n19K_`?e zPBV9MPP$Hmc;D%KYbq9`uXFuxI)ZO2`z@u)QZvy^5&LWM<}BMpuQ z2d790`*x?sCHQ=PX3R?uBUJ?I&r?+k(7o)P=XbJrXTdf6R;}*xGiMURRf5|JEVZv0IuYpn5Htl2mT6R1O4)V_3k< z(}ex5f{NlupRh>d;;t++kQGDM&3u>jG4}$a-d`2h9Ocqh62Lr`GIm-oPZ~lOA2@M@ zXi6Y+;A`qfubmv6?O$yEouRMgu8zyZEV(8)E^qEVBs%6fIToUja}FS7n>$z)xY!7g zOhjizQ$~G5rLqq>OI=cK@wI4ao)=T7FwHzR5i)=q&*#u1RWLx{1y{GH1D#sS#T>z9 zBR6r{P8ZV1QwYi!KM0JPCsKodkvMA?_}E;$EB zH%lXjhcISR(<*9S73(gt%cnxKJtRD(EAsnPhRlv(5BiwDiuoIL1o;igbX@63-WfR{ zln|ZcU|Vik&90DME&5=Y)Rh37D(dUOx*L;J_U~b>ZJ(LWo2MNzT%}ey*~Z=-TrN0# zamaKyY;KvJZSdxCOyG7#ec3XtP&-^yG^0Io#Jwaa?sb#+8KjuNT-DUFahSa zx#jk(+$snZX0gmub0FbI)l~7GNDKt3m7?4yoD-&BIE}JI;lsUb9}WM?&RG~J?q_u- zOu_C*?_N7s_>`en>C>ks&?tde&e(Tx?Fog5^;jXkD>-6Dydoj>y=yP#jk=Rz;)oyH z5%=C_$po6pWuAKj3A@I%?iy~wCp#z{#y)cDvn2OrI=vB|H+8ux`Zulyr=C4SH6nL8 zx;>WU=4RxIsG7=(d^-8b8;**Dro~bTl2W6w%);7qVQ7~%LBm>(6=PH*58<87N z?%AQ8M_g_N!hFS0jXb-ngE>AMc%JVijS#OkJ}V`GK1XX$^()gm1aXH%ZozHq2W|IF zVG``SyvFb@`W8Te{lS_TH{n3js&dZQbO4V0{O(L3Z)G4vM~+tx)}38f7UOo)pZP;a zi7n+*L4aDGkXlz^RjL|WT7)PaMpNem25Tt|PBoNvrXRLAv z8mDFwX|e|yquyMNzKA^yX~>r6C4wHwdc8I4T@dK$=c;BWL(v#QS1Qkv(KQWfac1Td zU7kpRa+3bfF2vANVFhb68yN6j(>vt!&l+%o4Q@_T*Uko#lYg=Mvr z$>4^ei_*?GeoUwz1TR^eDet$RoEi8e76wV+yN7iKLym7njvK z30vU2Z*4z)A?PD*QKMd3r!bxv0X)kZ*8$|4mdIAmTj2x(llZ#zhdr&FFTz)_diN5# zYUgLzk`6826=TSB0qyS> zHe51?v0St@W9aL$sr9t26Xk&fL-hLN=DiXJSmRHL&U+2I5=P&>^{MpY+8_?OFS`0f zc8?_K@NDybT$U#(X!d&x@u?n~bk3f*RdRi-^t?tHZ)jU_8yBa@J^4NS)wXyHe_%k1 z0pVrlMu#3{V(2}&r0NfUr?SYo3-OyW6vJ#r5IH$_cDy15(qw$UM`va13E>(XTw$q3y5xB-hUr@-WiT+ButOizvoXT#ci$ zM!yVst6S%|URX{yhYjp=2juzV7X}ie)ML5Kr1&PLM2a+%B2c+rUvRd9**JnG$0L)S1Qfpk zT*rvwIDwufu~gAF&LUqvduhyGlc?59(#RXzeijOPX7=eLLINU@^GM-q{npk%qHwkt zDCJh@qHb&@cH>-5?T(&~@$dlU0QmB>{sjngS^3~d-9>?5RuUlYiLHt#s(a{$O5lk` z-y}eyx~bWcOA0%_Dz+;{7>#2$9#d?FA$A=J528X>xHc7X-ChYgVtWmMT}tO!)qlpN znMB@&@lFd@alu!W=^ze@4+A<9vYsuPzCJr!Vh~nPzTD)w8TO2WsoENQwtuYhLo=>^+_00T)A$MBp!^qAHK5HgF^v#! z{NYd1#8zH}Ct^%iKAm>xOB(>6dW(Eutaw#TSSPNUMo8DkQel?z(xx{h-v*BiSu!<3 zrgbcEwYi9z4&8aaqA>;8#$B^7ub%g_2lHe_eV8;14$@})vt5pOg$qE<3k5sw2(c=IQrY!#F_a``8#9n=$Ly26NwJv3sYw}p8MPI|KkpqA1 z$}}V#w~pvrfC@twpP{^wMGd1Gz1Ccdcj1sNG~Nbh%Oaw$PK0_h$D8Xtp?NDMNddPEj0jZ=KkOkKc<) zfmRW2C{Z9S46Tqnz8hsTc>_qxK$VrA>2u8uQz#xJLKl-XId&(Pb!YaY-6NVNF6urO zKKwLi84!aA040WoV){$Ac8%=BjXh zZnMn#epLAvB1$qcC*2Arv=mQgmy?j*HMmyX<<=Kh>w_XHhA7VgF~cQeBr?S{eT5C| z4irY2FdBJSPt7Qtql@f8a4}lG*&@y-7vuel_g&|!Ab4^ZHyzFltF_*dxSQ@4nI!bf zABQ74d>*ObwT$Is4v1h2Nkw-Da2tOlodgJStnfGK4<}hB8%d7#*8~8`W1m9Av&YR& zR~n17w9AN&$rJz)w9Ltt`;u1k){@MSEvUL*nvur)rcEGhm$=!s1H!mtVPg>?d1;m* zEZ@elM~A^#h^IJTkVcQ$@4XyYfnYvvXIal2DFyo##9Hh z!%!Yl7$H~5+KQ)gryN!oi_}f!3x0770g_kMMg|NS1DR{00In`jN6d0P=WXRJycJ^B zj`UX*@2l31R+9)x4o}NIrE_}+rfnDQU&@{;BJ9*1tZfgYEz?}-15 zA$t?PX%~WH$2supp}GgofH;`y*&7)uIog|9oBRwVl_LesJDE{MFM^f?hguR3L}^78 zv4b*6xY{N%d!AUVn~IT=t{*Dk1UX;bt+l%}N~;g2gm(=Q1((4I^K5XPfI9W=uTEga zFx`59Y;N_jZHzqpTxh^jqvMJ~>!YcG8hN3e6S0LM7e<6yJudZG#1#NiOu=NN*S$H0 z7%bbyz^)#&5?3aj*AIJJ^nh{OGzGiu=NO9_lVA5o?v^J{MK_{q4>VkVRvCU*C=c&+ z`~|?tT`q8O0Oi-p9*PM1HZ~SN(|j?~(!UCn_oRk4Ta!f$8ML9{ixPsRdz_!g5r!#9 zB{Qy%n)|=jj7AhM^scNe#BJ=(NS+{1A(Tp`$|_0;Or|2$((m-%d>`he{KD3qGJz;{ z4Ha2dv{!6YesCwf$1CV-PifWs;w^=p6B3~VhLyld0jSP^NTX3Yy|S&|0@9N@jz`ue zE)qc$uA}2FBqvR5;#=XKFx&tNDpIUl&5^nuL1|({bOj+J*--MEshp$tc_OS^S@qxA zq}6qcJvfn#<7WcgIN`(Q-C{P`KlYHnz)rJ0P!Twi`#u`0O;dLBs@>}?!qV_o@(QyD zWTge~v+7kw$CoStfN zj;Z$zp@*x843jcb_|hF1vN9j4J+ZNTTD5PVJZz(X&bNW{X%IU0MwX8&H6EPKP50pc zmca%=`iq9~fwDAqM5>D!wdV+2E#7RAb-_ZLbz~yjmo@bAO_sSIrNW3+J7{SZQ~*pg zz(u88ZKf@I8aCoDl4!FOL^k<5DfkQ6^f|XEeDicwUG$eIX`X~~du`hR-MD+Ae-jw6 z$rC@vND-susW{3S!c7}z2HJToFObCz6#c-(Z$KWv(QGYmJ#Zq{lSL#i%hSC?7wXXn zYsVSXbY){xwD;vJZ_0b&5jOhu*D)DRmeE-60zBW(w4$Dg!oqTm*gNqJ9=S+`l$07X zAd6}SB`bw5Y-qOH0aAK3<%q*6vxlz)#>clh+G9W(HG>i_11WR&?kQM%yVeuk_<%YR z_9qO*F8@20|H@td6PzTMhqyOj7$?BR3q0@>d~$!0{e74JM7KF^@L%WmE+E;9Vctv_ zA*Px($a4M^Dv;M3Rf9Ekr_*P-{cU~lS8Ev#{}jQCOpxeJ=d0-=rl%9GCM03{^4s=0 z>}9Oq?A*OvVMQ&q^fZn}+kBxz_V29kgG-G*i#UzPp<{`|ns0i40B!)C6Umm}$4Tx8 zo2U)Q?<{SaXynMPxfXZoAom%k?y5eA@6|`zWj|g0(OSneNY#sz<>S1486H$H2Mbu@ z>T{>);CS5!YkVLPDyS3Urj8XHqN44P`+Se`rWbgi#@f;E1vqo1l75;7#BK57REp@s z=*<_6O_bq~X5NX=8>38K?_o|#KHX>@4RHRUtR#(N#3C+0HZ6hNbr%%%VFaZ zpkxZ?bbG>47ofIikVc;4D>yQuV)hejcX(rtIOg{u&R;9>(9gXa3apxPRt>_?JHFzq9?T zo8~b@kDEe%b4P=>_g_l?-6Has{c&T%Z+0ZGGx^Q_SDV9sTQr#CU*loX2GIYi=RYj> zpH1>7O8&%ub6t-o`q;-kDEfuc$G@}vhsS#?=W&$tTh0-<^7BtI&tnO|N4d7&5{kiH zIS&&4%DnwIu>M?o4;UaY>%S{gf9{aSwW;445B|>fyHfRd%8vt}-vasxe(L=@Z2xW2 z4=otK#)E|ee_8l}`LBkIKWF~9CF6njm(?o%gZFoX#^dQfF3$g!vJZCOVA%dPgP&4< kmg@h{rOd+rqm-XDV0menhbRVoNnk+4f#>W?_VDe00L%|cjQ{`u literal 0 HcmV?d00001 From b4545debd1460ac10c162dc1477b730d846a6e91 Mon Sep 17 00:00:00 2001 From: smireg <402809775@qq.com> Date: Sun, 18 Apr 2021 18:24:05 +0800 Subject: [PATCH 059/129] bugfix1765 --- .../property/ExcelWriteHeadProperty.java | 4 +- .../test/demo/Test1765/Data1765.xlsx | Bin 0 -> 3687 bytes .../test/demo/Test1765/Issue1765.java | 55 ++++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 src/test/java/com/alibaba/easyexcel/test/demo/Test1765/Data1765.xlsx create mode 100644 src/test/java/com/alibaba/easyexcel/test/demo/Test1765/Issue1765.java diff --git a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java index 979a7750..aa4893e5 100644 --- a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java +++ b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java @@ -154,11 +154,11 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty { continue; } alreadyRangeSet.add(i + "-" + j); - String headName = headNameList.get(j); + String headName = headNameList.get(j) == null ? "" : headNameList.get(j); int lastCol = i; int lastRow = j; for (int k = i + 1; k < headList.size(); k++) { - if (headList.get(k).getHeadNameList().get(j).equals(headName)) { + if ((headList.get(k).getHeadNameList().get(j) == null ? "" : headList.get(k).getHeadNameList().get(j)).equals(headName)) { alreadyRangeSet.add(k + "-" + j); lastCol = k; } else { diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/Test1765/Data1765.xlsx b/src/test/java/com/alibaba/easyexcel/test/demo/Test1765/Data1765.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..3377bb760f7a27ff706a43fda2d77dd6dd323ab7 GIT binary patch literal 3687 zcmaJ^2{@GP8XoHyd)cGx#NW@z7Lx2EYeI~&jb&^z43cfEjmVm{NMQ(3$iDuA(jdQ` zi0n&6b|cA|sdIjgbL#o7Z@!u9dY^Zm=YH?+e(%>vmx7WNKtn?V_*>#SLrZ(<(Nm%OAa(_N6 z6m$UWyQLDT(|A=PD>u}qKP(6SZg+(H_9f-wmCJ0nMUQC+wLmMnIw%K}he*af%@G%1 zrwE7C4cCo?lBZ%=UX3nY0477{twbvXx3Ti>0nauJsWYVqd%50dS5y16yiejx7v1mn z3$#6x5nU1+uh9&ed%ls%=w?l!Y4N5h9nko>eD{{88?W@RzTQ%^1DriN?!EXRWyf^k z4e2@yaCznu^2%_04h2Y&^;?b=&C*NWksxv-T_DZV82`o@V&^*K0D#div0)*OuvAAP zyd4nU)+T-)4qi7UZo9ixUh71(fSJFgycrgk+cYv|3svWBXD{5OxDk+KP7r>Py}EM~ zcp=$1iq>--=IG>jecQguvkI!N#uC{2IHZYGFHOOQ9XeZ?rWjw9brU>BG$0=fgf~B)fsFBtevxEl^|M50SsVS!_XA_Pb73a=T=LMlIDq{>wNHW0xp4v z6RubERB44Wy37?ss9zm?@+tjpdUh4s4VKW&Cd;jDPPbD${fQRyT*fSHcw@1Q^P)H9iNm~yO67c$Q zI9ej`8ehT=m{G`Tf96D)Jiai|fF35Ar6KBv`Vh0Fg^VQsOs@Gglj^UU4N?vq1u6A) ziR5@pZ|}>L_`N*E4g;jT3xwa!F47_yIA_+~wMLn+95XRn*JY9_CWNeM+l&C~cTX#f zq-ooY$iF4?aKN5u7e|L0KfCn$l|`$j+DYy>~ark#4d4M!>h;aTSV!1WM z``2VTakL>A66HYZ$UR~FN*kD2%Q|ni=@FLALTyYlnM&0Y$M&i|A;!IImp|%OP(Xj3 znGrt+KG2CVsjymG+40L_tBt<8xvCCE3o4uboS!N3W)r`~-IlXb&~OH+RJSpxqC`o1 zV>M$C57=G@MxOSZKPV=Sg7RH1dp0COXX@S-v~6?q^aXxv%}66-f5ua}Mgp|ycWNzT zXR#(I(>i$-336dF?E$zQzzj^V74$#--QE0t%0-NAUcR$?x~Z)7!T*1LrS+7L-SXssp0Xj+X8=L z+ueeFmAzbRF)FSIl^>)?u&FGiB9fw%c>fwhRw9PC-6Xx>wkQYtYu+elgp(HuM&%e) z5-|W@!h&f6s-wyNVEc*B9G`I2I@u$nGY_UBstUk#+TnE!7jg5x(y3 zRZCu#eblVGz}w$9#!|fL>9N>)Ctb2E7gRvo+5mjEUBfr?%|p(}IByWn;ul}a?TGwf zaSL77;*85s$rCK8N2kwUbOc+1oH{Q|4#tnlnQQmYS@(j9Xvs>nYv*qAYQ4~hV7IMw zGi5S;pi(Co(^>oPnw->SlAeGqT}(`B;5Eh6poRCXt8dQ*tJr1Qq`ERsi{qpAnrL9|6n{Pbxz4s6dYg1qy z9dQNS=B{OW(#VL@dLmxBuOzJMw~jyW6=FL|i_Bc`fsdc6#u@jyc7D0q&;oXZRYs1^ zctIkbBh}abZoE_h>$a;apVKc!|JZ&+R@Xieh)jo2{f_NSKPlsjM7i1_k**}7$Hu7| zw1Sy6cOdU^50xt^XjECBaz_lDzSlD0BN96}66dJb>0n+u!~Q;h;V&IFn|CQ&TOTeS zxa_V3lxf>>gk$WoFWZ!sdD=dka@hCwVe0(4o};KS>TdTwstY*OlP8mGT)y1HZPiAm zju?eZV0oPX@Z*zV@V$%QS%(%XEydD#oKNWgX z>BxxKu027>R^&TTT3m;1d|dr2c#`u@8GhN*UGCJt8+`C&g&$fId`6b1`BFUZ2fhOD zSZb)OJYPOK1t!HcFRc)4a_~b_r8zCv=7{}U{ZsZNPcM_G?@IJCmk*+Q zgFO3ioVf@|SkI@SeE{qaPq+Y=?%rba7?aSzog~Pe&3Q424qS z0I_rF-Oj!9>#9F`ZQ@gsX()cY8Ki^ z)35Ki%oLvTh1Nm9(8^_B{Y+DI(OFp=|G#z>*Dv+z1fCH0yG(n9b9z8yl6GqzpsGDM zWco)|1^Et}UeDT~u&;a!;)MhkT}?AX6g5Y_Rv)3jV<(Y(!+Da6>M>GIm)6>fO~h%3 zx5%Gc1zeN~{H9_`o-TNf+xEdtL;~53c34wl-T@<*b+4z)b}*R2cW`DT^@W zsthK3-hNrV5yLX~!5v7T#Oh|LlGAY#e0e0mKc27eNW!SCU%p zPRKX?5Iq|UnRo!v&02925Ebxa@7KmU`@l5UwS^A!gnWOFRgpT~MI0OX_Q9JPu2u=L zwrUMF)3Mw~15mlrJHx}PW+<^rBav{X+K8J6sRIJTt$)T0c+N4FrH(gSy)65H7F)9> z5l4A(==28hg~CviWQUBL6>xYaIO>Q=XM+EZBPWF8iAU`m$uJ)V5Am=5k9|Hq!BP7} za(#!9P9*qo4|qKLsBs`!tiy1oIFkJz!*x9U=;lpw7l%=11}`RPp#cM@d1_jKg>b`lpEh YQ4k|tDk6yh01)v~AuiKNdeX0d0kp*88vp> head() { + List> list = new ArrayList>(); + List head0 = new ArrayList(); + List head1 = new ArrayList(); + List head2 = new ArrayList(); + List head3 = new ArrayList(); + head0.add("表头"); + head1.add("日期"); + head2.add(null); + head3.add("数字"); + list.add(head0); + list.add(head1); + list.add(head2); + list.add(head3); + + return list; + } + + private List> dataList() { + List> list = new ArrayList>(); + for (int i = 0; i < 5; i++) { + List data = new ArrayList(); + data.add("字符串" + i); + data.add(new Date()); + data.add(i * 2); + data.add(i * 3); + list.add(data); + } + return list; + } +} From 79453b6c70e5ef9354131c7c2ea4da868733279b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=84=A6=E6=9D=BE?= Date: Mon, 19 Apr 2021 14:00:11 +0800 Subject: [PATCH 060/129] Update import package, remove import * --- .../excel/write/executor/ExcelWriteAddExecutor.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 1168bde3..fe83cc22 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -17,7 +17,12 @@ import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import java.lang.reflect.Field; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; /** * Add the data into excel From 74562ee5c9e1e8d0906b400467f8bd8a0906c9f8 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Thu, 22 Apr 2021 21:49:39 +0800 Subject: [PATCH 061/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E5=88=86=E5=BC=80celldata?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/excel/EasyExcelFactory.java | 139 ---------- .../java/com/alibaba/excel/ExcelReader.java | 181 +------------ .../java/com/alibaba/excel/ExcelWriter.java | 238 +----------------- .../v03/handlers/BlankRecordHandler.java | 2 +- .../v03/handlers/BoolErrRecordHandler.java | 2 +- .../v03/handlers/DummyRecordHandler.java | 2 +- .../v03/handlers/FormulaRecordHandler.java | 26 +- .../v03/handlers/LabelRecordHandler.java | 2 +- .../v03/handlers/LabelSstRecordHandler.java | 2 +- .../v03/handlers/NumberRecordHandler.java | 12 +- .../v03/handlers/RkRecordHandler.java | 2 +- .../v03/handlers/StringRecordHandler.java | 2 +- .../handlers/AbstractCellValueTagHandler.java | 2 +- .../v07/handlers/CellFormulaTagHandler.java | 10 +- .../CellInlineStringValueTagHandler.java | 6 +- .../analysis/v07/handlers/CellTagHandler.java | 11 +- .../v07/handlers/CellValueTagHandler.java | 2 +- .../excel/context/AnalysisContext.java | 10 - .../excel/context/AnalysisContextImpl.java | 26 +- .../excel/context/WriteContextImpl.java | 2 +- .../excel/converters/AutoConverter.java | 27 -- .../alibaba/excel/converters/Converter.java | 31 +-- .../converters/ReadConverterContext.java | 30 +++ .../converters/WriteConverterContext.java | 31 +++ .../BigDecimalBooleanConverter.java | 11 +- .../bigdecimal/BigDecimalNumberConverter.java | 7 +- .../bigdecimal/BigDecimalStringConverter.java | 7 +- .../BooleanBooleanConverter.java | 9 +- .../BooleanNumberConverter.java | 11 +- .../BooleanStringConverter.java | 9 +- .../BoxingByteArrayImageConverter.java | 26 +- .../bytearray/ByteArrayImageConverter.java | 28 +-- .../byteconverter/ByteBooleanConverter.java | 11 +- .../byteconverter/ByteNumberConverter.java | 14 +- .../byteconverter/ByteStringConverter.java | 7 +- .../converters/date/DateDateConverter.java | 24 +- .../converters/date/DateNumberConverter.java | 15 +- .../converters/date/DateStringConverter.java | 11 +- .../DoubleBooleanConverter.java | 11 +- .../DoubleNumberConverter.java | 14 +- .../DoubleStringConverter.java | 7 +- .../converters/file/FileImageConverter.java | 25 +- .../floatconverter/FloatBooleanConverter.java | 11 +- .../floatconverter/FloatNumberConverter.java | 12 +- .../floatconverter/FloatStringConverter.java | 7 +- .../InputStreamImageConverter.java | 26 +- .../integer/IntegerBooleanConverter.java | 11 +- .../integer/IntegerNumberConverter.java | 12 +- .../integer/IntegerStringConverter.java | 7 +- .../longconverter/LongBooleanConverter.java | 11 +- .../longconverter/LongNumberConverter.java | 12 +- .../longconverter/LongStringConverter.java | 7 +- .../shortconverter/ShortBooleanConverter.java | 11 +- .../shortconverter/ShortNumberConverter.java | 14 +- .../shortconverter/ShortStringConverter.java | 7 +- .../string/StringBooleanConverter.java | 9 +- .../string/StringErrorConverter.java | 9 +- .../string/StringImageConverter.java | 26 +- .../string/StringNumberConverter.java | 22 +- .../string/StringStringConverter.java | 9 +- .../converters/url/UrlImageConverter.java | 20 +- .../alibaba/excel/enums/CellDataTypeEnum.java | 6 +- .../AbstractIgnoreExceptionReadListener.java | 8 +- .../excel/event/AnalysisEventListener.java | 4 +- .../com/alibaba/excel/event/WriteHandler.java | 38 --- .../exception/ExcelDataConvertException.java | 4 +- .../alibaba/excel/metadata/BaseRowModel.java | 40 --- .../excel/metadata/BasicParameter.java | 63 +---- .../com/alibaba/excel/metadata/CellData.java | 193 -------------- .../alibaba/excel/metadata/HyperlinkData.java | 10 - .../alibaba/excel/metadata/ReadCellData.java | 13 - .../com/alibaba/excel/metadata/Sheet.java | 162 ------------ .../com/alibaba/excel/metadata/Table.java | 62 ----- .../alibaba/excel/metadata/TableStyle.java | 65 ----- .../alibaba/excel/metadata/WriteCellData.java | 42 ---- .../alibaba/excel/metadata/data/CellData.java | 76 ++++++ .../metadata/{ => data}/ClientAnchorData.java | 40 +-- .../metadata/{ => data}/CommentData.java | 4 +- .../excel/metadata/data/CoordinateData.java | 28 +++ .../DataFormatData.java} | 5 +- .../metadata/{ => data}/FormulaData.java | 2 +- .../excel/metadata/data/HyperlinkData.java | 53 ++++ .../excel/metadata/{ => data}/ImageData.java | 2 +- .../excel/metadata/data/ReadCellData.java | 111 ++++++++ .../{ => data}/RichTextStringData.java | 2 +- .../excel/metadata/data/WriteCellData.java | 101 ++++++++ .../excel/parameter/AnalysisParam.java | 58 ----- .../excel/parameter/GenerateParam.java | 71 ------ .../listener/ModelBuildEventListener.java | 38 ++- .../excel/read/listener/ReadListener.java | 24 +- .../read/metadata/ReadBasicParameter.java | 21 +- .../metadata/holder/AbstractReadHolder.java | 4 +- .../read/metadata/holder/ReadHolder.java | 2 +- .../read/metadata/holder/ReadSheetHolder.java | 90 +------ .../DefaultAnalysisEventProcessor.java | 2 +- .../com/alibaba/excel/util/ClassUtils.java | 3 - .../alibaba/excel/util/ConverterUtils.java | 40 +-- .../com/alibaba/excel/util/FileTypeUtils.java | 46 ++++ .../java/com/alibaba/excel/util/MapUtils.java | 40 ++- .../com/alibaba/excel/util/NumberUtils.java | 16 +- .../com/alibaba/excel/util/WorkBookUtil.java | 25 +- .../alibaba/excel/util/WriteHandlerUtils.java | 2 +- .../executor/AbstractExcelWriteExecutor.java | 2 +- .../write/executor/ExcelWriteAddExecutor.java | 2 +- .../executor/ExcelWriteFillExecutor.java | 2 +- .../handler/AbstractCellWriteHandler.java | 2 +- .../excel/write/handler/CellWriteHandler.java | 2 +- .../impl/FillDataFormatCellWriteHandler.java | 2 +- .../write/merge/AbstractMergeStrategy.java | 2 +- .../write/metadata/WriteBasicParameter.java | 76 +----- .../excel/write/metadata/WriteSheet.java | 3 +- .../excel/write/metadata/WriteTable.java | 1 - .../excel/write/metadata/WriteWorkbook.java | 107 +------- .../metadata/holder/AbstractWriteHolder.java | 1 - .../metadata/holder/WriteWorkbookHolder.java | 7 +- .../write/metadata/style/WriteCellStyle.java | 7 +- .../style/AbstractCellStyleStrategy.java | 2 +- .../AbstractColumnWidthStyleStrategy.java | 7 +- .../AbstractHeadColumnWidthStyleStrategy.java | 2 +- .../LongestMatchColumnWidthStyleStrategy.java | 2 +- .../test/core/celldata/CellDataData.java | 3 +- .../test/core/celldata/CellDataDataTest.java | 7 +- .../core/compatibility/CompatibilityData.java | 1 - .../compatibility/CompatibilityDataTest.java | 3 - .../CompatibilityParameterDataTest.java | 1 - .../compatibility/CompatibilityReadData.java | 2 - .../test/core/converter/ConverterData.java | 2 +- .../core/converter/ConverterDataTest.java | 2 +- .../test/core/handler/WriteHandler.java | 2 +- .../read/CellDataDemoHeadDataListener.java | 2 - .../test/demo/read/CellDataReadDemoData.java | 2 +- .../read/CustomStringStringConverter.java | 2 +- .../demo/write/CustomCellWriteHandler.java | 3 +- .../write/CustomStringStringConverter.java | 2 +- .../easyexcel/test/temp/LockDataListener.java | 2 - .../test/temp/dataformat/DataFormatData.java | 2 +- .../easyexcel/test/temp/poi/TestCell.java | 2 +- .../easyexcel/test/temp/read/CommentTest.java | 2 +- .../easyexcel/test/temp/read/HDListener.java | 1 - .../test/temp/simple/WriteCellHandler.java | 3 +- 140 files changed, 937 insertions(+), 2242 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/converters/ReadConverterContext.java create mode 100644 src/main/java/com/alibaba/excel/converters/WriteConverterContext.java delete mode 100644 src/main/java/com/alibaba/excel/event/WriteHandler.java delete mode 100644 src/main/java/com/alibaba/excel/metadata/BaseRowModel.java delete mode 100644 src/main/java/com/alibaba/excel/metadata/CellData.java delete mode 100644 src/main/java/com/alibaba/excel/metadata/HyperlinkData.java delete mode 100644 src/main/java/com/alibaba/excel/metadata/ReadCellData.java delete mode 100644 src/main/java/com/alibaba/excel/metadata/Sheet.java delete mode 100644 src/main/java/com/alibaba/excel/metadata/Table.java delete mode 100644 src/main/java/com/alibaba/excel/metadata/TableStyle.java delete mode 100644 src/main/java/com/alibaba/excel/metadata/WriteCellData.java create mode 100644 src/main/java/com/alibaba/excel/metadata/data/CellData.java rename src/main/java/com/alibaba/excel/metadata/{ => data}/ClientAnchorData.java (84%) rename src/main/java/com/alibaba/excel/metadata/{ => data}/CommentData.java (88%) create mode 100644 src/main/java/com/alibaba/excel/metadata/data/CoordinateData.java rename src/main/java/com/alibaba/excel/metadata/{DataFormat.java => data/DataFormatData.java} (72%) rename src/main/java/com/alibaba/excel/metadata/{ => data}/FormulaData.java (80%) create mode 100644 src/main/java/com/alibaba/excel/metadata/data/HyperlinkData.java rename src/main/java/com/alibaba/excel/metadata/{ => data}/ImageData.java (95%) create mode 100644 src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java rename src/main/java/com/alibaba/excel/metadata/{ => data}/RichTextStringData.java (97%) create mode 100644 src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java delete mode 100644 src/main/java/com/alibaba/excel/parameter/AnalysisParam.java delete mode 100644 src/main/java/com/alibaba/excel/parameter/GenerateParam.java create mode 100644 src/main/java/com/alibaba/excel/util/FileTypeUtils.java diff --git a/src/main/java/com/alibaba/excel/EasyExcelFactory.java b/src/main/java/com/alibaba/excel/EasyExcelFactory.java index a4924973..ef9b3ac3 100644 --- a/src/main/java/com/alibaba/excel/EasyExcelFactory.java +++ b/src/main/java/com/alibaba/excel/EasyExcelFactory.java @@ -3,17 +3,10 @@ package com.alibaba.excel; import java.io.File; import java.io.InputStream; import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import com.alibaba.excel.context.AnalysisContext; -import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.event.WriteHandler; -import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.read.builder.ExcelReaderBuilder; import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder; import com.alibaba.excel.read.listener.ReadListener; -import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.write.builder.ExcelWriterBuilder; import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder; import com.alibaba.excel.write.builder.ExcelWriterTableBuilder; @@ -39,138 +32,6 @@ import com.alibaba.excel.write.builder.ExcelWriterTableBuilder; */ public class EasyExcelFactory { - /** - * Quickly read small files,no more than 10,000 lines. - * - * @param in - * the POI filesystem that contains the Workbook stream. - * @param sheet - * read sheet. - * @return analysis result. - * @deprecated please use 'EasyExcel.read(in).sheet(sheetNo).doReadSync();' - */ - @Deprecated - public static List read(InputStream in, Sheet sheet) { - final List rows = new ArrayList(); - new ExcelReader(in, null, new AnalysisEventListener() { - @Override - public void invoke(Object object, AnalysisContext context) { - rows.add(object); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) {} - }, false).read(sheet); - return rows; - } - - /** - * Parsing large file - * - * @param in - * the POI filesystem that contains the Workbook stream. - * @param sheet - * read sheet. - * @param listener - * Callback method after each row is parsed. - * @deprecated please use 'EasyExcel.read(in,head,listener).sheet(sheetNo).doRead();' - */ - @Deprecated - public static void readBySax(InputStream in, Sheet sheet, AnalysisEventListener listener) { - new ExcelReader(in, null, listener).read(sheet); - } - - /** - * Get ExcelReader. - * - * @param in - * the POI filesystem that contains the Workbook stream. - * @param listener - * Callback method after each row is parsed. - * @return ExcelReader. - * @deprecated please use {@link EasyExcel#read()} build 'ExcelReader' - */ - @Deprecated - public static ExcelReader getReader(InputStream in, AnalysisEventListener listener) { - return new ExcelReader(in, null, listener); - } - - /** - * Get ExcelWriter - * - * @param outputStream - * the java OutputStream you wish to write the value to. - * @return new ExcelWriter. - * @deprecated please use {@link EasyExcel#write()} - */ - @Deprecated - public static ExcelWriter getWriter(OutputStream outputStream) { - return write().file(outputStream).autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build(); - } - - /** - * Get ExcelWriter - * - * @param outputStream - * the java OutputStream you wish to write the value to. - * @param typeEnum - * 03 or 07 - * @param needHead - * Do you need to write the header to the file? - * @return new ExcelWriter - * @deprecated please use {@link EasyExcel#write()} - */ - @Deprecated - public static ExcelWriter getWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { - return write().file(outputStream).excelType(typeEnum).needHead(needHead).autoCloseStream(Boolean.FALSE) - .convertAllFiled(Boolean.FALSE).build(); - } - - /** - * Get ExcelWriter with a template file - * - * @param temp - * Append value after a POI file , Can be null(the template POI filesystem that contains the Workbook - * stream) - * @param outputStream - * the java OutputStream you wish to write the value to - * @param typeEnum - * 03 or 07 - * @param needHead - * Whether a write header is required - * @return new ExcelWriter - * @deprecated please use {@link EasyExcel#write()} - */ - @Deprecated - public static ExcelWriter getWriterWithTemp(InputStream temp, OutputStream outputStream, ExcelTypeEnum typeEnum, - boolean needHead) { - return write().withTemplate(temp).file(outputStream).excelType(typeEnum).needHead(needHead) - .autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build(); - } - - /** - * Get ExcelWriter with a template file - * - * @param temp - * Append value after a POI file , Can be null(the template POI filesystem that contains the Workbook - * stream) - * @param outputStream - * the java OutputStream you wish to write the value to - * @param typeEnum - * 03 or 07 - * @param needHead - * Whether a write header is required - * @param handler - * User-defined callback - * @return new ExcelWriter - * @deprecated please use {@link EasyExcel#write()} - */ - @Deprecated - public static ExcelWriter getWriterWithTempAndHandler(InputStream temp, OutputStream outputStream, - ExcelTypeEnum typeEnum, boolean needHead, WriteHandler handler) { - return write().withTemplate(temp).file(outputStream).excelType(typeEnum).needHead(needHead) - .registerWriteHandler(handler).autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build(); - } /** * Build excel the write diff --git a/src/main/java/com/alibaba/excel/ExcelReader.java b/src/main/java/com/alibaba/excel/ExcelReader.java index 7af49eb6..a1a9c50d 100644 --- a/src/main/java/com/alibaba/excel/ExcelReader.java +++ b/src/main/java/com/alibaba/excel/ExcelReader.java @@ -1,25 +1,17 @@ package com.alibaba.excel; -import java.io.InputStream; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alibaba.excel.analysis.ExcelAnalyser; import com.alibaba.excel.analysis.ExcelAnalyserImpl; import com.alibaba.excel.analysis.ExcelReadExecutor; -import com.alibaba.excel.cache.MapCache; import com.alibaba.excel.context.AnalysisContext; -import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.parameter.AnalysisParam; -import com.alibaba.excel.read.listener.ReadListener; import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.read.metadata.ReadWorkbook; -import com.alibaba.excel.support.ExcelTypeEnum; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Excel readers are all read in event mode. @@ -34,113 +26,6 @@ public class ExcelReader { */ private ExcelAnalyser excelAnalyser; - /** - * Create new reader - * - * @param in - * the POI filesystem that contains the Workbook stream - * @param excelTypeEnum - * 03 or 07 - * @param customContent - * {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext - * @param eventListener - * Callback method after each row is parsed. - * @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader' - */ - @Deprecated - public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent, - AnalysisEventListener eventListener) { - this(in, excelTypeEnum, customContent, eventListener, true); - } - - /** - * Create new reader - * - * @param in - * the POI filesystem that contains the Workbook stream - * @param customContent - * {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext - * @param eventListener - * Callback method after each row is parsed - * @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader' - */ - @Deprecated - public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener) { - this(in, customContent, eventListener, true); - } - - /** - * Create new reader - * - * @param param - * old param Deprecated - * @param eventListener - * Callback method after each row is parsed. - * @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader' - */ - @Deprecated - public ExcelReader(AnalysisParam param, AnalysisEventListener eventListener) { - this(param.getIn(), param.getExcelTypeEnum(), param.getCustomContent(), eventListener, true); - } - - /** - * Create new reader - * - * @param in - * @param customContent - * {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext - * @param eventListener - * @param trim - * The content of the form is empty and needs to be empty. The purpose is to be fault-tolerant, because - * there are often table contents with spaces that can not be converted into custom types. For example: - * '1234 ' contain a space cannot be converted to int. - * @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader' - */ - @Deprecated - public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener, boolean trim) { - this(in, null, customContent, eventListener, trim); - } - - /** - * Create new reader - * - * @param in - * the POI filesystem that contains the Workbook stream - * @param excelTypeEnum - * 03 or 07 - * @param customContent - * {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext - * @param eventListener - * Callback method after each row is parsed. - * @param trim - * The content of the form is empty and needs to be empty. The purpose is to be fault-tolerant, because - * there are often table contents with spaces that can not be converted into custom types. For example: - * '1234 ' contain a space cannot be converted to int. - * @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader' - */ - @Deprecated - public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent, - AnalysisEventListener eventListener, boolean trim) { - ReadWorkbook readWorkbook = new ReadWorkbook(); - readWorkbook.setInputStream(in); - readWorkbook.setExcelType(excelTypeEnum); - readWorkbook.setCustomObject(customContent); - if (eventListener != null) { - List customReadListenerList = new ArrayList(); - customReadListenerList.add(eventListener); - readWorkbook.setCustomReadListenerList(customReadListenerList); - } - readWorkbook.setAutoTrim(trim); - readWorkbook.setAutoCloseStream(Boolean.FALSE); - readWorkbook.setMandatoryUseInputStream(Boolean.TRUE); - readWorkbook.setReadCache(new MapCache()); - readWorkbook.setConvertAllFiled(Boolean.FALSE); - readWorkbook.setDefaultReturnMap(Boolean.FALSE); - // The previous logic was that Article 0 started reading - readWorkbook.setHeadRowNumber(0); - excelAnalyser = new ExcelAnalyserImpl(readWorkbook); - } - public ExcelReader(ReadWorkbook readWorkbook) { excelAnalyser = new ExcelAnalyserImpl(readWorkbook); } @@ -183,44 +68,6 @@ public class ExcelReader { return this; } - /** - * Parse the specified sheet,SheetNo start from 1 - * - * @param sheet - * Read sheet - * @deprecated please us {@link #read(ReadSheet...)} - */ - @Deprecated - public void read(Sheet sheet) { - ReadSheet readSheet = null; - if (sheet != null) { - readSheet = new ReadSheet(); - readSheet.setSheetNo(sheet.getSheetNo() - 1); - readSheet.setSheetName(sheet.getSheetName()); - readSheet.setClazz(sheet.getClazz()); - readSheet.setHead(sheet.getHead()); - readSheet.setHeadRowNumber(sheet.getHeadLineMun()); - } - read(readSheet); - } - - /** - * Parse the specified sheet - * - * @param sheet - * Read sheet - * @param clazz - * object parsed into each row of value - * - * @deprecated Set the class in the sheet before read - */ - @Deprecated - public void read(Sheet sheet, Class clazz) { - if (sheet != null) { - sheet.setClazz(clazz); - } - read(sheet); - } /** * Context for the entire execution process @@ -240,28 +87,6 @@ public class ExcelReader { return excelAnalyser.excelExecutor(); } - /** - * Parse the workBook get all sheets - * - * @return workBook all sheets - * - * @deprecated please use {@link #excelExecutor()} - */ - @Deprecated - public List getSheets() { - List sheetList = excelExecutor().sheetList(); - List sheets = new ArrayList(); - if (sheetList == null || sheetList.isEmpty()) { - return sheets; - } - for (ReadSheet readSheet : sheetList) { - Sheet sheet = new Sheet(readSheet.getSheetNo() + 1); - sheet.setSheetName(readSheet.getSheetName()); - sheets.add(sheet); - } - return sheets; - } - /** * * @return diff --git a/src/main/java/com/alibaba/excel/ExcelWriter.java b/src/main/java/com/alibaba/excel/ExcelWriter.java index 2f5b61d2..634606f7 100644 --- a/src/main/java/com/alibaba/excel/ExcelWriter.java +++ b/src/main/java/com/alibaba/excel/ExcelWriter.java @@ -1,29 +1,18 @@ package com.alibaba.excel; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.alibaba.excel.context.WriteContext; -import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.metadata.Table; -import com.alibaba.excel.parameter.GenerateParam; -import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.write.ExcelBuilder; import com.alibaba.excel.write.ExcelBuilderImpl; -import com.alibaba.excel.write.handler.WriteHandler; -import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.metadata.WriteTable; import com.alibaba.excel.write.metadata.WriteWorkbook; import com.alibaba.excel.write.metadata.fill.FillConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Excel Writer This tool is used to write value out to Excel via POI. This object can perform the following two * functions. @@ -49,92 +38,6 @@ public class ExcelWriter { excelBuilder = new ExcelBuilderImpl(writeWorkbook); } - /** - * Create new writer - * - * @param outputStream - * the java OutputStream you wish to write the value to - * @param typeEnum - * 03 or 07 - * @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter - */ - @Deprecated - public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum) { - this(outputStream, typeEnum, true); - } - - /** - * - * Create new writer - * - * @param outputStream - * the java OutputStream you wish to write the value to - * @param typeEnum - * 03 or 07 - * @param needHead - * Do you need to write the header to the file? - * @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter - */ - @Deprecated - public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { - this(null, outputStream, typeEnum, needHead, null); - } - - /** - * Create new writer - * - * @param templateInputStream - * Append value after a POI file ,Can be null(the template POI filesystem that contains the Workbook - * stream) - * @param outputStream - * the java OutputStream you wish to write the value to - * @param typeEnum - * 03 or 07 - * @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter - */ - @Deprecated - public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum, - Boolean needHead) { - this(templateInputStream, outputStream, typeEnum, needHead, null); - } - - /** - * Create new writer - * - * @param templateInputStream - * Append value after a POI file ,Can be null(the template POI filesystem that contains the Workbook - * stream) - * @param outputStream - * the java OutputStream you wish to write the value to - * @param typeEnum - * 03 or 07 - * @param writeHandler - * User-defined callback - * @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter - */ - @Deprecated - public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum, - Boolean needHead, WriteHandler writeHandler) { - List customWriteHandlerList = new ArrayList(); - customWriteHandlerList.add(writeHandler); - WriteWorkbook writeWorkbook = new WriteWorkbook(); - writeWorkbook.setTemplateInputStream(templateInputStream); - writeWorkbook.setOutputStream(outputStream); - writeWorkbook.setExcelType(typeEnum); - writeWorkbook.setNeedHead(needHead); - writeWorkbook.setCustomWriteHandlerList(customWriteHandlerList); - excelBuilder = new ExcelBuilderImpl(writeWorkbook); - } - - /** - * @param generateParam - * @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter - */ - @Deprecated - public ExcelWriter(GenerateParam generateParam) { - this(generateParam.getOutputStream(), generateParam.getType(), true); - } - /** * Write data to a sheet * @@ -188,141 +91,6 @@ public class ExcelWriter { return this; } - /** - * Write data to a sheet - * - * @param data - * Data to be written - * @param sheet - * Write to this sheet - * @return this current writer - * @deprecated please use {@link ExcelWriter#write(Collection, WriteSheet)} - */ - @Deprecated - public ExcelWriter write(List data, Sheet sheet) { - return write(data, sheet, null); - } - - /** - * Write value to a sheet - * - * @param data - * Data to be written - * @param sheet - * Write to this sheet - * @param table - * Write to this table - * @return this - * @deprecated * @deprecated please use {@link ExcelWriter#write(Collection, WriteSheet,WriteTable)} - */ - @Deprecated - public ExcelWriter write(List data, Sheet sheet, Table table) { - WriteSheet writeSheet = null; - if (sheet != null) { - writeSheet = new WriteSheet(); - writeSheet.setSheetNo(sheet.getSheetNo() - 1); - writeSheet.setSheetName(sheet.getSheetName()); - writeSheet.setClazz(sheet.getClazz()); - writeSheet.setHead(sheet.getHead()); - writeSheet.setTableStyle(sheet.getTableStyle()); - writeSheet.setRelativeHeadRowIndex(sheet.getStartRow()); - writeSheet.setColumnWidthMap(sheet.getColumnWidthMap()); - } - - WriteTable writeTable = null; - if (table != null) { - writeTable = new WriteTable(); - writeTable.setTableNo(table.getTableNo()); - writeTable.setClazz(table.getClazz()); - writeTable.setHead(table.getHead()); - writeTable.setTableStyle(table.getTableStyle()); - } - return write(data, writeSheet, writeTable); - } - - /** - * Write data to a sheet - * - * @param data - * Data to be written - * @param sheet - * Write to this sheet - * @return this current writer - * @deprecated please use {@link ExcelWriter#write(Collection, WriteSheet)} - */ - @Deprecated - public ExcelWriter write0(List data, Sheet sheet) { - return write(data, sheet, null); - } - - /** - * Write value to a sheet - * - * @param data - * Data to be written - * @param sheet - * Write to this sheet - * @param table - * Write to this table - * @return this - * @deprecated * @deprecated please use {@link ExcelWriter#write(Collection, WriteSheet,WriteTable)} - */ - @Deprecated - public ExcelWriter write0(List data, Sheet sheet, Table table) { - return write(data, sheet, table); - } - - /** - * Write data to a sheet - * - * @param data - * Data to be written - * @param sheet - * Write to this sheet - * @return this current writer - * @deprecated please use {@link ExcelWriter#write(Collection, WriteSheet)} - */ - @Deprecated - public ExcelWriter write1(List data, Sheet sheet) { - return write(data, sheet, null); - } - - /** - * Write value to a sheet - * - * @param data - * Data to be written - * @param sheet - * Write to this sheet - * @param table - * Write to this table - * @return this - * @deprecated * @deprecated please use {@link ExcelWriter#write(Collection, WriteSheet,WriteTable)} - */ - @Deprecated - public ExcelWriter write1(List data, Sheet sheet, Table table) { - return write(data, sheet, table); - } - - /** - * Merge Cells,Indexes are zero-based. - * - * @param firstRow - * Index of first row - * @param lastRow - * Index of last row (inclusive), must be equal to or larger than {@code firstRow} - * @param firstCol - * Index of first column - * @param lastCol - * Index of last column (inclusive), must be equal to or larger than {@code firstCol} - * @deprecated please use{@link OnceAbsoluteMergeStrategy} - */ - @Deprecated - public ExcelWriter merge(int firstRow, int lastRow, int firstCol, int lastCol) { - excelBuilder.merge(firstRow, lastRow, firstCol, lastCol); - return this; - } - /** * Close IO */ diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/BlankRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/BlankRecordHandler.java index e6290eb5..30f09273 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/BlankRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/BlankRecordHandler.java @@ -5,7 +5,7 @@ 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.CellData; +import com.alibaba.excel.metadata.data.CellData; /** * Record handler diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/BoolErrRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/BoolErrRecordHandler.java index 8d435213..1afb6c1f 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/BoolErrRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/BoolErrRecordHandler.java @@ -6,7 +6,7 @@ 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.CellData; +import com.alibaba.excel.metadata.data.CellData; /** * Record handler diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/DummyRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/DummyRecordHandler.java index 54a2d1df..eb5bd2ae 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/DummyRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/DummyRecordHandler.java @@ -10,7 +10,7 @@ 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.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.read.metadata.holder.ReadRowHolder; import com.alibaba.excel.read.metadata.holder.xls.XlsReadSheetHolder; diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/FormulaRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/FormulaRecordHandler.java index 5f18b841..f5d7ff0a 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/FormulaRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/FormulaRecordHandler.java @@ -9,29 +9,30 @@ import com.alibaba.excel.context.xls.XlsReadContext; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.RowTypeEnum; import com.alibaba.excel.metadata.Cell; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.DataFormatData; +import com.alibaba.excel.metadata.data.FormulaData; +import com.alibaba.excel.metadata.data.ReadCellData; +import lombok.extern.slf4j.Slf4j; import org.apache.poi.hssf.model.HSSFFormulaParser; import org.apache.poi.hssf.record.FormulaRecord; import org.apache.poi.hssf.record.Record; import org.apache.poi.ss.usermodel.CellType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Record handler * * @author Dan Zheng */ +@Slf4j public class FormulaRecordHandler extends AbstractXlsRecordHandler implements IgnorableXlsRecordHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(FormulaRecordHandler.class); private static final String ERROR = "#VALUE!"; @Override public void processRecord(XlsReadContext xlsReadContext, Record record) { FormulaRecord frec = (FormulaRecord)record; Map cellMap = xlsReadContext.xlsReadSheetHolder().getCellMap(); - CellData tempCellData = new CellData<>(); + ReadCellData tempCellData = new ReadCellData<>(); tempCellData.setRowIndex(frec.getRow()); tempCellData.setColumnIndex((int)frec.getColumn()); CellType cellType = CellType.forInt(frec.getCachedResultType()); @@ -40,10 +41,11 @@ public class FormulaRecordHandler extends AbstractXlsRecordHandler implements Ig formulaValue = HSSFFormulaParser.toFormulaString(xlsReadContext.xlsReadWorkbookHolder().getHssfWorkbook(), frec.getParsedExpression()); } catch (Exception e) { - LOGGER.debug("Get formula value error.", e); + log.debug("Get formula value error.", e); } - tempCellData.setFormula(Boolean.TRUE); - tempCellData.setFormulaValue(formulaValue); + FormulaData formulaData = new FormulaData(); + formulaData.setFormulaValue(formulaValue); + tempCellData.setFormulaData(formulaData); xlsReadContext.xlsReadSheetHolder().setTempRowType(RowTypeEnum.DATA); switch (cellType) { case STRING: @@ -55,11 +57,11 @@ public class FormulaRecordHandler extends AbstractXlsRecordHandler implements Ig case NUMERIC: tempCellData.setType(CellDataTypeEnum.NUMBER); tempCellData.setNumberValue(BigDecimal.valueOf(frec.getValue())); - Integer dataFormat = + int dataFormat = xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatIndex(frec); - Short dataFormatShort = dataFormat.shortValue(); - tempCellData.setDataFormat(dataFormatShort); - tempCellData.setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormatShort, + DataFormatData dataFormatData = new DataFormatData(); + dataFormatData.setIndex((short)dataFormat); + dataFormatData.setFormat(BuiltinFormats.getBuiltinFormat(dataFormatData.getIndex(), xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatString(frec), xlsReadContext.readSheetHolder().getGlobalConfiguration().getLocale())); cellMap.put((int)frec.getColumn(), tempCellData); diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelRecordHandler.java index 4f63ab0c..39481de0 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelRecordHandler.java @@ -6,7 +6,7 @@ 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.CellData; +import com.alibaba.excel.metadata.data.CellData; /** * Record handler diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelSstRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelSstRecordHandler.java index 7fb5cd0d..0075254c 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelSstRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelSstRecordHandler.java @@ -10,7 +10,7 @@ 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.CellData; +import com.alibaba.excel.metadata.data.CellData; /** * Record handler diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java index f9e27c7a..1573b8e7 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java @@ -6,7 +6,8 @@ import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler; import com.alibaba.excel.constant.BuiltinFormats; import com.alibaba.excel.context.xls.XlsReadContext; import com.alibaba.excel.enums.RowTypeEnum; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.DataFormatData; +import com.alibaba.excel.metadata.data.ReadCellData; import org.apache.poi.hssf.record.NumberRecord; import org.apache.poi.hssf.record.Record; @@ -21,13 +22,16 @@ public class NumberRecordHandler extends AbstractXlsRecordHandler implements Ign @Override public void processRecord(XlsReadContext xlsReadContext, Record record) { NumberRecord nr = (NumberRecord)record; - CellDatacellData = CellData.newInstance(BigDecimal.valueOf(nr.getValue()), nr.getRow(), (int)nr.getColumn()); + ReadCellData cellData = ReadCellData.newInstance(BigDecimal.valueOf(nr.getValue()), nr.getRow(), + (int)nr.getColumn()); short dataFormat = (short)xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatIndex( nr); - cellData.setDataFormat(dataFormat); - cellData.setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormat, + DataFormatData dataFormatData = new DataFormatData(); + dataFormatData.setIndex(dataFormat); + dataFormatData.setFormat(BuiltinFormats.getBuiltinFormat(dataFormat, xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatString(nr), xlsReadContext.readSheetHolder().getGlobalConfiguration().getLocale())); + cellData.setDataFormatData(dataFormatData); xlsReadContext.xlsReadSheetHolder().getCellMap().put((int)nr.getColumn(), cellData); xlsReadContext.xlsReadSheetHolder().setTempRowType(RowTypeEnum.DATA); } diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/RkRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/RkRecordHandler.java index d8317b37..91c3c9f8 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/RkRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/RkRecordHandler.java @@ -5,7 +5,7 @@ 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.CellData; +import com.alibaba.excel.metadata.data.CellData; /** * Record handler diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/StringRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/StringRecordHandler.java index 2408d219..4e78a381 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/StringRecordHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/handlers/StringRecordHandler.java @@ -7,7 +7,7 @@ import org.slf4j.LoggerFactory; import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler; import com.alibaba.excel.context.xls.XlsReadContext; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.read.metadata.holder.xls.XlsReadSheetHolder; /** diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java index 770355b0..ac2b8457 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java @@ -4,7 +4,7 @@ import java.math.BigDecimal; import com.alibaba.excel.context.xlsx.XlsxReadContext; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder; import com.alibaba.excel.util.BooleanUtils; import com.alibaba.excel.util.StringUtils; diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellFormulaTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellFormulaTagHandler.java index e153a3b1..6e5246d3 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellFormulaTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellFormulaTagHandler.java @@ -1,10 +1,11 @@ package com.alibaba.excel.analysis.v07.handlers; -import org.xml.sax.Attributes; - import com.alibaba.excel.context.xlsx.XlsxReadContext; +import com.alibaba.excel.metadata.data.FormulaData; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder; +import org.xml.sax.Attributes; + /** * Cell Handler * @@ -15,14 +16,15 @@ public class CellFormulaTagHandler extends AbstractXlsxTagHandler { @Override public void startElement(XlsxReadContext xlsxReadContext, String name, Attributes attributes) { XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder(); - xlsxReadSheetHolder.getTempCellData().setFormula(Boolean.TRUE); xlsxReadSheetHolder.setTempFormula(new StringBuilder()); } @Override public void endElement(XlsxReadContext xlsxReadContext, String name) { XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder(); - xlsxReadSheetHolder.getTempCellData().setFormulaValue(xlsxReadSheetHolder.getTempFormula().toString()); + FormulaData formulaData = new FormulaData(); + formulaData.setFormulaValue(xlsxReadSheetHolder.getTempFormula().toString()); + xlsxReadSheetHolder.getTempCellData().setFormulaData(formulaData); } @Override diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellInlineStringValueTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellInlineStringValueTagHandler.java index 3058e8e8..99c4a8c5 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellInlineStringValueTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellInlineStringValueTagHandler.java @@ -1,9 +1,9 @@ package com.alibaba.excel.analysis.v07.handlers; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; - import com.alibaba.excel.context.xlsx.XlsxReadContext; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; + +import org.apache.poi.xssf.usermodel.XSSFRichTextString; /** * Cell inline string value handler diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java index 135153e0..4a58bf78 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java @@ -4,7 +4,8 @@ import com.alibaba.excel.constant.BuiltinFormats; import com.alibaba.excel.constant.ExcelXmlConstants; import com.alibaba.excel.context.xlsx.XlsxReadContext; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.DataFormatData; +import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder; import com.alibaba.excel.util.PositionUtils; import com.alibaba.excel.util.StringUtils; @@ -36,7 +37,7 @@ public class CellTagHandler extends AbstractXlsxTagHandler { // t="n" ,it's means Number // t is null ,it's means Empty or Number CellDataTypeEnum type = CellDataTypeEnum.buildFromCellType(attributes.getValue(ExcelXmlConstants.ATTRIBUTE_T)); - xlsxReadSheetHolder.setTempCellData(new CellData(type)); + xlsxReadSheetHolder.setTempCellData(new ReadCellData<>(type)); xlsxReadSheetHolder.setTempData(new StringBuilder()); // Put in data transformation information @@ -53,9 +54,11 @@ public class CellTagHandler extends AbstractXlsxTagHandler { } XSSFCellStyle xssfCellStyle = stylesTable.getStyleAt(dateFormatIndexInteger); short dataFormat = xssfCellStyle.getDataFormat(); - xlsxReadSheetHolder.getTempCellData().setDataFormat(dataFormat); - xlsxReadSheetHolder.getTempCellData().setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormat, + DataFormatData dataFormatData = new DataFormatData(); + dataFormatData.setIndex(dataFormat); + dataFormatData.setFormat(BuiltinFormats.getBuiltinFormat(dataFormat, xssfCellStyle.getDataFormatString(), xlsxReadSheetHolder.getGlobalConfiguration().getLocale())); + xlsxReadSheetHolder.getTempCellData().setDataFormatData(dataFormatData); } } diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellValueTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellValueTagHandler.java index 7e685c97..bd623f4a 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellValueTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellValueTagHandler.java @@ -2,7 +2,7 @@ package com.alibaba.excel.analysis.v07.handlers; import com.alibaba.excel.context.xlsx.XlsxReadContext; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.util.StringUtils; /** diff --git a/src/main/java/com/alibaba/excel/context/AnalysisContext.java b/src/main/java/com/alibaba/excel/context/AnalysisContext.java index df17f55d..37039cbc 100644 --- a/src/main/java/com/alibaba/excel/context/AnalysisContext.java +++ b/src/main/java/com/alibaba/excel/context/AnalysisContext.java @@ -4,7 +4,6 @@ import java.io.InputStream; import java.util.List; import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.read.metadata.holder.ReadHolder; import com.alibaba.excel.read.metadata.holder.ReadRowHolder; @@ -92,15 +91,6 @@ public interface AnalysisContext { */ void readSheetList(List readSheetList); - /** - * get current sheet - * - * @return current analysis sheet - * @deprecated please use {@link #readSheetHolder()} - */ - @Deprecated - Sheet getCurrentSheet(); - /** * * get excel type diff --git a/src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java b/src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java index ab27e87e..7aeba321 100644 --- a/src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java @@ -3,11 +3,7 @@ package com.alibaba.excel.context; import java.io.InputStream; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alibaba.excel.exception.ExcelAnalysisException; -import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.read.metadata.ReadWorkbook; import com.alibaba.excel.read.metadata.holder.ReadHolder; @@ -22,12 +18,13 @@ import com.alibaba.excel.read.processor.AnalysisEventProcessor; import com.alibaba.excel.read.processor.DefaultAnalysisEventProcessor; import com.alibaba.excel.support.ExcelTypeEnum; +import lombok.extern.slf4j.Slf4j; + /** - * * @author jipengfei */ +@Slf4j public class AnalysisContextImpl implements AnalysisContext { - private static final Logger LOGGER = LoggerFactory.getLogger(AnalysisContextImpl.class); /** * The Workbook currently written */ @@ -65,8 +62,8 @@ public class AnalysisContextImpl implements AnalysisContext { } currentReadHolder = readWorkbookHolder; analysisEventProcessor = new DefaultAnalysisEventProcessor(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Initialization 'AnalysisContextImpl' complete"); + if (log.isDebugEnabled()) { + log.debug("Initialization 'AnalysisContextImpl' complete"); } } @@ -87,8 +84,8 @@ public class AnalysisContextImpl implements AnalysisContext { throw new ExcelAnalysisException("Cannot read sheet repeatedly."); } readWorkbookHolder.getHasReadSheet().add(readSheetHolder.getSheetNo()); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Began to read:{}", readSheetHolder); + if (log.isDebugEnabled()) { + log.debug("Began to read:{}", readSheetHolder); } } @@ -137,15 +134,6 @@ public class AnalysisContextImpl implements AnalysisContext { } - @Override - public Sheet getCurrentSheet() { - Sheet sheet = new Sheet(readSheetHolder.getSheetNo() + 1); - sheet.setSheetName(readSheetHolder.getSheetName()); - sheet.setHead(readSheetHolder.getHead()); - sheet.setClazz(readSheetHolder.getClazz()); - sheet.setHeadLineMun(readSheetHolder.getHeadRowNumber()); - return sheet; - } @Override public ExcelTypeEnum getExcelType() { diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java index 648a7fe9..175f33da 100644 --- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java @@ -8,7 +8,7 @@ import java.util.UUID; import com.alibaba.excel.enums.WriteTypeEnum; import com.alibaba.excel.exception.ExcelGenerateException; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.util.DateUtils; diff --git a/src/main/java/com/alibaba/excel/converters/AutoConverter.java b/src/main/java/com/alibaba/excel/converters/AutoConverter.java index 07ad471f..5981e7ac 100644 --- a/src/main/java/com/alibaba/excel/converters/AutoConverter.java +++ b/src/main/java/com/alibaba/excel/converters/AutoConverter.java @@ -1,36 +1,9 @@ package com.alibaba.excel.converters; -import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; -import com.alibaba.excel.metadata.GlobalConfiguration; -import com.alibaba.excel.metadata.property.ExcelContentProperty; - /** * An empty converter.It's automatically converted by type. * * @author Jiaju Zhuang */ public class AutoConverter implements Converter { - - @Override - public Class supportJavaTypeKey() { - return null; - } - - @Override - public CellDataTypeEnum supportExcelTypeKey() { - return null; - } - - @Override - public Object convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - return null; - } - - @Override - public CellData convertToExcelData(Object value, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - return null; - } } diff --git a/src/main/java/com/alibaba/excel/converters/Converter.java b/src/main/java/com/alibaba/excel/converters/Converter.java index 3d1a369d..df7f4719 100644 --- a/src/main/java/com/alibaba/excel/converters/Converter.java +++ b/src/main/java/com/alibaba/excel/converters/Converter.java @@ -1,13 +1,10 @@ package com.alibaba.excel.converters; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; -import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; -import com.alibaba.excel.write.metadata.holder.WriteHolder; -import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; -import com.alibaba.excel.write.metadata.holder.WriteTableHolder; /** * Convert between Java objects and excel objects @@ -44,7 +41,7 @@ public interface Converter { * @return Data to put into a Java object * @throws Exception Exception. */ - default T convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + default T convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception { throw new UnsupportedOperationException("The current operation is not supported by the current converter."); } @@ -52,15 +49,13 @@ public interface Converter { /** * Convert excel objects to Java objects * - * @param cellData Excel cell data.NotNull. - * @param contentProperty Content property.Nullable. - * @param readSheetHolder .NotNull. + * @param context read converter context * @return Data to put into a Java object * @throws Exception Exception. */ - default T convertToJavaData(CellData cellData, - ExcelContentProperty contentProperty, ReadSheetHolder readSheetHolder) throws Exception { - return convertToJavaData(cellData, contentProperty, readSheetHolder.globalConfiguration()); + default T convertToJavaData(ReadConverterContext context) throws Exception { + return convertToJavaData(context.getReadCellData(), context.getContentProperty(), + context.getAnalysisContext().currentReadHolder().globalConfiguration()); } /** @@ -72,7 +67,7 @@ public interface Converter { * @return Data to put into a Excel * @throws Exception Exception. */ - default CellData convertToExcelData(T value, ExcelContentProperty contentProperty, + default WriteCellData convertToExcelData(T value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception { throw new UnsupportedOperationException("The current operation is not supported by the current converter."); } @@ -80,14 +75,12 @@ public interface Converter { /** * Convert Java objects to excel objects * - * @param value Java Data.NotNull. - * @param contentProperty Content property.Nullable. - * @param currentWriteHolder He would be {@link WriteSheetHolder} or {@link WriteTableHolder}.NotNull. + * @param context write context * @return Data to put into a Excel * @throws Exception Exception. */ - default CellData convertToExcelData(T value, ExcelContentProperty contentProperty, - WriteHolder currentWriteHolder) throws Exception { - return convertToExcelData(value, contentProperty, currentWriteHolder.globalConfiguration()); + default WriteCellData convertToExcelData(WriteConverterContext context) throws Exception { + return convertToExcelData(context.getValue(), context.getContentProperty(), + context.getWriteContext().currentWriteHolder().globalConfiguration()); } } diff --git a/src/main/java/com/alibaba/excel/converters/ReadConverterContext.java b/src/main/java/com/alibaba/excel/converters/ReadConverterContext.java new file mode 100644 index 00000000..e1367065 --- /dev/null +++ b/src/main/java/com/alibaba/excel/converters/ReadConverterContext.java @@ -0,0 +1,30 @@ +package com.alibaba.excel.converters; + +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.metadata.data.ReadCellData; +import com.alibaba.excel.metadata.property.ExcelContentProperty; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * read converter context + * + * @author Jiaju Zhuang + */ +@Data +@AllArgsConstructor +public class ReadConverterContext { + /** + * Excel cell data.NotNull. + */ + private ReadCellData readCellData; + /** + * Content property.Nullable. + */ + private ExcelContentProperty contentProperty; + /** + * context.NotNull. + */ + private AnalysisContext analysisContext; +} diff --git a/src/main/java/com/alibaba/excel/converters/WriteConverterContext.java b/src/main/java/com/alibaba/excel/converters/WriteConverterContext.java new file mode 100644 index 00000000..b1d0a5dd --- /dev/null +++ b/src/main/java/com/alibaba/excel/converters/WriteConverterContext.java @@ -0,0 +1,31 @@ +package com.alibaba.excel.converters; + +import com.alibaba.excel.context.WriteContext; +import com.alibaba.excel.metadata.property.ExcelContentProperty; + +import lombok.Data; + +/** + * write converter context + * + * @author Jiaju Zhuang + */ +@Data +@AllArgsConstructor +public class WriteConverterContext { + + /** + * Java Data.NotNull. + */ + private T value; + + /** + * Content property.Nullable. + */ + private ExcelContentProperty contentProperty; + + /** + * write context + */ + private WriteContext writeContext; +} diff --git a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java index f4e9ad6f..31484562 100644 --- a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java @@ -4,8 +4,9 @@ import java.math.BigDecimal; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -26,7 +27,7 @@ public class BigDecimalBooleanConverter implements Converter { } @Override - public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public BigDecimal convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return BigDecimal.ONE; @@ -35,12 +36,12 @@ public class BigDecimalBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (BigDecimal.ONE.equals(value)) { - return new CellData<>(Boolean.TRUE); + return new WriteCellData<>(Boolean.TRUE); } - return new CellData<>(Boolean.FALSE); + return new WriteCellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java index 39061d70..6a60b0d7 100644 --- a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java @@ -4,8 +4,9 @@ import java.math.BigDecimal; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; import com.alibaba.excel.write.metadata.holder.WriteHolder; @@ -28,13 +29,13 @@ public class BigDecimalNumberConverter implements Converter { } @Override - public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public BigDecimal convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue(); } @Override - public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, WriteHolder currentWriteHolder) { return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); } diff --git a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java index 356a38c5..3b117812 100644 --- a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java @@ -5,8 +5,9 @@ import java.text.ParseException; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; @@ -28,13 +29,13 @@ public class BigDecimalStringConverter implements Converter { } @Override - public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public BigDecimal convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseBigDecimal(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanBooleanConverter.java index 56654cd5..884f6515 100644 --- a/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanBooleanConverter.java @@ -2,8 +2,9 @@ package com.alibaba.excel.converters.booleanconverter; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -24,15 +25,15 @@ public class BooleanBooleanConverter implements Converter { } @Override - public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Boolean convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getBooleanValue(); } @Override - public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return new CellData<>(value); + return new WriteCellData<>(value); } } diff --git a/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanNumberConverter.java b/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanNumberConverter.java index 00cd4c2c..b2438e83 100644 --- a/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanNumberConverter.java @@ -4,8 +4,9 @@ import java.math.BigDecimal; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -25,7 +26,7 @@ public class BooleanNumberConverter implements Converter { } @Override - public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Boolean convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (BigDecimal.ONE.compareTo(cellData.getNumberValue()) == 0) { return Boolean.TRUE; @@ -34,12 +35,12 @@ public class BooleanNumberConverter implements Converter { } @Override - public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (value) { - return new CellData<>(BigDecimal.ONE); + return new WriteCellData<>(BigDecimal.ONE); } - return new CellData<>(BigDecimal.ZERO); + return new WriteCellData<>(BigDecimal.ZERO); } } diff --git a/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanStringConverter.java b/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanStringConverter.java index 9f82f32a..0141ef8d 100644 --- a/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanStringConverter.java @@ -2,8 +2,9 @@ package com.alibaba.excel.converters.booleanconverter; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -24,15 +25,15 @@ public class BooleanStringConverter implements Converter { } @Override - public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Boolean convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return Boolean.valueOf(cellData.getStringValue()); } @Override - public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return new CellData<>(value.toString()); + return new WriteCellData<>(value.toString()); } } diff --git a/src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java b/src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java index 63f387d7..a1f8d3ac 100644 --- a/src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java @@ -1,12 +1,8 @@ package com.alibaba.excel.converters.bytearray; -import java.lang.annotation.Annotation; - -import com.alibaba.excel.annotation.write.style.ImagePosition; import com.alibaba.excel.converters.Converter; -import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; +import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; /** @@ -21,29 +17,13 @@ public class BoxingByteArrayImageConverter implements Converter { } @Override - public CellDataTypeEnum supportExcelTypeKey() { - return CellDataTypeEnum.IMAGE; - } - - @Override - public Byte[] convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - throw new UnsupportedOperationException("Cannot convert images to byte arrays"); - } - - @Override - public CellData convertToExcelData(Byte[] value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Byte[] value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { byte[] byteValue = new byte[value.length]; for (int i = 0; i < value.length; i++) { byteValue[i] = value[i]; } - ImagePosition imagePosition = contentProperty.getField().getAnnotation(ImagePosition.class); - if (imagePosition != null) { - return new CellData(byteValue, imagePosition); - } else { - return new CellData(byteValue); - } + return new WriteCellData<>(byteValue); } } diff --git a/src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java b/src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java index 48b70cbb..9a871fea 100644 --- a/src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java @@ -1,12 +1,8 @@ package com.alibaba.excel.converters.bytearray; -import java.lang.annotation.Annotation; - -import com.alibaba.excel.annotation.write.style.ImagePosition; import com.alibaba.excel.converters.Converter; -import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; +import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; /** @@ -15,32 +11,16 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty; * @author Jiaju Zhuang */ public class ByteArrayImageConverter implements Converter { + @Override public Class supportJavaTypeKey() { return byte[].class; } @Override - public CellDataTypeEnum supportExcelTypeKey() { - return CellDataTypeEnum.IMAGE; - } - - @Override - - public byte[] convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(byte[] value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - throw new UnsupportedOperationException("Cannot convert images to byte arrays"); - } - - @Override - public CellData convertToExcelData(byte[] value, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - ImagePosition imagePosition = contentProperty.getField().getAnnotation(ImagePosition.class); - if (imagePosition != null) { - return new CellData(value, imagePosition); - } else { - return new CellData(value); - } + return new WriteCellData<>(value); } } diff --git a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteBooleanConverter.java index afe079cb..c7da08c4 100644 --- a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteBooleanConverter.java @@ -2,8 +2,9 @@ package com.alibaba.excel.converters.byteconverter; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -26,7 +27,7 @@ public class ByteBooleanConverter implements Converter { } @Override - public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Byte convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; @@ -35,12 +36,12 @@ public class ByteBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { - return new CellData<>(Boolean.TRUE); + return new WriteCellData<>(Boolean.TRUE); } - return new CellData<>(Boolean.FALSE); + return new WriteCellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java index 891ae714..4103b9cb 100644 --- a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java @@ -1,14 +1,12 @@ package com.alibaba.excel.converters.byteconverter; -import java.math.BigDecimal; - import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; -import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Byte and number converter @@ -28,15 +26,15 @@ public class ByteNumberConverter implements Converter { } @Override - public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Byte convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().byteValue(); } @Override - public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, - WriteHolder currentWriteHolder) { - return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); + public WriteCellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, + GlobalConfiguration globalConfiguration) { + return NumberUtils.formatToCellData(value, contentProperty); } } diff --git a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java index 041557cf..988afbc6 100644 --- a/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java @@ -4,8 +4,9 @@ import java.text.ParseException; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; @@ -27,13 +28,13 @@ public class ByteStringConverter implements Converter { } @Override - public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Byte convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseByte(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java b/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java index 73b071af..68daee84 100644 --- a/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java +++ b/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java @@ -3,12 +3,10 @@ package com.alibaba.excel.converters.date; import java.util.Date; import com.alibaba.excel.converters.Converter; -import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; 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.WorkBookUtil; -import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Date and date converter @@ -22,26 +20,14 @@ public class DateDateConverter implements Converter { } @Override - public CellDataTypeEnum supportExcelTypeKey() { - return CellDataTypeEnum.DATE; - } - - @Override - public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - return cellData.getDateValue(); - } - - @Override - public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, - WriteHolder currentWriteHolder) throws Exception { - CellData cellData = new CellData<>(value); + 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; } - WorkBookUtil.fillDataFormat(cellData, currentWriteHolder, - contentProperty.getDateTimeFormatProperty().getFormat()); + WorkBookUtil.fillDataFormat(cellData, contentProperty.getDateTimeFormatProperty().getFormat()); return cellData; } } diff --git a/src/main/java/com/alibaba/excel/converters/date/DateNumberConverter.java b/src/main/java/com/alibaba/excel/converters/date/DateNumberConverter.java index 6eee4de0..34bb7536 100644 --- a/src/main/java/com/alibaba/excel/converters/date/DateNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/date/DateNumberConverter.java @@ -3,14 +3,15 @@ package com.alibaba.excel.converters.date; import java.math.BigDecimal; import java.util.Date; -import org.apache.poi.ss.usermodel.DateUtil; - import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; +import org.apache.poi.ss.usermodel.DateUtil; + /** * Date and number converter * @@ -29,7 +30,7 @@ public class DateNumberConverter implements Converter { } @Override - public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Date convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { return DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(), @@ -41,13 +42,13 @@ public class DateNumberConverter implements Converter { } @Override - public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { - return new CellData<>( + return new WriteCellData<>( BigDecimal.valueOf(DateUtil.getExcelDate(value, globalConfiguration.getUse1904windowing()))); } else { - return new CellData<>(BigDecimal.valueOf( + return new WriteCellData<>(BigDecimal.valueOf( DateUtil.getExcelDate(value, contentProperty.getDateTimeFormatProperty().getUse1904windowing()))); } } diff --git a/src/main/java/com/alibaba/excel/converters/date/DateStringConverter.java b/src/main/java/com/alibaba/excel/converters/date/DateStringConverter.java index 687d84d7..9941c70e 100644 --- a/src/main/java/com/alibaba/excel/converters/date/DateStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/date/DateStringConverter.java @@ -5,8 +5,9 @@ import java.util.Date; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.DateUtils; @@ -27,7 +28,7 @@ public class DateStringConverter implements Converter { } @Override - public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Date convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { return DateUtils.parseDate(cellData.getStringValue(), null); @@ -38,12 +39,12 @@ public class DateStringConverter implements Converter { } @Override - public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { - return new CellData<>(DateUtils.format(value, null)); + return new WriteCellData<>(DateUtils.format(value, null)); } else { - return new CellData<>(DateUtils.format(value, contentProperty.getDateTimeFormatProperty().getFormat())); + return new WriteCellData<>(DateUtils.format(value, contentProperty.getDateTimeFormatProperty().getFormat())); } } } diff --git a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleBooleanConverter.java index 6aa509e1..3da808e1 100644 --- a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleBooleanConverter.java @@ -2,8 +2,9 @@ package com.alibaba.excel.converters.doubleconverter; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -26,7 +27,7 @@ public class DoubleBooleanConverter implements Converter { } @Override - public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Double convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; @@ -35,12 +36,12 @@ public class DoubleBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Double value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { - return new CellData<>(Boolean.TRUE); + return new WriteCellData<>(Boolean.TRUE); } - return new CellData<>(Boolean.FALSE); + return new WriteCellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java index c3db3d3b..70bdffb6 100644 --- a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java @@ -1,14 +1,12 @@ package com.alibaba.excel.converters.doubleconverter; -import java.math.BigDecimal; - import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; -import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Double and number converter @@ -28,14 +26,14 @@ public class DoubleNumberConverter implements Converter { } @Override - public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Double convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().doubleValue(); } @Override - public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, - WriteHolder currentWriteHolder) { - return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); + public WriteCellData convertToExcelData(Double value, ExcelContentProperty contentProperty, + GlobalConfiguration globalConfiguration) { + return NumberUtils.formatToCellData(value, contentProperty); } } diff --git a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java index 351d0b8a..e1951130 100644 --- a/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java @@ -4,8 +4,9 @@ import java.text.ParseException; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; @@ -27,13 +28,13 @@ public class DoubleStringConverter implements Converter { } @Override - public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Double convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseDouble(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Double value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java b/src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java index a94f7c08..c8fd6e8b 100644 --- a/src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java @@ -2,11 +2,10 @@ package com.alibaba.excel.converters.file; import java.io.File; import java.io.IOException; -import com.alibaba.excel.annotation.write.style.ImagePosition; + import com.alibaba.excel.converters.Converter; -import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; 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.FileUtils; @@ -22,24 +21,8 @@ public class FileImageConverter implements Converter { } @Override - public CellDataTypeEnum supportExcelTypeKey() { - return CellDataTypeEnum.IMAGE; - } - - @Override - public File convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - throw new UnsupportedOperationException("Cannot convert images to file"); - } - - @Override - public CellData convertToExcelData(File value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(File value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { - ImagePosition imagePosition = contentProperty.getField().getAnnotation(ImagePosition.class); - if (imagePosition != null) { - return new CellData(FileUtils.readFileToByteArray(value), imagePosition); - } else { - return new CellData(FileUtils.readFileToByteArray(value)); - } + return new WriteCellData<>(FileUtils.readFileToByteArray(value)); } } diff --git a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatBooleanConverter.java index c2f674f2..1ec6168c 100644 --- a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatBooleanConverter.java @@ -2,8 +2,9 @@ package com.alibaba.excel.converters.floatconverter; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -26,7 +27,7 @@ public class FloatBooleanConverter implements Converter { } @Override - public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Float convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; @@ -35,12 +36,12 @@ public class FloatBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Float value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { - return new CellData<>(Boolean.TRUE); + return new WriteCellData<>(Boolean.TRUE); } - return new CellData<>(Boolean.FALSE); + return new WriteCellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java index 1a401dff..478086e3 100644 --- a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java @@ -1,12 +1,13 @@ package com.alibaba.excel.converters.floatconverter; import com.alibaba.excel.converters.Converter; +import com.alibaba.excel.converters.WriteConverterContext; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; -import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Float and number converter @@ -26,14 +27,13 @@ public class FloatNumberConverter implements Converter { } @Override - public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Float convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().floatValue(); } @Override - public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, - WriteHolder currentWriteHolder) { - return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); + public WriteCellData convertToExcelData(WriteConverterContext context) { + return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty()); } } diff --git a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java index 29c819b1..bd5e9762 100644 --- a/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java @@ -4,8 +4,9 @@ import java.text.ParseException; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; @@ -27,13 +28,13 @@ public class FloatStringConverter implements Converter { } @Override - public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Float convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseFloat(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Float value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java b/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java index 15043074..ff8492f0 100644 --- a/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java @@ -2,15 +2,11 @@ package com.alibaba.excel.converters.inputstream; import java.io.IOException; import java.io.InputStream; -import java.lang.annotation.Annotation; -import com.alibaba.excel.annotation.write.style.ImagePosition; import com.alibaba.excel.converters.Converter; -import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; 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.FileUtils; import com.alibaba.excel.util.IoUtils; /** @@ -25,25 +21,9 @@ public class InputStreamImageConverter implements Converter { } @Override - public CellDataTypeEnum supportExcelTypeKey() { - return CellDataTypeEnum.IMAGE; - } - - @Override - public InputStream convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - throw new UnsupportedOperationException("Cannot convert images to input stream"); - } - - @Override - public CellData convertToExcelData(InputStream value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(InputStream value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { - ImagePosition imagePosition = contentProperty.getField().getAnnotation(ImagePosition.class); - if (imagePosition != null) { - return new CellData(IoUtils.toByteArray(value), imagePosition); - } else { - return new CellData(IoUtils.toByteArray(value)); - } + return new WriteCellData<>(IoUtils.toByteArray(value)); } } diff --git a/src/main/java/com/alibaba/excel/converters/integer/IntegerBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/integer/IntegerBooleanConverter.java index 37b5d913..e3f13068 100644 --- a/src/main/java/com/alibaba/excel/converters/integer/IntegerBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/integer/IntegerBooleanConverter.java @@ -2,8 +2,9 @@ package com.alibaba.excel.converters.integer; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -26,7 +27,7 @@ public class IntegerBooleanConverter implements Converter { } @Override - public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Integer convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; @@ -35,12 +36,12 @@ public class IntegerBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { - return new CellData<>(Boolean.TRUE); + return new WriteCellData<>(Boolean.TRUE); } - return new CellData<>(Boolean.FALSE); + return new WriteCellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java b/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java index 95a796b5..203aa1ac 100644 --- a/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java @@ -1,12 +1,13 @@ package com.alibaba.excel.converters.integer; import com.alibaba.excel.converters.Converter; +import com.alibaba.excel.converters.WriteConverterContext; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; -import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Integer and number converter @@ -26,15 +27,14 @@ public class IntegerNumberConverter implements Converter { } @Override - public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Integer convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().intValue(); } @Override - public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, - WriteHolder currentWriteHolder) { - return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); + public WriteCellData convertToExcelData(WriteConverterContext context) { + return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty()); } } diff --git a/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java b/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java index e6d91d34..62dce6e6 100644 --- a/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java @@ -4,8 +4,9 @@ import java.text.ParseException; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; @@ -27,13 +28,13 @@ public class IntegerStringConverter implements Converter { } @Override - public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Integer convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseInteger(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/longconverter/LongBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/longconverter/LongBooleanConverter.java index 298fed5e..d123ed66 100644 --- a/src/main/java/com/alibaba/excel/converters/longconverter/LongBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/longconverter/LongBooleanConverter.java @@ -2,8 +2,9 @@ package com.alibaba.excel.converters.longconverter; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -26,7 +27,7 @@ public class LongBooleanConverter implements Converter { } @Override - public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Long convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; @@ -35,12 +36,12 @@ public class LongBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { - return new CellData<>(Boolean.TRUE); + return new WriteCellData<>(Boolean.TRUE); } - return new CellData<>(Boolean.FALSE); + return new WriteCellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/longconverter/LongNumberConverter.java b/src/main/java/com/alibaba/excel/converters/longconverter/LongNumberConverter.java index 7e4aa235..aee15b5b 100644 --- a/src/main/java/com/alibaba/excel/converters/longconverter/LongNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/longconverter/LongNumberConverter.java @@ -1,12 +1,13 @@ package com.alibaba.excel.converters.longconverter; import com.alibaba.excel.converters.Converter; +import com.alibaba.excel.converters.WriteConverterContext; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; -import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Long and number converter @@ -26,15 +27,14 @@ public class LongNumberConverter implements Converter { } @Override - public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Long convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().longValue(); } @Override - public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, - WriteHolder currentWriteHolder) { - return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); + public WriteCellData convertToExcelData(WriteConverterContext context) { + return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty()); } } diff --git a/src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java b/src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java index 873fb113..26ffcc81 100644 --- a/src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java @@ -4,8 +4,9 @@ import java.text.ParseException; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; @@ -27,13 +28,13 @@ public class LongStringConverter implements Converter { } @Override - public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Long convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseLong(cellData.getStringValue(), contentProperty); } @Override - public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortBooleanConverter.java index eb39b7de..1f0517ee 100644 --- a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortBooleanConverter.java @@ -2,8 +2,9 @@ package com.alibaba.excel.converters.shortconverter; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -26,7 +27,7 @@ public class ShortBooleanConverter implements Converter { } @Override - public Short convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Short convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; @@ -35,12 +36,12 @@ public class ShortBooleanConverter implements Converter { } @Override - public CellData convertToExcelData(Short value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Short value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { - return new CellData<>(Boolean.TRUE); + return new WriteCellData<>(Boolean.TRUE); } - return new CellData<>(Boolean.FALSE); + return new WriteCellData<>(Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortNumberConverter.java b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortNumberConverter.java index eedfca4f..d0568606 100644 --- a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortNumberConverter.java @@ -1,14 +1,13 @@ package com.alibaba.excel.converters.shortconverter; -import java.math.BigDecimal; - import com.alibaba.excel.converters.Converter; +import com.alibaba.excel.converters.WriteConverterContext; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; -import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Short and number converter @@ -28,14 +27,13 @@ public class ShortNumberConverter implements Converter { } @Override - public Short convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public Short convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().shortValue(); } @Override - public CellData convertToExcelData(Short value, ExcelContentProperty contentProperty, - WriteHolder currentWriteHolder) { - return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); + public WriteCellData convertToExcelData(WriteConverterContext context) { + return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty()); } } diff --git a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java index 85c56067..497fdee9 100644 --- a/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java @@ -4,8 +4,9 @@ import java.text.ParseException; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.NumberUtils; @@ -27,13 +28,13 @@ public class ShortStringConverter implements Converter { } @Override - public Short convertToJavaData(CellDatacellData, ExcelContentProperty contentProperty, + public Short convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseShort(cellData.getStringValue(), contentProperty); } @Override - public CellDataconvertToExcelData(Short value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(Short value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } diff --git a/src/main/java/com/alibaba/excel/converters/string/StringBooleanConverter.java b/src/main/java/com/alibaba/excel/converters/string/StringBooleanConverter.java index f2aafb4d..704a18b4 100644 --- a/src/main/java/com/alibaba/excel/converters/string/StringBooleanConverter.java +++ b/src/main/java/com/alibaba/excel/converters/string/StringBooleanConverter.java @@ -2,8 +2,9 @@ package com.alibaba.excel.converters.string; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -24,15 +25,15 @@ public class StringBooleanConverter implements Converter { } @Override - public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public String convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getBooleanValue().toString(); } @Override - public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return new CellData<>(Boolean.valueOf(value)); + return new WriteCellData<>(Boolean.valueOf(value)); } } diff --git a/src/main/java/com/alibaba/excel/converters/string/StringErrorConverter.java b/src/main/java/com/alibaba/excel/converters/string/StringErrorConverter.java index f0a71a46..1456d80f 100644 --- a/src/main/java/com/alibaba/excel/converters/string/StringErrorConverter.java +++ b/src/main/java/com/alibaba/excel/converters/string/StringErrorConverter.java @@ -2,8 +2,9 @@ package com.alibaba.excel.converters.string; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -23,15 +24,15 @@ public class StringErrorConverter implements Converter { } @Override - public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public String convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getStringValue(); } @Override - public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return new CellData<>(CellDataTypeEnum.ERROR, value); + return new WriteCellData<>(CellDataTypeEnum.ERROR, value); } } diff --git a/src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java b/src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java index 940d0065..fb262e19 100644 --- a/src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java @@ -2,16 +2,12 @@ package com.alibaba.excel.converters.string; import java.io.File; import java.io.IOException; -import java.lang.annotation.Annotation; -import com.alibaba.excel.annotation.write.style.ImagePosition; import com.alibaba.excel.converters.Converter; -import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; 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.FileUtils; -import com.alibaba.excel.util.IoUtils; /** * String and image converter @@ -25,25 +21,9 @@ public class StringImageConverter implements Converter { } @Override - public CellDataTypeEnum supportExcelTypeKey() { - return CellDataTypeEnum.IMAGE; - } - - @Override - public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - throw new UnsupportedOperationException("Cannot convert images to string"); - } - - @Override - public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { - ImagePosition imagePosition = contentProperty.getField().getAnnotation(ImagePosition.class); - if (imagePosition != null) { - return new CellData(FileUtils.readFileToByteArray(new File(value)), imagePosition); - } else { - return new CellData(FileUtils.readFileToByteArray(new File(value))); - } + return new WriteCellData<>(FileUtils.readFileToByteArray(new File(value))); } } diff --git a/src/main/java/com/alibaba/excel/converters/string/StringNumberConverter.java b/src/main/java/com/alibaba/excel/converters/string/StringNumberConverter.java index e9b6fef6..4c3bbc59 100644 --- a/src/main/java/com/alibaba/excel/converters/string/StringNumberConverter.java +++ b/src/main/java/com/alibaba/excel/converters/string/StringNumberConverter.java @@ -2,18 +2,19 @@ package com.alibaba.excel.converters.string; import java.math.BigDecimal; -import org.apache.poi.ss.usermodel.DateUtil; - import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; import com.alibaba.excel.util.DateUtils; import com.alibaba.excel.util.NumberDataFormatterUtils; import com.alibaba.excel.util.NumberUtils; import com.alibaba.excel.util.StringUtils; +import org.apache.poi.ss.usermodel.DateUtil; + /** * String and number converter * @@ -32,7 +33,7 @@ public class StringNumberConverter implements Converter { } @Override - public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public String convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { // If there are "DateTimeFormat", read as date if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) { @@ -46,17 +47,20 @@ public class StringNumberConverter implements Converter { return NumberUtils.format(cellData.getNumberValue(), contentProperty); } // Excel defines formatting - if (cellData.getDataFormat() != null && !StringUtils.isEmpty(cellData.getDataFormatString())) { - return NumberDataFormatterUtils.format(cellData.getNumberValue().doubleValue(), cellData.getDataFormat(), - cellData.getDataFormatString(), globalConfiguration); + boolean hasDataFormatData = cellData.getDataFormatData() != null + && cellData.getDataFormatData().getIndex() != null && !StringUtils.isEmpty( + cellData.getDataFormatData().getFormat()); + if (hasDataFormatData) { + return NumberDataFormatterUtils.format(cellData.getNumberValue().doubleValue(), + cellData.getDataFormatData().getIndex(), cellData.getDataFormatData().getFormat(), globalConfiguration); } // Default conversion number return NumberUtils.format(cellData.getNumberValue(), contentProperty); } @Override - public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { - return new CellData<>(new BigDecimal(value)); + return new WriteCellData<>(new BigDecimal(value)); } } diff --git a/src/main/java/com/alibaba/excel/converters/string/StringStringConverter.java b/src/main/java/com/alibaba/excel/converters/string/StringStringConverter.java index 3b1ce3df..5edc6b16 100644 --- a/src/main/java/com/alibaba/excel/converters/string/StringStringConverter.java +++ b/src/main/java/com/alibaba/excel/converters/string/StringStringConverter.java @@ -2,8 +2,9 @@ package com.alibaba.excel.converters.string; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.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; /** @@ -23,15 +24,15 @@ public class StringStringConverter implements Converter { } @Override - public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, + public String convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getStringValue(); } @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); } } diff --git a/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java b/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java index a9e60df9..2aea00bf 100644 --- a/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java @@ -5,17 +5,16 @@ import java.io.InputStream; import java.net.URL; import com.alibaba.excel.converters.Converter; -import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; 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.IoUtils; /** * Url and image converter * - * @since 2.1.1 * @author Jiaju Zhuang + * @since 2.1.1 */ public class UrlImageConverter implements Converter { @Override @@ -24,24 +23,13 @@ public class UrlImageConverter implements Converter { } @Override - public CellDataTypeEnum supportExcelTypeKey() { - return CellDataTypeEnum.IMAGE; - } - - @Override - public URL convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, - GlobalConfiguration globalConfiguration) { - throw new UnsupportedOperationException("Cannot convert images to url."); - } - - @Override - public CellData convertToExcelData(URL value, ExcelContentProperty contentProperty, + public WriteCellData convertToExcelData(URL value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { InputStream inputStream = null; try { inputStream = value.openStream(); byte[] bytes = IoUtils.toByteArray(inputStream); - return new CellData<>(bytes); + return new WriteCellData<>(bytes); } finally { if (inputStream != null) { inputStream.close(); diff --git a/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java b/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java index a7a667f0..12f53d05 100644 --- a/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java +++ b/src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java @@ -37,11 +37,7 @@ public enum CellDataTypeEnum { */ ERROR, /** - * image. Support only when writing. - */ - IMAGE, - /** - * date.Support only when writing. + * date. Support only when writing. */ DATE, /** diff --git a/src/main/java/com/alibaba/excel/event/AbstractIgnoreExceptionReadListener.java b/src/main/java/com/alibaba/excel/event/AbstractIgnoreExceptionReadListener.java index 1e93397e..365336b7 100644 --- a/src/main/java/com/alibaba/excel/event/AbstractIgnoreExceptionReadListener.java +++ b/src/main/java/com/alibaba/excel/event/AbstractIgnoreExceptionReadListener.java @@ -8,7 +8,9 @@ import com.alibaba.excel.read.listener.ReadListener; * Receives the return of each piece of data parsed * * @author jipengfei + * @deprecated Use directly {@link ReadListener} */ +@Deprecated public abstract class AbstractIgnoreExceptionReadListener implements ReadListener { /** @@ -24,10 +26,8 @@ public abstract class AbstractIgnoreExceptionReadListener implements ReadList /** * The current method is called when extra information is returned * - * @param extra - * extra information - * @param context - * analysis context + * @param extra extra information + * @param context analysis context */ @Override public void extra(CellExtra extra, AnalysisContext context) {} diff --git a/src/main/java/com/alibaba/excel/event/AnalysisEventListener.java b/src/main/java/com/alibaba/excel/event/AnalysisEventListener.java index a0cd5078..bc94d75e 100644 --- a/src/main/java/com/alibaba/excel/event/AnalysisEventListener.java +++ b/src/main/java/com/alibaba/excel/event/AnalysisEventListener.java @@ -3,8 +3,8 @@ package com.alibaba.excel.event; import java.util.Map; import com.alibaba.excel.context.AnalysisContext; -import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.CellExtra; +import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.read.listener.ReadListener; import com.alibaba.excel.util.ConverterUtils; @@ -16,7 +16,7 @@ import com.alibaba.excel.util.ConverterUtils; public abstract class AnalysisEventListener implements ReadListener { @Override - public void invokeHead(Map> headMap, AnalysisContext context) { + public void invokeHead(Map> headMap, AnalysisContext context) { invokeHeadMap(ConverterUtils.convertToStringMap(headMap, context), context); } diff --git a/src/main/java/com/alibaba/excel/event/WriteHandler.java b/src/main/java/com/alibaba/excel/event/WriteHandler.java deleted file mode 100644 index 8c981ffc..00000000 --- a/src/main/java/com/alibaba/excel/event/WriteHandler.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.alibaba.excel.event; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; - -/** - * - * @author jipengfei - * @deprecated please use {@link com.alibaba.excel.write.handler.WriteHandler} - */ -@Deprecated -public interface WriteHandler { - - /** - * Custom operation after creating each sheet - * - * @param sheetNo - * @param sheet - */ - void sheet(int sheetNo, Sheet sheet); - - /** - * Custom operation after creating each row - * - * @param rowNum - * @param row - */ - void row(int rowNum, Row row); - - /** - * Custom operation after creating each cell - * - * @param cellNum - * @param cell - */ - void cell(int cellNum, Cell cell); -} diff --git a/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java b/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java index 3cd9077b..1cb9c934 100644 --- a/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java +++ b/src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java @@ -1,12 +1,10 @@ package com.alibaba.excel.exception; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.write.builder.ExcelWriterBuilder; import lombok.Data; -import lombok.Getter; -import lombok.Setter; /** * Data convert exception diff --git a/src/main/java/com/alibaba/excel/metadata/BaseRowModel.java b/src/main/java/com/alibaba/excel/metadata/BaseRowModel.java deleted file mode 100644 index 7df131e4..00000000 --- a/src/main/java/com/alibaba/excel/metadata/BaseRowModel.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.alibaba.excel.metadata; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.ss.usermodel.CellStyle; - -import com.alibaba.excel.annotation.ExcelIgnore; - -/** - * Excel基础模型 - * - * @author jipengfei - * @deprecated Now you don't need to extend any classes - */ -@Deprecated -public class BaseRowModel { - - /** - * 每列样式 - */ - @ExcelIgnore - private Map cellStyleMap = new HashMap(); - - public void addStyle(Integer row, CellStyle cellStyle) { - cellStyleMap.put(row, cellStyle); - } - - public CellStyle getStyle(Integer row) { - return cellStyleMap.get(row); - } - - public Map getCellStyleMap() { - return cellStyleMap; - } - - public void setCellStyleMap(Map cellStyleMap) { - this.cellStyleMap = cellStyleMap; - } -} diff --git a/src/main/java/com/alibaba/excel/metadata/BasicParameter.java b/src/main/java/com/alibaba/excel/metadata/BasicParameter.java index 5baf5cf5..f574f10e 100644 --- a/src/main/java/com/alibaba/excel/metadata/BasicParameter.java +++ b/src/main/java/com/alibaba/excel/metadata/BasicParameter.java @@ -5,11 +5,14 @@ import java.util.Locale; import com.alibaba.excel.converters.Converter; +import lombok.Data; + /** * Basic parameter * * @author Jiaju Zhuang **/ +@Data public class BasicParameter { /** * You can only choose one of the {@link BasicParameter#head} and {@link BasicParameter#clazz} @@ -18,11 +21,11 @@ public class BasicParameter { /** * You can only choose one of the {@link BasicParameter#head} and {@link BasicParameter#clazz} */ - private Class clazz; + private Class clazz; /** * Custom type conversions override the default */ - private List customConverterList; + private List> customConverterList; /** * Automatic trim includes sheet name and content */ @@ -47,60 +50,4 @@ public class BasicParameter { * default is false */ private Boolean useScientificFormat; - - public List> getHead() { - return head; - } - - public void setHead(List> head) { - this.head = head; - } - - public Class getClazz() { - return clazz; - } - - public void setClazz(Class clazz) { - this.clazz = clazz; - } - - public List getCustomConverterList() { - return customConverterList; - } - - public void setCustomConverterList(List customConverterList) { - this.customConverterList = customConverterList; - } - - public Boolean getAutoTrim() { - return autoTrim; - } - - public void setAutoTrim(Boolean autoTrim) { - this.autoTrim = autoTrim; - } - - public Boolean getUse1904windowing() { - return use1904windowing; - } - - public void setUse1904windowing(Boolean use1904windowing) { - this.use1904windowing = use1904windowing; - } - - public Locale getLocale() { - return locale; - } - - public void setLocale(Locale locale) { - this.locale = locale; - } - - public Boolean getUseScientificFormat() { - return useScientificFormat; - } - - public void setUseScientificFormat(Boolean useScientificFormat) { - this.useScientificFormat = useScientificFormat; - } } diff --git a/src/main/java/com/alibaba/excel/metadata/CellData.java b/src/main/java/com/alibaba/excel/metadata/CellData.java deleted file mode 100644 index 604df146..00000000 --- a/src/main/java/com/alibaba/excel/metadata/CellData.java +++ /dev/null @@ -1,193 +0,0 @@ -package com.alibaba.excel.metadata; - -import java.math.BigDecimal; -import java.util.Date; - -import com.alibaba.excel.annotation.write.style.ImagePosition; -import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.property.ImagePositionProperty; -import com.alibaba.excel.util.StringUtils; -import com.alibaba.excel.write.metadata.style.WriteCellStyle; - -import lombok.Data; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.ss.usermodel.RichTextString; - -/** - * Excel internal cell data. - * - *

- * - * @author Jiaju Zhuang - */ -@Data -public class CellData extends AbstractCell { - private CellDataTypeEnum type; - /** - * {@link CellDataTypeEnum#NUMBER} - */ - private BigDecimal numberValue; - /** - * {@link CellDataTypeEnum#STRING} and{@link CellDataTypeEnum#ERROR} - */ - private String stringValue; - /** - * {@link CellDataTypeEnum#BOOLEAN} - */ - private Boolean booleanValue; - - /** - * The resulting converted data. - */ - private T data; - - /** - * formula - */ - private FormulaData formulaData; - /** - * data format - */ - private DataFormat dataFormat; - - public CellData() {} - - public CellData(T data) { - this.data = data; - } - - public CellData(String stringValue) { - this(CellDataTypeEnum.STRING, stringValue); - } - - public CellData(CellDataTypeEnum type, String stringValue) { - if (type != CellDataTypeEnum.STRING && type != CellDataTypeEnum.ERROR) { - throw new IllegalArgumentException("Only support CellDataTypeEnum.STRING and CellDataTypeEnum.ERROR"); - } - if (stringValue == null) { - throw new IllegalArgumentException("StringValue can not be null"); - } - this.type = type; - this.stringValue = stringValue; - } - - public CellData(BigDecimal numberValue) { - if (numberValue == null) { - throw new IllegalArgumentException("DoubleValue can not be null"); - } - this.type = CellDataTypeEnum.NUMBER; - this.numberValue = numberValue; - } - - public CellData(byte[] imageValue) { - if (imageValue == null) { - throw new IllegalArgumentException("ImageValue can not be null"); - } - this.type = CellDataTypeEnum.IMAGE; - this.imageValue = imageValue; - } - - public CellData(byte[] imageValue, ImagePosition imagePosition) { - if (imageValue == null) { - throw new IllegalArgumentException("ImageValue can not be null"); - } - if (imagePosition == null) { - throw new IllegalArgumentException("ImagePosition can not be null"); - } - this.type = CellDataTypeEnum.IMAGE; - this.imageValue = imageValue; - this.imagePositionProperty = ImagePositionProperty.build(imagePosition); - this.useImagePositionProperty = true; - this.formula = Boolean.FALSE; - } - - public CellData(Boolean booleanValue) { - if (booleanValue == null) { - throw new IllegalArgumentException("BooleanValue can not be null"); - } - this.type = CellDataTypeEnum.BOOLEAN; - this.booleanValue = booleanValue; - } - - public CellData(Date dateValue) { - if (dateValue == null) { - throw new IllegalArgumentException("DateValue can not be null"); - } - this.type = CellDataTypeEnum.DATE; - this.dateValue = dateValue; - this.formula = Boolean.FALSE; - } - - public CellData(CellDataTypeEnum type) { - if (type == null) { - throw new IllegalArgumentException("Type can not be null"); - } - this.type = type; - } - - /** - * Ensure that the object does not appear null - */ - public void checkEmpty() { - if (type == null) { - type = CellDataTypeEnum.EMPTY; - } - switch (type) { - case STRING: - case ERROR: - if (StringUtils.isEmpty(stringValue)) { - type = CellDataTypeEnum.EMPTY; - } - return; - case NUMBER: - if (numberValue == null) { - type = CellDataTypeEnum.EMPTY; - } - return; - case BOOLEAN: - if (booleanValue == null) { - type = CellDataTypeEnum.EMPTY; - } - return; - default: - } - } - - public static CellData newEmptyInstance() { - return newEmptyInstance(null, null); - } - - public static CellData newEmptyInstance(Integer rowIndex, Integer columnIndex) { - CellData cellData = new CellData<>(CellDataTypeEnum.EMPTY); - cellData.setRowIndex(rowIndex); - cellData.setColumnIndex(columnIndex); - return cellData; - } - - public static CellData newInstance(Boolean booleanValue) { - return newInstance(booleanValue, null, null); - } - - public static CellData newInstance(Boolean booleanValue, Integer rowIndex, Integer columnIndex) { - CellData cellData = new CellData<>(booleanValue); - cellData.setRowIndex(rowIndex); - cellData.setColumnIndex(columnIndex); - return cellData; - } - - public static CellData newInstance(String stringValue, Integer rowIndex, Integer columnIndex) { - CellData cellData = new CellData<>(stringValue); - cellData.setRowIndex(rowIndex); - cellData.setColumnIndex(columnIndex); - return cellData; - } - - public static CellData newInstance(BigDecimal numberValue, Integer rowIndex, Integer columnIndex) { - CellData cellData = new CellData<>(numberValue); - cellData.setRowIndex(rowIndex); - cellData.setColumnIndex(columnIndex); - return cellData; - } - -} diff --git a/src/main/java/com/alibaba/excel/metadata/HyperlinkData.java b/src/main/java/com/alibaba/excel/metadata/HyperlinkData.java deleted file mode 100644 index f3453c64..00000000 --- a/src/main/java/com/alibaba/excel/metadata/HyperlinkData.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.alibaba.excel.metadata; - -/** - * TODO - * - * @author Jiaju Zhuang - */ -public class HyperlinkData { - -} diff --git a/src/main/java/com/alibaba/excel/metadata/ReadCellData.java b/src/main/java/com/alibaba/excel/metadata/ReadCellData.java deleted file mode 100644 index cf9ad233..00000000 --- a/src/main/java/com/alibaba/excel/metadata/ReadCellData.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.alibaba.excel.metadata; - -import lombok.Data; - -/** - * TODO - * - * @author Jiaju Zhuang - */ -@Data -public class ReadCellData extends CellData{ - -} diff --git a/src/main/java/com/alibaba/excel/metadata/Sheet.java b/src/main/java/com/alibaba/excel/metadata/Sheet.java deleted file mode 100644 index 38bd30af..00000000 --- a/src/main/java/com/alibaba/excel/metadata/Sheet.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.alibaba.excel.metadata; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * - * @author jipengfei - * @deprecated pleas use {@link com.alibaba.excel.write.metadata.WriteSheet} or - * {@link com.alibaba.excel.read.metadata.ReadSheet} - */ -@Deprecated -public class Sheet { - - /** - */ - private int headLineMun; - - /** - * Starting from 1 - */ - private int sheetNo; - - /** - */ - private String sheetName; - - /** - */ - private Class clazz; - - /** - */ - private List> head; - - /** - * - */ - private TableStyle tableStyle; - - /** - * column with - */ - private Map columnWidthMap = new HashMap(); - - /** - * - */ - private Boolean autoWidth = Boolean.FALSE; - - /** - * - */ - private int startRow = 0; - - public Sheet(int sheetNo) { - this.sheetNo = sheetNo; - } - - public Sheet(int sheetNo, int headLineMun) { - this.sheetNo = sheetNo; - this.headLineMun = headLineMun; - } - - public Sheet(int sheetNo, int headLineMun, Class clazz) { - this.sheetNo = sheetNo; - this.headLineMun = headLineMun; - this.clazz = clazz; - } - - public Sheet(int sheetNo, int headLineMun, Class clazz, String sheetName, - List> head) { - this.sheetNo = sheetNo; - this.clazz = clazz; - this.headLineMun = headLineMun; - this.sheetName = sheetName; - this.head = head; - } - - public List> getHead() { - return head; - } - - public void setHead(List> head) { - this.head = head; - } - - public Class getClazz() { - return clazz; - } - - public void setClazz(Class clazz) { - this.clazz = clazz; - if (headLineMun == 0) { - this.headLineMun = 1; - } - } - - public int getHeadLineMun() { - return headLineMun; - } - - public void setHeadLineMun(int headLineMun) { - this.headLineMun = headLineMun; - } - - public int getSheetNo() { - return sheetNo; - } - - public void setSheetNo(int sheetNo) { - this.sheetNo = sheetNo; - } - - public String getSheetName() { - return sheetName; - } - - public void setSheetName(String sheetName) { - this.sheetName = sheetName; - } - - public TableStyle getTableStyle() { - return tableStyle; - } - - public void setTableStyle(TableStyle tableStyle) { - this.tableStyle = tableStyle; - } - - public Map getColumnWidthMap() { - return columnWidthMap; - } - - public void setColumnWidthMap(Map columnWidthMap) { - this.columnWidthMap = columnWidthMap; - } - - @Override - public String toString() { - return "Sheet{" + "headLineMun=" + headLineMun + ", sheetNo=" + sheetNo + ", sheetName='" + sheetName + '\'' - + ", clazz=" + clazz + ", head=" + head + ", tableStyle=" + tableStyle + ", columnWidthMap=" - + columnWidthMap + '}'; - } - - public Boolean getAutoWidth() { - return autoWidth; - } - - public void setAutoWidth(Boolean autoWidth) { - this.autoWidth = autoWidth; - } - - public int getStartRow() { - return startRow; - } - - public void setStartRow(int startRow) { - this.startRow = startRow; - } -} diff --git a/src/main/java/com/alibaba/excel/metadata/Table.java b/src/main/java/com/alibaba/excel/metadata/Table.java deleted file mode 100644 index d4c63aba..00000000 --- a/src/main/java/com/alibaba/excel/metadata/Table.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.alibaba.excel.metadata; - -import java.util.List; - -/** - * @author jipengfei - * @deprecated please use {@link com.alibaba.excel.write.metadata.WriteTable} - */ -@Deprecated -public class Table { - /** - */ - private Class clazz; - - /** - */ - private List> head; - - /** - */ - private int tableNo; - - /** - */ - private TableStyle tableStyle; - - public Table(Integer tableNo) { - this.tableNo = tableNo; - } - - public TableStyle getTableStyle() { - return tableStyle; - } - - public void setTableStyle(TableStyle tableStyle) { - this.tableStyle = tableStyle; - } - - public Class getClazz() { - return clazz; - } - - public void setClazz(Class clazz) { - this.clazz = clazz; - } - - public List> getHead() { - return head; - } - - public void setHead(List> head) { - this.head = head; - } - - public int getTableNo() { - return tableNo; - } - - public void setTableNo(int tableNo) { - this.tableNo = tableNo; - } -} diff --git a/src/main/java/com/alibaba/excel/metadata/TableStyle.java b/src/main/java/com/alibaba/excel/metadata/TableStyle.java deleted file mode 100644 index fa8905c5..00000000 --- a/src/main/java/com/alibaba/excel/metadata/TableStyle.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.alibaba.excel.metadata; - -import org.apache.poi.ss.usermodel.IndexedColors; - -import com.alibaba.excel.write.style.HorizontalCellStyleStrategy; - -/** - * @author jipengfei - * @deprecated please use {@link HorizontalCellStyleStrategy} - */ -@Deprecated -public class TableStyle { - - /** - * 表头背景颜色 - */ - private IndexedColors tableHeadBackGroundColor; - - /** - * 表头字体样式 - */ - private Font tableHeadFont; - - /** - * 表格内容字体样式 - */ - private Font tableContentFont; - - /** - * 表格内容背景颜色 - */ - private IndexedColors tableContentBackGroundColor; - - public IndexedColors getTableHeadBackGroundColor() { - return tableHeadBackGroundColor; - } - - public void setTableHeadBackGroundColor(IndexedColors tableHeadBackGroundColor) { - this.tableHeadBackGroundColor = tableHeadBackGroundColor; - } - - public Font getTableHeadFont() { - return tableHeadFont; - } - - public void setTableHeadFont(Font tableHeadFont) { - this.tableHeadFont = tableHeadFont; - } - - public Font getTableContentFont() { - return tableContentFont; - } - - public void setTableContentFont(Font tableContentFont) { - this.tableContentFont = tableContentFont; - } - - public IndexedColors getTableContentBackGroundColor() { - return tableContentBackGroundColor; - } - - public void setTableContentBackGroundColor(IndexedColors tableContentBackGroundColor) { - this.tableContentBackGroundColor = tableContentBackGroundColor; - } -} diff --git a/src/main/java/com/alibaba/excel/metadata/WriteCellData.java b/src/main/java/com/alibaba/excel/metadata/WriteCellData.java deleted file mode 100644 index 901aa916..00000000 --- a/src/main/java/com/alibaba/excel/metadata/WriteCellData.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.alibaba.excel.metadata; - -import java.util.Date; - -import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.write.metadata.style.WriteCellStyle; - -import lombok.Data; - -/** - * TODO - * - * @author Jiaju Zhuang - */ -@Data -public class WriteCellData extends CellData { - /** - * Support only when writing.{@link CellDataTypeEnum#DATE} - */ - private Date dateValue; - /** - * {@link CellDataTypeEnum#IMAGE} - */ - private ImageData imageDataValue; - /** - * rich text.{@link CellDataTypeEnum#RICH_TEXT_STRING} - */ - private RichTextStringData richTextStringDataValue; - - /** - * comment - */ - private CommentData commentData; - /** - * hyper link - */ - private HyperlinkData hyperlinkData; - /** - * sytle - */ - private WriteCellStyle writeCellStyle; -} diff --git a/src/main/java/com/alibaba/excel/metadata/data/CellData.java b/src/main/java/com/alibaba/excel/metadata/data/CellData.java new file mode 100644 index 00000000..ed6085f9 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/data/CellData.java @@ -0,0 +1,76 @@ +package com.alibaba.excel.metadata.data; + +import java.math.BigDecimal; + +import com.alibaba.excel.enums.CellDataTypeEnum; +import com.alibaba.excel.metadata.AbstractCell; +import com.alibaba.excel.util.StringUtils; + +import lombok.Data; + +/** + * Excel internal cell data. + * + *

+ * + * @author Jiaju Zhuang + */ +@Data +public class CellData extends AbstractCell { + /** + * cell type + */ + private CellDataTypeEnum type; + /** + * {@link CellDataTypeEnum#NUMBER} + */ + private BigDecimal numberValue; + /** + * {@link CellDataTypeEnum#STRING} and{@link CellDataTypeEnum#ERROR} + */ + private String stringValue; + /** + * {@link CellDataTypeEnum#BOOLEAN} + */ + private Boolean booleanValue; + + /** + * The resulting converted data. + */ + private T data; + + /** + * formula + */ + private FormulaData formulaData; + + /** + * Ensure that the object does not appear null + */ + public void checkEmpty() { + if (type == null) { + type = CellDataTypeEnum.EMPTY; + } + switch (type) { + case STRING: + case ERROR: + if (StringUtils.isEmpty(stringValue)) { + type = CellDataTypeEnum.EMPTY; + } + return; + case NUMBER: + if (numberValue == null) { + type = CellDataTypeEnum.EMPTY; + } + return; + case BOOLEAN: + if (booleanValue == null) { + type = CellDataTypeEnum.EMPTY; + } + return; + default: + } + } + + +} diff --git a/src/main/java/com/alibaba/excel/metadata/ClientAnchorData.java b/src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java similarity index 84% rename from src/main/java/com/alibaba/excel/metadata/ClientAnchorData.java rename to src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java index cf215e6f..b240eb97 100644 --- a/src/main/java/com/alibaba/excel/metadata/ClientAnchorData.java +++ b/src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java @@ -1,4 +1,4 @@ -package com.alibaba.excel.metadata; +package com.alibaba.excel.metadata.data; import lombok.Data; import org.apache.poi.ss.usermodel.ClientAnchor; @@ -21,47 +21,27 @@ import org.apache.poi.util.Internal; * @author Jiaju Zhuang */ @Data -public class ClientAnchorData { - - /** - * The x coordinate within the first cell. - */ - private int dx1; - - /** - * The y coordinate within the first cell. - */ - private int dy1; - - /** - * The x coordinate within the second cell. - */ - private int dx2; - +public class ClientAnchorData extends CoordinateData { /** - * The y coordinate within the second cell + * top */ - private int dy2; + private Integer top; /** - * 0-based column of the first cell. + * right */ - private short col1; + private Integer right; /** - * 0-based row of the first cell. + * bottom */ - private int row1; + private Integer bottom; /** - * 0-based column of the second cell. + * left */ - private short col2; + private Integer left; - /** - * 0-based row of the second cell. - */ - private int row2; /** * anchor type */ diff --git a/src/main/java/com/alibaba/excel/metadata/CommentData.java b/src/main/java/com/alibaba/excel/metadata/data/CommentData.java similarity index 88% rename from src/main/java/com/alibaba/excel/metadata/CommentData.java rename to src/main/java/com/alibaba/excel/metadata/data/CommentData.java index 94c1b675..6f86a3e3 100644 --- a/src/main/java/com/alibaba/excel/metadata/CommentData.java +++ b/src/main/java/com/alibaba/excel/metadata/data/CommentData.java @@ -1,9 +1,9 @@ -package com.alibaba.excel.metadata; +package com.alibaba.excel.metadata.data; import lombok.Data; /** - * TODO + * comment * * @author Jiaju Zhuang */ diff --git a/src/main/java/com/alibaba/excel/metadata/data/CoordinateData.java b/src/main/java/com/alibaba/excel/metadata/data/CoordinateData.java new file mode 100644 index 00000000..c9b73ffb --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/data/CoordinateData.java @@ -0,0 +1,28 @@ +package com.alibaba.excel.metadata.data; + +import lombok.Data; + +/** + * coordinate. + * + * @author Jiaju Zhuang + */ +@Data +public class CoordinateData { + /** + * first row index + */ + private Integer firstRowIndex; + /** + * first column index + */ + private Integer firstColumnIndex; + /** + * last row index + */ + private Integer lastRowIndex; + /** + * last column index + */ + private Integer lastColumnIndex; +} diff --git a/src/main/java/com/alibaba/excel/metadata/DataFormat.java b/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java similarity index 72% rename from src/main/java/com/alibaba/excel/metadata/DataFormat.java rename to src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java index fdaa5236..3ac70781 100644 --- a/src/main/java/com/alibaba/excel/metadata/DataFormat.java +++ b/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java @@ -1,4 +1,4 @@ -package com.alibaba.excel.metadata; +package com.alibaba.excel.metadata.data; import lombok.Data; @@ -8,11 +8,12 @@ import lombok.Data; * @author Jiaju Zhuang */ @Data -public class DataFormat { +public class DataFormatData { /** * index */ private Short index; + /** * format */ diff --git a/src/main/java/com/alibaba/excel/metadata/FormulaData.java b/src/main/java/com/alibaba/excel/metadata/data/FormulaData.java similarity index 80% rename from src/main/java/com/alibaba/excel/metadata/FormulaData.java rename to src/main/java/com/alibaba/excel/metadata/data/FormulaData.java index 8f3c4f15..cdf91055 100644 --- a/src/main/java/com/alibaba/excel/metadata/FormulaData.java +++ b/src/main/java/com/alibaba/excel/metadata/data/FormulaData.java @@ -1,4 +1,4 @@ -package com.alibaba.excel.metadata; +package com.alibaba.excel.metadata.data; import lombok.Data; diff --git a/src/main/java/com/alibaba/excel/metadata/data/HyperlinkData.java b/src/main/java/com/alibaba/excel/metadata/data/HyperlinkData.java new file mode 100644 index 00000000..c38d7dd6 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/data/HyperlinkData.java @@ -0,0 +1,53 @@ +package com.alibaba.excel.metadata.data; + +import lombok.Data; + +/** + * hyperlink + * + * @author Jiaju Zhuang + */ +@Data +public class HyperlinkData extends CoordinateData { + /** + * Depending on the hyperlink type it can be URL, e-mail, path to a file, etc + */ + private String address; + /** + * hyperlink type + */ + private HyperlinkType hyperlinkType; + + public enum HyperlinkType { + /** + * Not a hyperlink + */ + NONE(-1), + + /** + * Link to an existing file or web page + */ + URL(1), + + /** + * Link to a place in this document + */ + DOCUMENT(2), + + /** + * Link to an E-mail address + */ + EMAIL(3), + + /** + * Link to a file + */ + FILE(4); + + public final int value; + + HyperlinkType(int value) { + this.value = value; + } + } +} diff --git a/src/main/java/com/alibaba/excel/metadata/ImageData.java b/src/main/java/com/alibaba/excel/metadata/data/ImageData.java similarity index 95% rename from src/main/java/com/alibaba/excel/metadata/ImageData.java rename to src/main/java/com/alibaba/excel/metadata/data/ImageData.java index e1bb30fa..48276db3 100644 --- a/src/main/java/com/alibaba/excel/metadata/ImageData.java +++ b/src/main/java/com/alibaba/excel/metadata/data/ImageData.java @@ -1,4 +1,4 @@ -package com.alibaba.excel.metadata; +package com.alibaba.excel.metadata.data; import lombok.Data; diff --git a/src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java b/src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java new file mode 100644 index 00000000..462cbac7 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java @@ -0,0 +1,111 @@ +package com.alibaba.excel.metadata.data; + +import java.math.BigDecimal; + +import com.alibaba.excel.enums.CellDataTypeEnum; + +import lombok.Data; + +/** + * read cell data + * + * @author Jiaju Zhuang + */ +@Data +public class ReadCellData extends CellData { + /** + * data format. + */ + private DataFormatData dataFormatData; + + + public ReadCellData(CellDataTypeEnum type) { + super(); + if (type == null) { + throw new IllegalArgumentException("Type can not be null"); + } + setType(type); + } + + public ReadCellData(T data) { + super(); + setData(data); + } + + public ReadCellData(String stringValue) { + this(CellDataTypeEnum.STRING, stringValue); + } + + public ReadCellData(CellDataTypeEnum type, String stringValue) { + super(); + if (type != CellDataTypeEnum.STRING && type != CellDataTypeEnum.ERROR) { + throw new IllegalArgumentException("Only support CellDataTypeEnum.STRING and CellDataTypeEnum.ERROR"); + } + if (stringValue == null) { + throw new IllegalArgumentException("StringValue can not be null"); + } + setType(type); + setStringValue(stringValue); + } + + public ReadCellData(BigDecimal numberValue) { + super(); + if (numberValue == null) { + throw new IllegalArgumentException("DoubleValue can not be null"); + } + setType(CellDataTypeEnum.NUMBER); + setNumberValue(numberValue); + } + + public ReadCellData(Boolean booleanValue) { + super(); + if (booleanValue == null) { + throw new IllegalArgumentException("BooleanValue can not be null"); + } + setType(CellDataTypeEnum.BOOLEAN); + setBooleanValue(booleanValue); + } + + public static ReadCellData newEmptyInstance() { + return newEmptyInstance(null, null); + } + + public static ReadCellData newEmptyInstance(Integer rowIndex, Integer columnIndex) { + ReadCellData cellData = new ReadCellData<>(CellDataTypeEnum.EMPTY); + cellData.setRowIndex(rowIndex); + cellData.setColumnIndex(columnIndex); + return cellData; + } + + public static ReadCellData newInstance(Boolean booleanValue) { + return newInstance(booleanValue, null, null); + } + + public static ReadCellData newInstance(Boolean booleanValue, Integer rowIndex, Integer columnIndex) { + ReadCellData cellData = new ReadCellData<>(booleanValue); + cellData.setRowIndex(rowIndex); + cellData.setColumnIndex(columnIndex); + return cellData; + } + + public static ReadCellData newInstance(String stringValue, Integer rowIndex, Integer columnIndex) { + ReadCellData cellData = new ReadCellData<>(stringValue); + cellData.setRowIndex(rowIndex); + cellData.setColumnIndex(columnIndex); + return cellData; + } + + public static ReadCellData newInstance(BigDecimal numberValue, Integer rowIndex, Integer columnIndex) { + ReadCellData cellData = new ReadCellData<>(numberValue); + cellData.setRowIndex(rowIndex); + cellData.setColumnIndex(columnIndex); + return cellData; + } + + + @Override + public ReadCellData clone(){ + return new ReadCellData<>(""); + } + +} diff --git a/src/main/java/com/alibaba/excel/metadata/RichTextStringData.java b/src/main/java/com/alibaba/excel/metadata/data/RichTextStringData.java similarity index 97% rename from src/main/java/com/alibaba/excel/metadata/RichTextStringData.java rename to src/main/java/com/alibaba/excel/metadata/data/RichTextStringData.java index eabb85c3..4b8a0420 100644 --- a/src/main/java/com/alibaba/excel/metadata/RichTextStringData.java +++ b/src/main/java/com/alibaba/excel/metadata/data/RichTextStringData.java @@ -1,4 +1,4 @@ -package com.alibaba.excel.metadata; +package com.alibaba.excel.metadata.data; import java.util.List; diff --git a/src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java b/src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java new file mode 100644 index 00000000..3f1de9be --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java @@ -0,0 +1,101 @@ +package com.alibaba.excel.metadata.data; + +import java.math.BigDecimal; +import java.util.Date; +import java.util.List; + +import com.alibaba.excel.enums.CellDataTypeEnum; +import com.alibaba.excel.util.ListUtils; +import com.alibaba.excel.write.metadata.style.WriteCellStyle; + +import lombok.Data; + +/** + * wirte cell data + * + * @author Jiaju Zhuang + */ +@Data +public class WriteCellData extends CellData { + /** + * Support only when writing.{@link CellDataTypeEnum#DATE} + */ + private Date dateValue; + /** + * rich text.{@link CellDataTypeEnum#RICH_TEXT_STRING} + */ + private RichTextStringData richTextStringDataValue; + /** + * image + */ + private List imageDataList; + /** + * comment + */ + private CommentData commentData; + /** + * hyper link + */ + private HyperlinkData hyperlinkData; + /** + * sytle + */ + private WriteCellStyle writeCellStyle; + + + public WriteCellData(String stringValue) { + this(CellDataTypeEnum.STRING, stringValue); + } + + public WriteCellData(CellDataTypeEnum type, String stringValue) { + super(); + if (type != CellDataTypeEnum.STRING && type != CellDataTypeEnum.ERROR) { + throw new IllegalArgumentException("Only support CellDataTypeEnum.STRING and CellDataTypeEnum.ERROR"); + } + if (stringValue == null) { + throw new IllegalArgumentException("StringValue can not be null"); + } + setType(type); + setStringValue(stringValue); + } + + public WriteCellData(BigDecimal numberValue) { + super(); + if (numberValue == null) { + throw new IllegalArgumentException("DoubleValue can not be null"); + } + setType(CellDataTypeEnum.NUMBER); + setNumberValue(numberValue); + } + + public WriteCellData(Boolean booleanValue) { + super(); + if (booleanValue == null) { + throw new IllegalArgumentException("BooleanValue can not be null"); + } + setType(CellDataTypeEnum.BOOLEAN); + setBooleanValue(booleanValue); + } + + public WriteCellData(Date dateValue) { + super(); + if (dateValue == null) { + throw new IllegalArgumentException("DateValue can not be null"); + } + setType(CellDataTypeEnum.DATE); + this.dateValue = dateValue; + } + + public WriteCellData(byte[] image) { + super(); + if (image == null) { + throw new IllegalArgumentException("Image can not be null"); + } + setType(CellDataTypeEnum.EMPTY); + this.imageDataList= ListUtils.newArrayList(); + ImageData imageData = new ImageData(); + imageData.setImage(image); + imageDataList.add(imageData); + } + +} diff --git a/src/main/java/com/alibaba/excel/parameter/AnalysisParam.java b/src/main/java/com/alibaba/excel/parameter/AnalysisParam.java deleted file mode 100644 index f8679ac0..00000000 --- a/src/main/java/com/alibaba/excel/parameter/AnalysisParam.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.alibaba.excel.parameter; - -import com.alibaba.excel.support.ExcelTypeEnum; - -import java.io.InputStream; - -/** - * - * @author jipengfei - */ -@Deprecated -public class AnalysisParam { - - /** - * @see ExcelTypeEnum - */ - private ExcelTypeEnum excelTypeEnum; - - /** - * the POI filesystem that contains the Workbook stream - */ - private InputStream in; - - /** - * user defined param to listener use - */ - private Object customContent; - - public AnalysisParam(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent) { - this.in = in; - this.excelTypeEnum = excelTypeEnum; - this.customContent = customContent; - } - - public ExcelTypeEnum getExcelTypeEnum() { - return excelTypeEnum; - } - - public void setExcelTypeEnum(ExcelTypeEnum excelTypeEnum) { - this.excelTypeEnum = excelTypeEnum; - } - - public Object getCustomContent() { - return customContent; - } - - public void setCustomContent(Object customContent) { - this.customContent = customContent; - } - - public InputStream getIn() { - return in; - } - - public void setIn(InputStream in) { - this.in = in; - } -} diff --git a/src/main/java/com/alibaba/excel/parameter/GenerateParam.java b/src/main/java/com/alibaba/excel/parameter/GenerateParam.java deleted file mode 100644 index acbcfbde..00000000 --- a/src/main/java/com/alibaba/excel/parameter/GenerateParam.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.alibaba.excel.parameter; - -import java.io.OutputStream; - -import com.alibaba.excel.support.ExcelTypeEnum; - -/** - * Created by jipengfei on 17/2/19. - * - * @author jipengfei - * @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter - */ -@Deprecated -public class GenerateParam { - - private OutputStream outputStream; - - private String sheetName; - - private Class clazz; - - private ExcelTypeEnum type; - - private boolean needHead = true; - - public GenerateParam(String sheetName, Class clazz, OutputStream outputStream) { - this.outputStream = outputStream; - this.sheetName = sheetName; - this.clazz = clazz; - } - - public OutputStream getOutputStream() { - return outputStream; - } - - public void setOutputStream(OutputStream outputStream) { - this.outputStream = outputStream; - } - - public String getSheetName() { - return sheetName; - } - - public void setSheetName(String sheetName) { - this.sheetName = sheetName; - } - - public Class getClazz() { - return clazz; - } - - public void setClazz(Class clazz) { - this.clazz = clazz; - } - - public ExcelTypeEnum getType() { - return type; - } - - public void setType(ExcelTypeEnum type) { - this.type = type; - } - - public boolean isNeedHead() { - return needHead; - } - - public void setNeedHead(boolean needHead) { - this.needHead = needHead; - } -} diff --git a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java index 13e3d45b..9feb1515 100644 --- a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java +++ b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java @@ -1,23 +1,21 @@ package com.alibaba.excel.read.listener; import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.HeadKindEnum; -import com.alibaba.excel.event.AbstractIgnoreExceptionReadListener; import com.alibaba.excel.exception.ExcelDataConvertException; -import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.Head; +import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty; import com.alibaba.excel.util.ConverterUtils; import com.alibaba.excel.util.FieldUtils; +import com.alibaba.excel.util.MapUtils; import net.sf.cglib.beans.BeanMap; @@ -26,13 +24,13 @@ import net.sf.cglib.beans.BeanMap; * * @author jipengfei */ -public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener>> { +public class ModelBuildEventListener implements ReadListener>> { @Override - public void invokeHead(Map> cellDataMap, AnalysisContext context) {} + public void invokeHead(Map> cellDataMap, AnalysisContext context) {} @Override - public void invoke(Map> cellDataMap, AnalysisContext context) { + public void invoke(Map> cellDataMap, AnalysisContext context) { ReadSheetHolder readSheetHolder = context.readSheetHolder(); if (HeadKindEnum.CLASS.equals(readSheetHolder.excelReadHeadProperty().getHeadKind())) { context.readRowHolder() @@ -42,14 +40,14 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener context.readRowHolder().setCurrentRowAnalysisResult(buildStringList(cellDataMap, readSheetHolder, context)); } - private Object buildStringList(Map> cellDataMap, ReadSheetHolder readSheetHolder, + private Object buildStringList(Map> cellDataMap, ReadSheetHolder readSheetHolder, AnalysisContext context) { int index = 0; if (context.readWorkbookHolder().getDefaultReturnMap()) { - Map map = new LinkedHashMap(cellDataMap.size() * 4 / 3 + 1); - for (Map.Entry> entry : cellDataMap.entrySet()) { + Map map = MapUtils.newLinkedHashMapWithExpectedSize(cellDataMap.size()); + for (Map.Entry> entry : cellDataMap.entrySet()) { Integer key = entry.getKey(); - CellData cellData = entry.getValue(); + ReadCellData cellData = entry.getValue(); while (index < key) { map.put(index, null); index++; @@ -61,7 +59,7 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener } map.put(key, (String)ConverterUtils.convertToJavaObject(cellData, null, null, readSheetHolder.converterMap(), - readSheetHolder, context.readRowHolder().getRowIndex(), key)); + context, context.readRowHolder().getRowIndex(), key)); } int headSize = readSheetHolder.excelReadHeadProperty().getHeadMap().size(); while (index < headSize) { @@ -72,9 +70,9 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener } else { // Compatible with the old code the old code returns a list List list = new ArrayList<>(); - for (Map.Entry> entry : cellDataMap.entrySet()) { + for (Map.Entry> entry : cellDataMap.entrySet()) { Integer key = entry.getKey(); - CellData cellData = entry.getValue(); + ReadCellData cellData = entry.getValue(); while (index < key) { list.add(null); index++; @@ -86,7 +84,7 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener } list.add( (String)ConverterUtils.convertToJavaObject(cellData, null, null, readSheetHolder.converterMap(), - readSheetHolder, context.readRowHolder().getRowIndex(), key)); + context, context.readRowHolder().getRowIndex(), key)); } int headSize = readSheetHolder.excelReadHeadProperty().getHeadMap().size(); while (index < headSize) { @@ -97,7 +95,7 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener } } - private Object buildUserModel(Map> cellDataMap, ReadSheetHolder readSheetHolder, + private Object buildUserModel(Map> cellDataMap, ReadSheetHolder readSheetHolder, AnalysisContext context) { ExcelReadHeadProperty excelReadHeadProperty = readSheetHolder.excelReadHeadProperty(); Object resultModel; @@ -105,24 +103,24 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener resultModel = excelReadHeadProperty.getHeadClazz().newInstance(); } catch (Exception e) { throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), 0, - new CellData<>(CellDataTypeEnum.EMPTY), null, + new ReadCellData<>(CellDataTypeEnum.EMPTY), null, "Can not instance class: " + excelReadHeadProperty.getHeadClazz().getName(), e); } Map headMap = excelReadHeadProperty.getHeadMap(); - Map map = new HashMap(headMap.size() * 4 / 3 + 1); + Map map = MapUtils.newHashMapWithExpectedSize(headMap.size()); Map contentPropertyMap = excelReadHeadProperty.getContentPropertyMap(); for (Map.Entry entry : headMap.entrySet()) { Integer index = entry.getKey(); if (!cellDataMap.containsKey(index)) { continue; } - CellData cellData = cellDataMap.get(index); + ReadCellData cellData = cellDataMap.get(index); if (cellData.getType() == CellDataTypeEnum.EMPTY) { continue; } ExcelContentProperty excelContentProperty = contentPropertyMap.get(index); Object value = ConverterUtils.convertToJavaObject(cellData, excelContentProperty.getField(), - excelContentProperty, readSheetHolder.converterMap(), readSheetHolder, + excelContentProperty, readSheetHolder.converterMap(), context, context.readRowHolder().getRowIndex(), index); if (value != null) { map.put(FieldUtils.resolveCglibFieldName(excelContentProperty.getField()), value); diff --git a/src/main/java/com/alibaba/excel/read/listener/ReadListener.java b/src/main/java/com/alibaba/excel/read/listener/ReadListener.java index b3a2e970..d951d1a6 100644 --- a/src/main/java/com/alibaba/excel/read/listener/ReadListener.java +++ b/src/main/java/com/alibaba/excel/read/listener/ReadListener.java @@ -4,8 +4,8 @@ import java.util.Map; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.Listener; -import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.CellExtra; +import com.alibaba.excel.metadata.data.ReadCellData; /** * Interface to listen for read results @@ -21,7 +21,7 @@ public interface ReadListener extends Listener { * @param context * @throws Exception */ - void onException(Exception exception, AnalysisContext context) throws Exception; + default void onException(Exception exception, AnalysisContext context) throws Exception {} /** * When analysis one head row trigger invoke function. @@ -29,27 +29,23 @@ public interface ReadListener extends Listener { * @param headMap * @param context */ - void invokeHead(Map> headMap, AnalysisContext context); + default void invokeHead(Map> headMap, AnalysisContext context) {} /** * When analysis one row trigger invoke function. * - * @param data - * one row value. Is is same as {@link AnalysisContext#readRowHolder()} - * @param context - * analysis context + * @param data one row value. Is is same as {@link AnalysisContext#readRowHolder()} + * @param context analysis context */ void invoke(T data, AnalysisContext context); /** * The current method is called when extra information is returned * - * @param extra - * extra information - * @param context - * analysis context + * @param extra extra information + * @param context analysis context */ - void extra(CellExtra extra, AnalysisContext context); + default void extra(CellExtra extra, AnalysisContext context) {} /** * if have something to do after all analysis @@ -64,5 +60,7 @@ public interface ReadListener extends Listener { * @param context * @return */ - boolean hasNext(AnalysisContext context); + default boolean hasNext(AnalysisContext context) { + return true; + } } diff --git a/src/main/java/com/alibaba/excel/read/metadata/ReadBasicParameter.java b/src/main/java/com/alibaba/excel/read/metadata/ReadBasicParameter.java index d4035873..b5d17cbe 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/ReadBasicParameter.java +++ b/src/main/java/com/alibaba/excel/read/metadata/ReadBasicParameter.java @@ -6,11 +6,14 @@ import java.util.List; import com.alibaba.excel.metadata.BasicParameter; import com.alibaba.excel.read.listener.ReadListener; +import lombok.Data; + /** * Read basic parameter * * @author Jiaju Zhuang **/ +@Data public class ReadBasicParameter extends BasicParameter { /** * Count the number of added heads when read sheet. @@ -26,21 +29,9 @@ public class ReadBasicParameter extends BasicParameter { /** * Custom type listener run after default */ - private List customReadListenerList = new ArrayList(); - - public Integer getHeadRowNumber() { - return headRowNumber; - } - - public void setHeadRowNumber(Integer headRowNumber) { - this.headRowNumber = headRowNumber; - } - - public List getCustomReadListenerList() { - return customReadListenerList; - } + private List> customReadListenerList; - public void setCustomReadListenerList(List customReadListenerList) { - this.customReadListenerList = customReadListenerList; + public ReadBasicParameter() { + customReadListenerList = new ArrayList<>(); } } diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java index 396fa55a..641b489f 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java @@ -42,7 +42,7 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH /** * Read listener */ - private List readListenerList; + private List> readListenerList; public AbstractReadHolder(ReadBasicParameter readBasicParameter, AbstractReadHolder parentAbstractReadHolder, Boolean convertAllFiled) { @@ -114,7 +114,7 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH @Override - public List readListenerList() { + public List> readListenerList() { return getReadListenerList(); } diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadHolder.java index 43e13013..32ac6ee9 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadHolder.java @@ -18,7 +18,7 @@ public interface ReadHolder extends ConfigurationHolder { * * @return Current {@link ReadListener} */ - List readListenerList(); + List> readListenerList(); /** * What {@link ExcelReadHeadProperty} does the currently operated cell need to execute diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java index ddb5ca27..12cd7233 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java @@ -5,15 +5,18 @@ import java.util.Map; import com.alibaba.excel.enums.HolderEnum; import com.alibaba.excel.metadata.Cell; -import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.CellExtra; +import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.read.metadata.ReadSheet; +import lombok.Data; + /** * sheet holder * * @author Jiaju Zhuang */ +@Data public class ReadSheetHolder extends AbstractReadHolder { /** @@ -51,7 +54,7 @@ public class ReadSheetHolder extends AbstractReadHolder { /** * Current CellData */ - private CellData tempCellData; + private ReadCellData tempCellData; public ReadSheetHolder(ReadSheet readSheet, ReadWorkbookHolder readWorkbookHolder) { super(readSheet, readWorkbookHolder, readWorkbookHolder.getReadWorkbook().getConvertAllFiled()); @@ -59,42 +62,10 @@ public class ReadSheetHolder extends AbstractReadHolder { this.parentReadWorkbookHolder = readWorkbookHolder; this.sheetNo = readSheet.getSheetNo(); this.sheetName = readSheet.getSheetName(); - this.cellMap = new LinkedHashMap(); + this.cellMap = new LinkedHashMap<>(); this.rowIndex = -1; } - public ReadSheet getReadSheet() { - return readSheet; - } - - public void setReadSheet(ReadSheet readSheet) { - this.readSheet = readSheet; - } - - public ReadWorkbookHolder getParentReadWorkbookHolder() { - return parentReadWorkbookHolder; - } - - public void setParentReadWorkbookHolder(ReadWorkbookHolder parentReadWorkbookHolder) { - this.parentReadWorkbookHolder = parentReadWorkbookHolder; - } - - public Integer getSheetNo() { - return sheetNo; - } - - public void setSheetNo(Integer sheetNo) { - this.sheetNo = sheetNo; - } - - public String getSheetName() { - return sheetName; - } - - public void setSheetName(String sheetName) { - this.sheetName = sheetName; - } - /** * Approximate total number of rows * @@ -106,58 +77,9 @@ public class ReadSheetHolder extends AbstractReadHolder { return approximateTotalRowNumber; } - /** - * Approximate total number of rows - * - * @return - */ - public Integer getApproximateTotalRowNumber() { - return approximateTotalRowNumber; - } - - public void setApproximateTotalRowNumber(Integer approximateTotalRowNumber) { - this.approximateTotalRowNumber = approximateTotalRowNumber; - } - - public Map getCellMap() { - return cellMap; - } - - public void setCellMap(Map cellMap) { - this.cellMap = cellMap; - } - - public Integer getRowIndex() { - return rowIndex; - } - - public void setRowIndex(Integer rowIndex) { - this.rowIndex = rowIndex; - } - - public CellData getTempCellData() { - return tempCellData; - } - - public void setTempCellData(CellData tempCellData) { - this.tempCellData = tempCellData; - } - - public CellExtra getCellExtra() { - return cellExtra; - } - - public void setCellExtra(CellExtra cellExtra) { - this.cellExtra = cellExtra; - } - @Override public HolderEnum holderType() { return HolderEnum.SHEET; } - @Override - public String toString() { - return "ReadSheetHolder{" + "sheetNo=" + sheetNo + ", sheetName='" + sheetName + '\'' + "} " + super.toString(); - } } diff --git a/src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java b/src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java index f23f58c9..ab2e69de 100644 --- a/src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java +++ b/src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java @@ -12,7 +12,7 @@ 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.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.read.listener.ReadListener; diff --git a/src/main/java/com/alibaba/excel/util/ClassUtils.java b/src/main/java/com/alibaba/excel/util/ClassUtils.java index 16643de4..45df3846 100644 --- a/src/main/java/com/alibaba/excel/util/ClassUtils.java +++ b/src/main/java/com/alibaba/excel/util/ClassUtils.java @@ -16,11 +16,8 @@ import java.util.concurrent.ConcurrentHashMap; import com.alibaba.excel.annotation.ExcelIgnore; import com.alibaba.excel.annotation.ExcelIgnoreUnannotated; import com.alibaba.excel.annotation.ExcelProperty; -import com.alibaba.excel.event.Handler; import com.alibaba.excel.exception.ExcelCommonException; -import com.alibaba.excel.metadata.BaseRowModel; import com.alibaba.excel.metadata.Holder; -import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.metadata.holder.WriteHolder; /** diff --git a/src/main/java/com/alibaba/excel/util/ConverterUtils.java b/src/main/java/com/alibaba/excel/util/ConverterUtils.java index 61f69ac4..029c8196 100644 --- a/src/main/java/com/alibaba/excel/util/ConverterUtils.java +++ b/src/main/java/com/alibaba/excel/util/ConverterUtils.java @@ -8,11 +8,12 @@ import java.util.Map; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.ConverterKeyBuild; +import com.alibaba.excel.converters.ReadConverterContext; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.exception.ExcelDataConvertException; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; +import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; -import com.alibaba.excel.read.metadata.holder.ReadHolder; import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; /** @@ -31,13 +32,14 @@ public class ConverterUtils { * @param context * @return */ - public static Map convertToStringMap(Map> cellDataMap, AnalysisContext context) { + public static Map convertToStringMap(Map> cellDataMap, + AnalysisContext context) { Map stringMap = MapUtils.newHashMapWithExpectedSize(cellDataMap.size()); ReadSheetHolder readSheetHolder = context.readSheetHolder(); int index = 0; - for (Map.Entry> entry : cellDataMap.entrySet()) { + for (Map.Entry> entry : cellDataMap.entrySet()) { Integer key = entry.getKey(); - CellData cellData = entry.getValue(); + ReadCellData cellData = entry.getValue(); while (index < key) { stringMap.put(index, null); index++; @@ -55,7 +57,7 @@ public class ConverterUtils { } try { stringMap.put(key, - (String)(converter.convertToJavaData(cellData, null, readSheetHolder))); + (String)(converter.convertToJavaData(new ReadConverterContext<>(cellData, null, context)))); } catch (Exception e) { throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), key, cellData, null, "Convert data " + cellData + " to String error ", e); @@ -71,14 +73,14 @@ public class ConverterUtils { * @param field * @param contentProperty * @param converterMap - * @param readSheetHolder + * @param context * @param rowIndex * @param columnIndex * @return */ - public static Object convertToJavaObject(CellData cellData, Field field, ExcelContentProperty contentProperty, - Map> converterMap, ReadSheetHolder readSheetHolder, Integer rowIndex, - Integer columnIndex) { + public static Object convertToJavaObject(ReadCellData cellData, Field field, + ExcelContentProperty contentProperty, Map> converterMap, AnalysisContext context, + Integer rowIndex, Integer columnIndex) { Class clazz; if (field == null) { clazz = String.class; @@ -94,12 +96,13 @@ public class ConverterUtils { } else { classGeneric = String.class; } - CellData cellDataReturn = new CellData(cellData); + + ReadCellData cellDataReturn = cellData.clone(); cellDataReturn.setData(doConvertToJavaObject(cellData, classGeneric, contentProperty, converterMap, - readSheetHolder, rowIndex, columnIndex)); + context, rowIndex, columnIndex)); return cellDataReturn; } - return doConvertToJavaObject(cellData, clazz, contentProperty, converterMap, readSheetHolder, rowIndex, + return doConvertToJavaObject(cellData, clazz, contentProperty, converterMap, context, rowIndex, columnIndex); } @@ -108,15 +111,14 @@ public class ConverterUtils { * @param clazz * @param contentProperty * @param converterMap - * @param readSheetHolder + * @param context * @param rowIndex * @param columnIndex * @return */ - private static Object doConvertToJavaObject(CellData cellData, Class clazz, - ExcelContentProperty contentProperty, - Map> converterMap, ReadSheetHolder readSheetHolder, Integer rowIndex, - Integer columnIndex) { + private static Object doConvertToJavaObject(ReadCellData cellData, Class clazz, + ExcelContentProperty contentProperty, Map> converterMap, AnalysisContext context, + Integer rowIndex, Integer columnIndex) { Converter converter = null; if (contentProperty != null) { converter = contentProperty.getConverter(); @@ -129,7 +131,7 @@ public class ConverterUtils { "Converter not found, convert " + cellData.getType() + " to " + clazz.getName()); } try { - return converter.convertToJavaData(cellData, contentProperty, readSheetHolder); + return converter.convertToJavaData(new ReadConverterContext<>(cellData, contentProperty, context)); } catch (Exception e) { throw new ExcelDataConvertException(rowIndex, columnIndex, cellData, contentProperty, "Convert data " + cellData + " to " + clazz + " error ", e); diff --git a/src/main/java/com/alibaba/excel/util/FileTypeUtils.java b/src/main/java/com/alibaba/excel/util/FileTypeUtils.java new file mode 100644 index 00000000..6469da18 --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/FileTypeUtils.java @@ -0,0 +1,46 @@ +package com.alibaba.excel.util; + +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.excel.metadata.data.ImageData.ImageType; + +/** + * file type utils + * + * @author Jiaju Zhuang + */ +public class FileTypeUtils { + + private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', + 'f'}; + private static final int IMAGE_TYPE_MARK_LENGTH = 28; + + private static final Map FILE_TYPE_MAP; + + 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 ImageType getImageType(byte[] image) { + if (image == null || image.length <= IMAGE_TYPE_MARK_LENGTH) { + return null; + } + byte[] typeMarkByte = new byte[IMAGE_TYPE_MARK_LENGTH]; + System.arraycopy(image, 0, typeMarkByte, 0, IMAGE_TYPE_MARK_LENGTH); + return FILE_TYPE_MAP.get(encodeHexStr(typeMarkByte)); + } + + private static String encodeHexStr(byte[] data) { + final int len = data.length; + final char[] out = new char[len << 1]; + // two characters from the hex value. + for (int i = 0, j = 0; i < len; i++) { + out[j++] = DIGITS[(0xF0 & data[i]) >>> 4]; + out[j++] = DIGITS[0x0F & data[i]]; + } + return new String(out); + } +} diff --git a/src/main/java/com/alibaba/excel/util/MapUtils.java b/src/main/java/com/alibaba/excel/util/MapUtils.java index 6af4129e..2ecee78a 100644 --- a/src/main/java/com/alibaba/excel/util/MapUtils.java +++ b/src/main/java/com/alibaba/excel/util/MapUtils.java @@ -1,9 +1,7 @@ package com.alibaba.excel.util; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.LinkedHashMap; /** * Map utils @@ -12,6 +10,7 @@ import java.util.Map; **/ public class MapUtils { private MapUtils() {} + /** * Creates a mutable, empty {@code HashMap} instance. * @@ -37,13 +36,44 @@ public class MapUtils { * * @param expectedSize the number of entries you expect to add to the returned map * @return a new, empty {@code HashMap} with enough capacity to hold {@code expectedSize} entries - * without resizing + * without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative */ public static HashMap newHashMapWithExpectedSize(int expectedSize) { return new HashMap<>(capacity(expectedSize)); } + /** + * Creates a mutable, empty, insertion-ordered {@code LinkedHashMap} instance. + * + *

Note: if mutability is not required, use {@link ImmutableMap#of()} instead. + * + *

Note for Java 7 and later: this method is now unnecessary and should be treated as + * deprecated. Instead, use the {@code LinkedHashMap} constructor directly, taking advantage of + * the new "diamond" syntax. + * + * @return a new, empty {@code LinkedHashMap} + */ + public static LinkedHashMap newLinkedHashMap() { + return new LinkedHashMap<>(); + } + + /** + * Creates a {@code LinkedHashMap} instance, with a high enough "initial capacity" that it + * should hold {@code expectedSize} elements without growth. This behavior cannot be + * broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed + * that the method isn't inadvertently oversizing the returned map. + * + * @param expectedSize the number of entries you expect to add to the returned map + * @return a new, empty {@code LinkedHashMap} with enough capacity to hold {@code expectedSize} + * entries without resizing + * @throws IllegalArgumentException if {@code expectedSize} is negative + * @since 19.0 + */ + public static LinkedHashMap newLinkedHashMapWithExpectedSize(int expectedSize) { + return new LinkedHashMap<>(capacity(expectedSize)); + } + /** * Returns a capacity that is sufficient to keep the map from being resized as long as it grows no * larger than expectedSize and the load factor is ≥ its default (0.75). @@ -56,7 +86,7 @@ public class MapUtils { // This is the calculation used in JDK8 to resize when a putAll // happens; it seems to be the most conservative calculation we // can make. 0.75 is the default load factor. - return (int) ((float) expectedSize / 0.75F + 1.0F); + return (int)((float)expectedSize / 0.75F + 1.0F); } return Integer.MAX_VALUE; } diff --git a/src/main/java/com/alibaba/excel/util/NumberUtils.java b/src/main/java/com/alibaba/excel/util/NumberUtils.java index 09a15bea..4bb6c91b 100644 --- a/src/main/java/com/alibaba/excel/util/NumberUtils.java +++ b/src/main/java/com/alibaba/excel/util/NumberUtils.java @@ -5,9 +5,8 @@ import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.ParseException; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; -import com.alibaba.excel.write.metadata.holder.WriteHolder; /** * Number utils @@ -47,8 +46,8 @@ public class NumberUtils { * @param contentProperty * @return */ - public static CellData formatToCellDataString(Number num, ExcelContentProperty contentProperty) { - return new CellData<>(format(num, contentProperty)); + public static WriteCellData formatToCellDataString(Number num, ExcelContentProperty contentProperty) { + return new WriteCellData<>(format(num, contentProperty)); } /** @@ -56,16 +55,13 @@ public class NumberUtils { * * @param num * @param contentProperty - * @param currentWriteHolder * @return */ - public static CellData formatToCellData(Number num, ExcelContentProperty contentProperty, - WriteHolder currentWriteHolder) { - CellData cellData = new CellData<>(BigDecimal.valueOf(num.doubleValue())); + public static WriteCellData formatToCellData(Number num, ExcelContentProperty contentProperty) { + WriteCellData cellData = new WriteCellData<>(BigDecimal.valueOf(num.doubleValue())); if (contentProperty != null && contentProperty.getNumberFormatProperty() != null && StringUtils.isNotBlank(contentProperty.getNumberFormatProperty().getFormat())) { - WorkBookUtil.fillDataFormat(cellData, currentWriteHolder, - contentProperty.getNumberFormatProperty().getFormat()); + WorkBookUtil.fillDataFormat(cellData, contentProperty.getNumberFormatProperty().getFormat()); } return cellData; } diff --git a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java index 0ee92209..fb8a428b 100644 --- a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java +++ b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java @@ -2,12 +2,11 @@ package com.alibaba.excel.util; import java.io.IOException; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.DataFormatData; +import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.support.ExcelTypeEnum; -import com.alibaba.excel.write.metadata.holder.WriteHolder; -import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; -import com.alibaba.excel.write.metadata.holder.WriteTableHolder; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; +import com.alibaba.excel.write.metadata.style.WriteCellStyle; import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -95,15 +94,15 @@ public class WorkBookUtil { return cell; } - public static void fillDataFormat(CellData cellData, WriteHolder currentWriteHolder, String format) { - WriteWorkbookHolder writeWorkbookHolder; - if (currentWriteHolder instanceof WriteSheetHolder) { - writeWorkbookHolder = ((WriteSheetHolder)currentWriteHolder).getParentWriteWorkbookHolder(); - } else { - writeWorkbookHolder = ((WriteTableHolder)currentWriteHolder).getParentWriteSheetHolder() - .getParentWriteWorkbookHolder(); + public static void fillDataFormat(WriteCellData cellData, String format) { + if (cellData.getWriteCellStyle() == null) { + cellData.setWriteCellStyle(new WriteCellStyle()); + } + if (cellData.getWriteCellStyle().getDataFormatData() == null) { + cellData.getWriteCellStyle().setDataFormatData(new DataFormatData()); + } + if (cellData.getWriteCellStyle().getDataFormatData().getFormat() == null) { + cellData.getWriteCellStyle().getDataFormatData().setFormat(format); } - cellData.setDataFormat(writeWorkbookHolder.getDataFormat(format)); - cellData.setDataFormatString(format); } } diff --git a/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java b/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java index 0bd0a068..aa613a1e 100644 --- a/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java +++ b/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java @@ -5,7 +5,7 @@ import java.util.List; import java.util.Map; import com.alibaba.excel.context.WriteContext; -import com.alibaba.excel.metadata.CellData; +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.handler.RowWriteHandler; diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index 51463e69..e96df6f8 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -6,7 +6,7 @@ import com.alibaba.excel.converters.ConverterKeyBuild; import com.alibaba.excel.converters.NullableObjectConverter; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.exception.ExcelDataConvertException; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.util.WriteHandlerUtils; diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index c4b3e45e..ebc3516f 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -10,7 +10,7 @@ import java.util.TreeMap; import com.alibaba.excel.context.WriteContext; import com.alibaba.excel.enums.HeadKindEnum; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.util.ClassUtils; diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 9a144534..fbae327a 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/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.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.util.WriteHandlerUtils; diff --git a/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java index 6b663ce9..642fdffd 100644 --- a/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java @@ -5,7 +5,7 @@ import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder; diff --git a/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java index 4c9e39ed..5cf16c1b 100644 --- a/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java @@ -2,7 +2,7 @@ package com.alibaba.excel.write.handler; import java.util.List; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder; diff --git a/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java index a465546b..2186f381 100644 --- a/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java +++ b/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java @@ -7,7 +7,7 @@ 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.CellData; +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; diff --git a/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java b/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java index 7b3d4b2b..21e80716 100644 --- a/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java +++ b/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java @@ -2,7 +2,7 @@ package com.alibaba.excel.write.merge; import java.util.List; -import com.alibaba.excel.metadata.CellData; +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; diff --git a/src/main/java/com/alibaba/excel/write/metadata/WriteBasicParameter.java b/src/main/java/com/alibaba/excel/write/metadata/WriteBasicParameter.java index e6d2b9f0..91527cc1 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/WriteBasicParameter.java +++ b/src/main/java/com/alibaba/excel/write/metadata/WriteBasicParameter.java @@ -7,11 +7,14 @@ import java.util.List; import com.alibaba.excel.metadata.BasicParameter; import com.alibaba.excel.write.handler.WriteHandler; +import lombok.Data; + /** * Write basic parameter * * @author Jiaju Zhuang **/ +@Data public class WriteBasicParameter extends BasicParameter { /** * Writes the head relative to the existing contents of the sheet. Indexes are zero-based. @@ -49,77 +52,4 @@ public class WriteBasicParameter extends BasicParameter { * Only output the custom columns. */ private Collection includeColumnFieldNames; - - public Integer getRelativeHeadRowIndex() { - return relativeHeadRowIndex; - } - - public void setRelativeHeadRowIndex(Integer relativeHeadRowIndex) { - this.relativeHeadRowIndex = relativeHeadRowIndex; - } - - public Boolean getNeedHead() { - return needHead; - } - - public void setNeedHead(Boolean needHead) { - this.needHead = needHead; - } - - public List getCustomWriteHandlerList() { - return customWriteHandlerList; - } - - public void setCustomWriteHandlerList(List customWriteHandlerList) { - this.customWriteHandlerList = customWriteHandlerList; - } - - public 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 getExcludeColumnIndexes() { - return excludeColumnIndexes; - } - - public void setExcludeColumnIndexes(Collection excludeColumnIndexes) { - this.excludeColumnIndexes = excludeColumnIndexes; - } - - public Collection getExcludeColumnFieldNames() { - return excludeColumnFieldNames; - } - - public void setExcludeColumnFieldNames(Collection excludeColumnFieldNames) { - this.excludeColumnFieldNames = excludeColumnFieldNames; - } - - public Collection getIncludeColumnIndexes() { - return includeColumnIndexes; - } - - public void setIncludeColumnIndexes(Collection includeColumnIndexes) { - this.includeColumnIndexes = includeColumnIndexes; - } - - public Collection getIncludeColumnFieldNames() { - return includeColumnFieldNames; - } - - public void setIncludeColumnFieldNames(Collection includeColumnFieldNames) { - this.includeColumnFieldNames = includeColumnFieldNames; - } - } diff --git a/src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java b/src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java index 62fac752..96e88c2e 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java +++ b/src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java @@ -3,10 +3,11 @@ package com.alibaba.excel.write.metadata; import java.util.HashMap; import java.util.Map; -import com.alibaba.excel.metadata.TableStyle; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy; import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy; +import org.apache.poi.ss.usermodel.TableStyle; + /** * Write sheet * diff --git a/src/main/java/com/alibaba/excel/write/metadata/WriteTable.java b/src/main/java/com/alibaba/excel/write/metadata/WriteTable.java index ec7933c0..a7bcc814 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/WriteTable.java +++ b/src/main/java/com/alibaba/excel/write/metadata/WriteTable.java @@ -1,6 +1,5 @@ package com.alibaba.excel.write.metadata; -import com.alibaba.excel.metadata.TableStyle; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy; /** diff --git a/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java b/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java index c28e0412..899e4ca1 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java +++ b/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java @@ -5,13 +5,15 @@ import java.io.InputStream; import java.io.OutputStream; import com.alibaba.excel.support.ExcelTypeEnum; -import com.alibaba.excel.write.handler.WriteHandler; + +import lombok.Data; /** * Workbook * * @author Jiaju Zhuang **/ +@Data public class WriteWorkbook extends WriteBasicParameter { /** * Excel type.The default is xlsx @@ -78,107 +80,4 @@ public class WriteWorkbook extends WriteBasicParameter { */ @Deprecated private Boolean convertAllFiled; - /** - * Write handler - * - * @deprecated please use {@link WriteHandler} - */ - @Deprecated - private com.alibaba.excel.event.WriteHandler writeHandler; - - public ExcelTypeEnum getExcelType() { - return excelType; - } - - public void setExcelType(ExcelTypeEnum excelType) { - this.excelType = excelType; - } - - public File getFile() { - return file; - } - - public void setFile(File file) { - this.file = file; - } - - public OutputStream getOutputStream() { - return outputStream; - } - - public void setOutputStream(OutputStream outputStream) { - this.outputStream = outputStream; - } - - public InputStream getTemplateInputStream() { - return templateInputStream; - } - - public void setTemplateInputStream(InputStream templateInputStream) { - this.templateInputStream = templateInputStream; - } - - public File getTemplateFile() { - return templateFile; - } - - public void setTemplateFile(File templateFile) { - this.templateFile = templateFile; - } - - public Boolean getAutoCloseStream() { - return autoCloseStream; - } - - public void setAutoCloseStream(Boolean autoCloseStream) { - this.autoCloseStream = autoCloseStream; - } - - public Boolean getMandatoryUseInputStream() { - return mandatoryUseInputStream; - } - - public void setMandatoryUseInputStream(Boolean mandatoryUseInputStream) { - this.mandatoryUseInputStream = mandatoryUseInputStream; - } - - public Boolean getConvertAllFiled() { - return convertAllFiled; - } - - public void setConvertAllFiled(Boolean convertAllFiled) { - this.convertAllFiled = convertAllFiled; - } - - public com.alibaba.excel.event.WriteHandler getWriteHandler() { - return writeHandler; - } - - public void setWriteHandler(com.alibaba.excel.event.WriteHandler writeHandler) { - this.writeHandler = writeHandler; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public Boolean getInMemory() { - return inMemory; - } - - public void setInMemory(Boolean inMemory) { - this.inMemory = inMemory; - } - - public Boolean getWriteExcelOnException() { - return writeExcelOnException; - } - - public void setWriteExcelOnException(Boolean writeExcelOnException) { - this.writeExcelOnException = writeExcelOnException; - } } diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java index 54c31245..80f858e7 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java @@ -24,7 +24,6 @@ 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.TableStyle; import com.alibaba.excel.metadata.property.LoopMergeProperty; import com.alibaba.excel.metadata.property.OnceAbsoluteMergeProperty; import com.alibaba.excel.metadata.property.RowHeightProperty; diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java index 671b96f7..a48e39e8 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java @@ -13,6 +13,7 @@ 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; import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.util.IoUtils; @@ -122,7 +123,7 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { /** * Used to cache data Format. */ - private Map dataFormatCache; + private Map dataFormatCache; public WriteWorkbookHolder(WriteWorkbook writeWorkbook) { super(writeWorkbook, null, writeWorkbook.getConvertAllFiled()); @@ -210,11 +211,11 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { * @param format * @return */ - public Short getDataFormat(String format) { + public DataFormatData getDataFormat(String format) { if (StringUtils.isEmpty(format)) { return BuiltinFormats.GENERAL; } - Short dataFormat = dataFormatCache.get(format); + DataFormatData dataFormat = dataFormatCache.get(format); if (dataFormat != null) { return dataFormat; } diff --git a/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java b/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java index 330aa51a..8661897b 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java +++ b/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java @@ -1,12 +1,14 @@ 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; import com.alibaba.excel.util.StringUtils; import lombok.Data; import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.BuiltinFormats; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IgnoredErrorType; @@ -23,7 +25,8 @@ public class WriteCellStyle { /** * 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 */ diff --git a/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java index f131c456..9442e4e2 100644 --- a/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java @@ -3,7 +3,7 @@ package com.alibaba.excel.write.style; import java.util.List; import com.alibaba.excel.event.NotRepeatExecutor; -import com.alibaba.excel.metadata.CellData; +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.handler.WorkbookWriteHandler; diff --git a/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java index 277f96b9..3037fbc9 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java @@ -2,16 +2,15 @@ package com.alibaba.excel.write.style.column; import java.util.List; -import org.apache.poi.ss.usermodel.Cell; - import com.alibaba.excel.event.NotRepeatExecutor; -import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.Head; -import com.alibaba.excel.write.handler.AbstractCellWriteHandler; +import com.alibaba.excel.metadata.data.CellData; 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.ss.usermodel.Cell; + /** * Column width style strategy * diff --git a/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java index d306d2e4..b388bc44 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java @@ -4,7 +4,7 @@ import java.util.List; import org.apache.poi.ss.usermodel.Cell; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; diff --git a/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java index c6cc9df1..1010163e 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java @@ -8,7 +8,7 @@ import org.apache.commons.collections4.CollectionUtils; import org.apache.poi.ss.usermodel.Cell; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataData.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataData.java index ac928ec1..bed0685d 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataData.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataData.java @@ -2,9 +2,8 @@ package com.alibaba.easyexcel.test.core.celldata; import java.util.Date; -import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.format.DateTimeFormat; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import lombok.Data; diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java index ad8cbf13..fdedb1ef 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java @@ -3,22 +3,17 @@ package com.alibaba.easyexcel.test.core.celldata; import java.io.File; import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Date; import java.util.List; -import org.junit.Assert; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; -import com.alibaba.easyexcel.test.core.simple.SimpleData; -import com.alibaba.easyexcel.test.core.simple.SimpleDataListener; -import com.alibaba.easyexcel.test.core.simple.SimpleDataSheetNameListener; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.util.DateUtils; /** diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityData.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityData.java index 45b7f63a..c0d9d89f 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityData.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityData.java @@ -1,7 +1,6 @@ package com.alibaba.easyexcel.test.core.compatibility; import com.alibaba.excel.annotation.ExcelProperty; -import com.alibaba.excel.metadata.BaseRowModel; import lombok.Data; diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java index 258f055c..87edf636 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java @@ -20,9 +20,6 @@ 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.metadata.Sheet; -import com.alibaba.excel.metadata.Table; -import com.alibaba.excel.metadata.TableStyle; import com.alibaba.excel.parameter.AnalysisParam; import com.alibaba.excel.parameter.GenerateParam; diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java index 2e3b7355..9890f894 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java @@ -15,7 +15,6 @@ 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.Sheet; /** * diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java index ba062a5f..6ff7bbfb 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java @@ -1,7 +1,5 @@ package com.alibaba.easyexcel.test.core.compatibility; -import com.alibaba.excel.metadata.BaseRowModel; - import lombok.Data; /** diff --git a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java index fdff30e3..619415c6 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java +++ b/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.CellData; +import com.alibaba.excel.metadata.data.CellData; import lombok.Data; diff --git a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java index a339e9ef..3b3b8d1a 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java @@ -13,7 +13,7 @@ import org.junit.runners.MethodSorters; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.util.DateUtils; import com.alibaba.excel.util.FileUtils; diff --git a/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java b/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java index cf9c5d26..0a852c0f 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java @@ -6,7 +6,7 @@ import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.junit.Assert; -import com.alibaba.excel.metadata.CellData; +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.handler.RowWriteHandler; diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/read/CellDataDemoHeadDataListener.java b/src/test/java/com/alibaba/easyexcel/test/demo/read/CellDataDemoHeadDataListener.java index 896cea62..53e0bf68 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/read/CellDataDemoHeadDataListener.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/read/CellDataDemoHeadDataListener.java @@ -2,14 +2,12 @@ package com.alibaba.easyexcel.test.demo.read; import java.util.ArrayList; 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.event.AnalysisEventListener; -import com.alibaba.excel.metadata.CellData; import com.alibaba.fastjson.JSON; /** diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/read/CellDataReadDemoData.java b/src/test/java/com/alibaba/easyexcel/test/demo/read/CellDataReadDemoData.java index f5d01e0c..357dbfe9 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/read/CellDataReadDemoData.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/read/CellDataReadDemoData.java @@ -2,7 +2,7 @@ package com.alibaba.easyexcel.test.demo.read; import java.util.Date; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import lombok.Data; diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/read/CustomStringStringConverter.java b/src/test/java/com/alibaba/easyexcel/test/demo/read/CustomStringStringConverter.java index 5201e750..6116c852 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/read/CustomStringStringConverter.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/read/CustomStringStringConverter.java @@ -2,7 +2,7 @@ package com.alibaba.easyexcel.test.demo.read; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java index b4ade88f..e9567a27 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java @@ -9,9 +9,8 @@ import org.apache.poi.ss.usermodel.Hyperlink; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.Head; -import com.alibaba.excel.write.handler.AbstractCellWriteHandler; import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder; diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomStringStringConverter.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomStringStringConverter.java index 45ebc8c1..53aec631 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomStringStringConverter.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomStringStringConverter.java @@ -2,7 +2,7 @@ package com.alibaba.easyexcel.test.demo.write; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.property.ExcelContentProperty; diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/LockDataListener.java b/src/test/java/com/alibaba/easyexcel/test/temp/LockDataListener.java index 64cce8db..bda277c6 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/LockDataListener.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/LockDataListener.java @@ -2,7 +2,6 @@ package com.alibaba.easyexcel.test.temp; import java.util.ArrayList; import java.util.List; -import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -10,7 +9,6 @@ import org.slf4j.LoggerFactory; import com.alibaba.easyexcel.test.demo.read.DemoDataListener; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.CellData; import com.alibaba.fastjson.JSON; /** diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatData.java b/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatData.java index d057d8e7..ae663254 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatData.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatData.java @@ -1,6 +1,6 @@ package com.alibaba.easyexcel.test.temp.dataformat; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import lombok.Data; diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/poi/TestCell.java b/src/test/java/com/alibaba/easyexcel/test/temp/poi/TestCell.java index bb12c220..0edc995d 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/poi/TestCell.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/poi/TestCell.java @@ -2,7 +2,7 @@ package com.alibaba.easyexcel.test.temp.poi; import java.util.List; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import lombok.Data; diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/read/CommentTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/read/CommentTest.java index 22de3956..48512b6c 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/read/CommentTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/read/CommentTest.java @@ -10,7 +10,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.excel.EasyExcel; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.fastjson.JSON; /** diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/read/HDListener.java b/src/test/java/com/alibaba/easyexcel/test/temp/read/HDListener.java index e52dc51a..1c58e798 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/read/HDListener.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/read/HDListener.java @@ -7,7 +7,6 @@ import org.slf4j.LoggerFactory; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.CellData; import com.alibaba.fastjson.JSON; /** diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java b/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java index 375cf636..d8825f0c 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java @@ -1,8 +1,7 @@ package com.alibaba.easyexcel.test.temp.simple; -import com.alibaba.excel.metadata.CellData; +import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.Head; -import com.alibaba.excel.write.handler.AbstractCellWriteHandler; import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder; From 466287d4adc51ca71d65b6ae026bb8af8fb3343b Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 23 Apr 2021 12:43:53 +0800 Subject: [PATCH 062/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E5=88=86=E5=BC=80celldata?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/write/builder/ExcelWriterBuilder.java | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java index 12c2f22f..22196555 100644 --- a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java +++ b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java @@ -6,7 +6,6 @@ import java.io.OutputStream; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.support.ExcelTypeEnum; -import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.metadata.WriteWorkbook; /** @@ -18,7 +17,7 @@ public class ExcelWriterBuilder extends AbstractExcelWriterParameterBuilder Date: Thu, 6 May 2021 20:22:36 +0800 Subject: [PATCH 063/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E5=BA=95=E5=B1=82=E5=9F=BA=E4=BA=8E=E6=96=B0=E7=9A=84celldata?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- easyexcel | 1 - .../v03/handlers/BlankRecordHandler.java | 10 +- .../v03/handlers/BoolErrRecordHandler.java | 10 +- .../v03/handlers/DummyRecordHandler.java | 12 +- .../v03/handlers/LabelRecordHandler.java | 10 +- .../v03/handlers/LabelSstRecordHandler.java | 14 +- .../v03/handlers/RkRecordHandler.java | 10 +- .../annotation/write/style/HeadStyle.java | 6 - .../alibaba/excel/constant/OrderConstant.java | 13 +- .../excel/context/WriteContextImpl.java | 4 +- .../converters/WriteConverterContext.java | 1 + .../bigdecimal/BigDecimalNumberConverter.java | 5 +- .../converters/date/DateDateConverter.java | 9 +- .../java/com/alibaba/excel/event/Handler.java | 15 +- .../excel/metadata/AbstractHolder.java | 2 +- .../metadata/AbstractParameterBuilder.java | 8 +- .../excel/metadata/data/ClientAnchorData.java | 16 +- .../excel/metadata/data/CommentData.java | 10 +- .../excel/metadata/data/CoordinateData.java | 25 +- .../excel/metadata/data/HyperlinkData.java | 16 +- .../excel/metadata/data/ImageData.java | 4 +- .../excel/metadata/data/ReadCellData.java | 2 + .../metadata/data/RichTextStringData.java | 2 +- .../excel/metadata/data/WriteCellData.java | 10 +- .../property/ExcelContentProperty.java | 45 +--- .../metadata/property/StyleProperty.java | 203 +------------- .../AbstractExcelReaderParameterBuilder.java | 7 +- .../DefaultAnalysisEventProcessor.java | 12 +- .../com/alibaba/excel/util/ClassUtils.java | 30 +-- .../com/alibaba/excel/util/FileTypeUtils.java | 13 + .../com/alibaba/excel/util/ListUtils.java | 15 ++ .../com/alibaba/excel/util/NumberUtils.java | 2 +- .../com/alibaba/excel/util/StyleUtil.java | 154 ++++++----- .../com/alibaba/excel/util/WorkBookUtil.java | 8 +- .../alibaba/excel/util/WriteHandlerUtils.java | 94 ++++--- .../executor/AbstractExcelWriteExecutor.java | 250 +++++++++++++----- .../write/executor/ExcelWriteAddExecutor.java | 18 +- .../executor/ExcelWriteFillExecutor.java | 8 +- .../handler/AbstractCellWriteHandler.java | 13 +- .../excel/write/handler/CellWriteHandler.java | 50 +++- .../handler/DefaultWriteHandlerLoader.java | 17 +- .../excel/write/handler/RowWriteHandler.java | 31 +++ .../write/handler/SheetWriteHandler.java | 19 ++ .../write/handler/WorkbookWriteHandler.java | 28 ++ .../context/CellWriteHandlerContext.java | 69 +++++ .../context/RowWriteHandlerContext.java | 52 ++++ .../context/SheetWriteHandlerContext.java | 30 +++ .../context/WorkbookWriteHandlerContext.java | 25 ++ .../handler/impl/DefaultRowWriteHandler.java | 11 +- .../impl/FillDataFormatCellWriteHandler.java | 76 ------ .../impl/FillStyleCellWriteHandler.java | 43 +++ .../write/merge/AbstractMergeStrategy.java | 14 +- .../excel/write/metadata/WriteTable.java | 25 +- .../metadata/holder/AbstractWriteHolder.java | 178 +------------ .../metadata/holder/WriteWorkbookHolder.java | 75 ++++-- .../write/metadata/style/WriteCellStyle.java | 11 +- .../style/AbstractCellStyleStrategy.java | 63 ++--- .../AbstractVerticalCellStyleStrategy.java | 93 ++----- .../style/HorizontalCellStyleStrategy.java | 17 +- .../AbstractColumnWidthStyleStrategy.java | 29 +- .../AbstractHeadColumnWidthStyleStrategy.java | 8 +- .../LongestMatchColumnWidthStyleStrategy.java | 18 +- .../row/AbstractRowHeightStyleStrategy.java | 39 +-- .../core/celldata/CellDataDataListener.java | 10 +- .../test/core/celldata/CellDataDataTest.java | 22 +- .../core/compatibility/CompatibilityData.java | 16 -- .../CompatibilityDataListener.java | 34 --- .../compatibility/CompatibilityDataTest.java | 157 ----------- .../CompatibilityParameterDataTest.java | 142 ---------- .../compatibility/CompatibilityReadData.java | 12 - .../test/core/converter/ConverterData.java | 4 +- .../core/converter/ConverterDataTest.java | 14 +- .../test/core/handler/WriteHandler.java | 17 +- .../test/core/style/StyleDataTest.java | 28 +- .../read/CustomStringStringConverter.java | 11 +- .../demo/write/CustomCellWriteHandler.java | 14 +- .../write/CustomStringStringConverter.java | 29 +- .../test/temp/dataformat/DataFormatData.java | 7 +- .../test/temp/dataformat/DataFormatTest.java | 20 +- .../test/temp/read/HeadReadTest.java | 18 +- .../test/temp/simple/WriteCellHandler.java | 4 +- 81 files changed, 1159 insertions(+), 1508 deletions(-) delete mode 160000 easyexcel create mode 100644 src/main/java/com/alibaba/excel/write/handler/context/CellWriteHandlerContext.java create mode 100644 src/main/java/com/alibaba/excel/write/handler/context/RowWriteHandlerContext.java create mode 100644 src/main/java/com/alibaba/excel/write/handler/context/SheetWriteHandlerContext.java create mode 100644 src/main/java/com/alibaba/excel/write/handler/context/WorkbookWriteHandlerContext.java delete mode 100644 src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java create mode 100644 src/main/java/com/alibaba/excel/write/handler/impl/FillStyleCellWriteHandler.java delete mode 100644 src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityData.java delete mode 100644 src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataListener.java delete mode 100644 src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java delete mode 100644 src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java delete mode 100644 src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java diff --git a/easyexcel b/easyexcel deleted file mode 160000 index 4076b897..00000000 --- a/easyexcel +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 4076b897953b18f9e96c278c6929325e89f2be12 diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/BlankRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/BlankRecordHandler.java index 30f09273..25d1338e 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/BlankRecordHandler.java +++ b/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())); } } diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/BoolErrRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/BoolErrRecordHandler.java index 1afb6c1f..19665907 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/BoolErrRecordHandler.java +++ b/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); } } diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/DummyRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/DummyRecordHandler.java index eb5bd2ae..8ecc33a4 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/DummyRecordHandler.java +++ b/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())); } } } diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelRecordHandler.java index 39481de0..a90ad6bb 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelRecordHandler.java +++ b/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); } } diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelSstRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelSstRecordHandler.java index 0075254c..fd464e54 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelSstRecordHandler.java +++ b/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 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); } } diff --git a/src/main/java/com/alibaba/excel/analysis/v03/handlers/RkRecordHandler.java b/src/main/java/com/alibaba/excel/analysis/v03/handlers/RkRecordHandler.java index 91c3c9f8..3fb45899 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/handlers/RkRecordHandler.java +++ b/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())); } } diff --git a/src/main/java/com/alibaba/excel/annotation/write/style/HeadStyle.java b/src/main/java/com/alibaba/excel/annotation/write/style/HeadStyle.java index d882da8f..5bc3ffc6 100644 --- a/src/main/java/com/alibaba/excel/annotation/write/style/HeadStyle.java +++ b/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 true 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 Note: Ensure Foreground color is set prior to background color. * * @see IndexedColors - * */ short fillForegroundColor() default -1; diff --git a/src/main/java/com/alibaba/excel/constant/OrderConstant.java b/src/main/java/com/alibaba/excel/constant/OrderConstant.java index a955025c..54d438e5 100644 --- a/src/main/java/com/alibaba/excel/constant/OrderConstant.java +++ b/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; } diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java index 175f33da..2b7ced3e 100644 --- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java +++ b/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); } } diff --git a/src/main/java/com/alibaba/excel/converters/WriteConverterContext.java b/src/main/java/com/alibaba/excel/converters/WriteConverterContext.java index b1d0a5dd..36ce56c6 100644 --- a/src/main/java/com/alibaba/excel/converters/WriteConverterContext.java +++ b/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; /** diff --git a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java b/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java index 6a60b0d7..f1b1285c 100644 --- a/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java +++ b/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 { @Override public WriteCellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, - WriteHolder currentWriteHolder) { - return NumberUtils.formatToCellData(value, contentProperty, currentWriteHolder); + GlobalConfiguration globalConfiguration) { + return NumberUtils.formatToCellData(value, contentProperty); } } diff --git a/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java b/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java index 68daee84..29970070 100644 --- a/src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java +++ b/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 { 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; } } diff --git a/src/main/java/com/alibaba/excel/event/Handler.java b/src/main/java/com/alibaba/excel/event/Handler.java index 2fe304f0..4b32be0c 100644 --- a/src/main/java/com/alibaba/excel/event/Handler.java +++ b/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; + } +} diff --git a/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java b/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java index d8b4ec43..ffb54559 100644 --- a/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java +++ b/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 */ diff --git a/src/main/java/com/alibaba/excel/metadata/AbstractParameterBuilder.java b/src/main/java/com/alibaba/excel/metadata/AbstractParameterBuilder.java index 66df25b6..319c5ab6 100644 --- a/src/main/java/com/alibaba/excel/metadata/AbstractParameterBuilder.java +++ b/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 clazz) { parameter().setClazz(clazz); return self(); } @@ -40,9 +40,9 @@ public abstract class AbstractParameterBuilder converter) { if (parameter().getCustomConverterList() == null) { - parameter().setCustomConverterList(new ArrayList()); + parameter().setCustomConverterList(ListUtils.newArrayList()); } parameter().getCustomConverterList().add(converter); return self(); diff --git a/src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java b/src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java index b240eb97..86a93d48 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java +++ b/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) *

*/ - 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 { *

* 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. *

*/ - 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. *

*/ - 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; } /** diff --git a/src/main/java/com/alibaba/excel/metadata/data/CommentData.java b/src/main/java/com/alibaba/excel/metadata/data/CommentData.java index 6f86a3e3..08cff272 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/CommentData.java +++ b/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 */ diff --git a/src/main/java/com/alibaba/excel/metadata/data/CoordinateData.java b/src/main/java/com/alibaba/excel/metadata/data/CoordinateData.java index c9b73ffb..69242e57 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/CoordinateData.java +++ b/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; } diff --git a/src/main/java/com/alibaba/excel/metadata/data/HyperlinkData.java b/src/main/java/com/alibaba/excel/metadata/data/HyperlinkData.java index c38d7dd6..3fa23893 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/HyperlinkData.java +++ b/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; } } diff --git a/src/main/java/com/alibaba/excel/metadata/data/ImageData.java b/src/main/java/com/alibaba/excel/metadata/data/ImageData.java index 48276db3..20cd43e1 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/ImageData.java +++ b/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; diff --git a/src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java b/src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java index 462cbac7..90cf9a5a 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java +++ b/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 extends CellData { /** * data format. diff --git a/src/main/java/com/alibaba/excel/metadata/data/RichTextStringData.java b/src/main/java/com/alibaba/excel/metadata/data/RichTextStringData.java index 4b8a0420..1717741a 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/RichTextStringData.java +++ b/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 */ diff --git a/src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java b/src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java index 3f1de9be..82231e5f 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java +++ b/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 extends CellData { /** * Support only when writing.{@link CellDataTypeEnum#DATE} @@ -42,11 +44,15 @@ public class WriteCellData extends CellData { */ 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) { @@ -92,7 +98,7 @@ public class WriteCellData extends CellData { throw new IllegalArgumentException("Image can not be null"); } setType(CellDataTypeEnum.EMPTY); - this.imageDataList= ListUtils.newArrayList(); + this.imageDataList = ListUtils.newArrayList(); ImageData imageData = new ImageData(); imageData.setImage(image); imageDataList.add(imageData); diff --git a/src/main/java/com/alibaba/excel/metadata/property/ExcelContentProperty.java b/src/main/java/com/alibaba/excel/metadata/property/ExcelContentProperty.java index fcad87b3..f6f92532 100644 --- a/src/main/java/com/alibaba/excel/metadata/property/ExcelContentProperty.java +++ b/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; - } } diff --git a/src/main/java/com/alibaba/excel/metadata/property/StyleProperty.java b/src/main/java/com/alibaba/excel/metadata/property/StyleProperty.java index 9222b102..f6d0ab0b 100644 --- a/src/main/java/com/alibaba/excel/metadata/property/StyleProperty.java +++ b/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 true 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 Note: Ensure Foreground color is set prior to background color. * * @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; - } } diff --git a/src/main/java/com/alibaba/excel/read/builder/AbstractExcelReaderParameterBuilder.java b/src/main/java/com/alibaba/excel/read/builder/AbstractExcelReaderParameterBuilder.java index 29d676cb..75f98065 100644 --- a/src/main/java/com/alibaba/excel/read/builder/AbstractExcelReaderParameterBuilder.java +++ b/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 readListener) { if (parameter().getCustomReadListenerList() == null) { - parameter().setCustomReadListenerList(new ArrayList()); + parameter().setCustomReadListenerList(ListUtils.newArrayList()); } parameter().getCustomReadListenerList().add(readListener); return self(); diff --git a/src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java b/src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java index ab2e69de..c3c50234 100644 --- a/src/main/java/com/alibaba/excel/read/processor/DefaultAnalysisEventProcessor.java +++ b/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> cellDataMap = (Map)readRowHolder.getCellMap(); + Map> 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> cellDataMap) { + private void buildHead(AnalysisContext analysisContext, Map> cellDataMap) { if (!HeadKindEnum.CLASS.equals(analysisContext.currentReadHolder().excelReadHeadProperty().getHeadKind())) { return; } diff --git a/src/main/java/com/alibaba/excel/util/ClassUtils.java b/src/main/java/com/alibaba/excel/util/ClassUtils.java index 45df3846..2f628780 100644 --- a/src/main/java/com/alibaba/excel/util/ClassUtils.java +++ b/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> FIELD_CACHE = - new ConcurrentHashMap>(); + private static final Map, SoftReference> FIELD_CACHE = new ConcurrentHashMap<>(); - public static void declaredFields(Class clazz, Map sortedAllFiledMap, + public static void declaredFields(Class clazz, Map sortedAllFiledMap, Map indexFiledMap, Map ignoreMap, Boolean convertAllFiled, Boolean needIgnore, Holder holder) { FieldCache fieldCache = getFieldCache(clazz, convertAllFiled); @@ -54,7 +53,7 @@ public class ClassUtils { int index = 0; for (Map.Entry entry : fieldCache.getSortedAllFiledMap().entrySet()) { Field field = entry.getValue(); - if (((WriteHolder) holder).ignore(entry.getValue().getName(), entry.getKey())) { + if (((WriteHolder)holder).ignore(entry.getValue().getName(), entry.getKey())) { if (ignoreMap != null) { ignoreMap.put(field.getName(), field); } @@ -69,12 +68,12 @@ public class ClassUtils { } } - public static void declaredFields(Class clazz, Map sortedAllFiledMap, Boolean convertAllFiled, + public static void declaredFields(Class clazz, Map 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 tempFieldList = new ArrayList(); - Class tempClass = clazz; + private static void declaredFields(Class clazz, Boolean convertAllFiled) { + List 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 indexFiledMap = new TreeMap(); Map ignoreMap = new HashMap(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 { } } - /** *

Gets a {@code List} of all interfaces implemented by the given * class and its superclasses.

@@ -218,9 +215,9 @@ public class ClassUtils { * superclass is considered in the same way. Later duplicates are ignored, * so the order is maintained.

* - * @param cls the class to look up, may be {@code null} + * @param cls the class to look up, may be {@code null} * @return the {@code List} of interfaces in order, - * {@code null} if null input + * {@code null} if null input */ public static List> getAllInterfaces(final Class cls) { if (cls == null) { @@ -233,11 +230,10 @@ public class ClassUtils { return new ArrayList<>(interfacesFound); } - /** * Gets the interfaces for the specified class. * - * @param cls the class to look up, may be {@code null} + * @param cls the class to look up, may be {@code null} * @param interfacesFound the {@code Set} of interfaces for the class */ private static void getAllInterfaces(Class cls, final HashSet> interfacesFound) { diff --git a/src/main/java/com/alibaba/excel/util/FileTypeUtils.java b/src/main/java/com/alibaba/excel/util/FileTypeUtils.java index 6469da18..45de5059 100644 --- a/src/main/java/com/alibaba/excel/util/FileTypeUtils.java +++ b/src/main/java/com/alibaba/excel/util/FileTypeUtils.java @@ -18,12 +18,25 @@ public class FileTypeUtils { private static final Map 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; diff --git a/src/main/java/com/alibaba/excel/util/ListUtils.java b/src/main/java/com/alibaba/excel/util/ListUtils.java index 85d06b4d..e64acb36 100644 --- a/src/main/java/com/alibaba/excel/util/ListUtils.java +++ b/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 mutable {@code ArrayList} instance containing the given elements. + * + */ + public static ArrayList newArrayList(E... elements) { + checkNotNull(elements); + // Avoid integer overflow when a large array is passed in + int capacity = computeArrayListCapacity(elements.length); + ArrayList list = new ArrayList<>(capacity); + Collections.addAll(list, elements); + return list; + } + + /** * Creates a mutable {@code ArrayList} instance containing the given elements; a very thin * shortcut for creating an empty list and then calling {@link Iterators#addAll}. diff --git a/src/main/java/com/alibaba/excel/util/NumberUtils.java b/src/main/java/com/alibaba/excel/util/NumberUtils.java index 4bb6c91b..ea2635e6 100644 --- a/src/main/java/com/alibaba/excel/util/NumberUtils.java +++ b/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; } diff --git a/src/main/java/com/alibaba/excel/util/StyleUtil.java b/src/main/java/com/alibaba/excel/util/StyleUtil.java index 0154f181..4f10a1b0 100644 --- a/src/main/java/com/alibaba/excel/util/StyleUtil.java +++ b/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 boolean isDefaultStyle(CellStyle cellStyle) { - if (cellStyle == null) { - return true; + public static HyperlinkType getHyperlinkType(HyperlinkData.HyperlinkType hyperlinkType) { + if (hyperlinkType == null) { + return HyperlinkType.NONE; } - if (cellStyle instanceof XSSFCellStyle) { - return cellStyle.getIndex() == XSSF_DEFAULT_STYLE; + return hyperlinkType.getValue(); + } + + public static int getCoordinate(Integer coordinate) { + if (coordinate == null) { + return 0; + } + return baseCoordinate * coordinate; + } + + public static int getCellCoordinate(Integer currentCoordinate, Integer absoluteCoordinate, + Integer relativeCoordinate) { + if (absoluteCoordinate != null && absoluteCoordinate > 0) { + return absoluteCoordinate; } - return cellStyle.getIndex() == HSSF_DEFAULT_STYLE; + if (relativeCoordinate != null) { + return currentCoordinate + relativeCoordinate; + } + return currentCoordinate; } + } + + diff --git a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java index fb8a428b..8aa2bfbf 100644 --- a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java +++ b/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) { - cellData.getWriteCellStyle().getDataFormatData().setFormat(format); + if (format == null) { + cellData.getWriteCellStyle().getDataFormatData().setFormat(defaultFormat); + } else { + cellData.getWriteCellStyle().getDataFormatData().setFormat(format); + } } } } diff --git a/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java b/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java index aa613a1e..2e7863e8 100644 --- a/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java +++ b/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,54 +138,57 @@ 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 handlerList = writeContext.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class); if (handlerList == null || handlerList.isEmpty()) { return; } + List> 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> cellDataList = new ArrayList<>(); - if (cellData != null) { - cellDataList.add(cellData); - } + List> cellDataList = cellData == null ? null : ListUtils.newArrayList(cellData); afterCellDispose(writeContext, cellDataList, cell, head, relativeRowIndex, isHead); } - public static void afterCellDispose(WriteContext writeContext, List> cellDataList, Cell cell, Head head, + public static void afterCellDispose(WriteContext writeContext, List> cellDataList, Cell cell, + Head head, Integer relativeRowIndex, Boolean isHead) { List 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); - } } public static void beforeRowCreate(WriteContext writeContext, Integer rowIndex, Integer relativeRowIndex, @@ -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,15 +226,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).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); - } } private static List getHandlerList(WriteContext writeContext, Class clazz, diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index e96df6f8..879d16c2 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/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 CellData convert(WriteHolder currentWriteHolder, Class clazz, CellDataTypeEnum targetType, + protected void fillImage(Cell cell, List 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 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)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); - } } diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index ebc3516f..b1777c02 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/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 beanMapHandledSet = new HashSet(); - 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 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 sortedAllFiledMap) { + private void initSortedAllFiledMapFieldList(Class clazz, Map sortedAllFiledMap) { if (!sortedAllFiledMap.isEmpty()) { return; } diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index fbae327a..7675bcf3 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/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> cellDataList = new ArrayList<>(); + List> 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(); diff --git a/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java index 642fdffd..688598ac 100644 --- a/src/main/java/com/alibaba/excel/write/handler/AbstractCellWriteHandler.java +++ b/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> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { + List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { } } diff --git a/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java index 5cf16c1b..fd144e1c 100644 --- a/src/main/java/com/alibaba/excel/write/handler/CellWriteHandler.java +++ b/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> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {} + List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {} } diff --git a/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java b/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java index 16897076..284397b6 100644 --- a/src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java +++ b/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 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; } diff --git a/src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java index e12d98f6..afef0c97 100644 --- a/src/main/java/com/alibaba/excel/write/handler/RowWriteHandler.java +++ b/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. * diff --git a/src/main/java/com/alibaba/excel/write/handler/SheetWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/SheetWriteHandler.java index 5490fd39..67672b7d 100644 --- a/src/main/java/com/alibaba/excel/write/handler/SheetWriteHandler.java +++ b/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 * diff --git a/src/main/java/com/alibaba/excel/write/handler/WorkbookWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/WorkbookWriteHandler.java index c3b758f5..140d226c 100644 --- a/src/main/java/com/alibaba/excel/write/handler/WorkbookWriteHandler.java +++ b/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 * diff --git a/src/main/java/com/alibaba/excel/write/handler/context/CellWriteHandlerContext.java b/src/main/java/com/alibaba/excel/write/handler/context/CellWriteHandlerContext.java new file mode 100644 index 00000000..6dd9a988 --- /dev/null +++ b/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> cellDataList; + /** + * Nullable.It is null in the case of fill data. + */ + private Boolean head; +} diff --git a/src/main/java/com/alibaba/excel/write/handler/context/RowWriteHandlerContext.java b/src/main/java/com/alibaba/excel/write/handler/context/RowWriteHandlerContext.java new file mode 100644 index 00000000..6578d3a2 --- /dev/null +++ b/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; +} diff --git a/src/main/java/com/alibaba/excel/write/handler/context/SheetWriteHandlerContext.java b/src/main/java/com/alibaba/excel/write/handler/context/SheetWriteHandlerContext.java new file mode 100644 index 00000000..c1164eb0 --- /dev/null +++ b/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; +} diff --git a/src/main/java/com/alibaba/excel/write/handler/context/WorkbookWriteHandlerContext.java b/src/main/java/com/alibaba/excel/write/handler/context/WorkbookWriteHandlerContext.java new file mode 100644 index 00000000..f955d4bf --- /dev/null +++ b/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; +} diff --git a/src/main/java/com/alibaba/excel/write/handler/impl/DefaultRowWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/impl/DefaultRowWriteHandler.java index 36f5ed09..2d1f3f77 100644 --- a/src/main/java/com/alibaba/excel/write/handler/impl/DefaultRowWriteHandler.java +++ b/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()); } + } diff --git a/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java deleted file mode 100644 index 2186f381..00000000 --- a/src/main/java/com/alibaba/excel/write/handler/impl/FillDataFormatCellWriteHandler.java +++ /dev/null @@ -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 cellStyleSet = new HashSet<>(); - - private CellStyle defaultDateCellStyle; - - @Override - public int order() { - return OrderConstant.FILL_DATA_FORMAT; - } - - @Override - public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, - List> 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; - } - -} diff --git a/src/main/java/com/alibaba/excel/write/handler/impl/FillStyleCellWriteHandler.java b/src/main/java/com/alibaba/excel/write/handler/impl/FillStyleCellWriteHandler.java new file mode 100644 index 00000000..9956ea19 --- /dev/null +++ b/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> 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)); + } + +} diff --git a/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java b/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java index 21e80716..70db8a01 100644 --- a/src/main/java/com/alibaba/excel/write/merge/AbstractMergeStrategy.java +++ b/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> 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()); } /** diff --git a/src/main/java/com/alibaba/excel/write/metadata/WriteTable.java b/src/main/java/com/alibaba/excel/write/metadata/WriteTable.java index a7bcc814..a935f326 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/WriteTable.java +++ b/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; - } } diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java index 80f858e7..d667b1b3 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java +++ b/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 handlerList = new ArrayList(); @@ -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()); - } - 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 columnWidthMap) { - if (columnWidthMap == null || columnWidthMap.isEmpty()) { - return; - } - if (writeBasicParameter.getCustomWriteHandlerList() == null) { - writeBasicParameter.setCustomWriteHandlerList(new ArrayList()); - } - 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 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, List> getWriteHandlerMap() { - return writeHandlerMap; - } - - public void setWriteHandlerMap(Map, List> writeHandlerMap) { - this.writeHandlerMap = writeHandlerMap; - } - - public Map, List> getOwnWriteHandlerMap() { - return ownWriteHandlerMap; - } - - public void setOwnWriteHandlerMap( - Map, List> 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 getExcludeColumnIndexes() { - return excludeColumnIndexes; - } - - public void setExcludeColumnIndexes(Collection excludeColumnIndexes) { - this.excludeColumnIndexes = excludeColumnIndexes; - } - - public Collection getExcludeColumnFieldNames() { - return excludeColumnFieldNames; - } - - public void setExcludeColumnFieldNames(Collection excludeColumnFieldNames) { - this.excludeColumnFieldNames = excludeColumnFieldNames; - } - - public Collection getIncludeColumnIndexes() { - return includeColumnIndexes; - } - - public void setIncludeColumnIndexes(Collection includeColumnIndexes) { - this.includeColumnIndexes = includeColumnIndexes; - } - - public Collection getIncludeColumnFieldNames() { - return includeColumnFieldNames; - } - - public void setIncludeColumnFieldNames(Collection includeColumnFieldNames) { - this.includeColumnFieldNames = includeColumnFieldNames; - } - @Override public ExcelWriteHeadProperty excelWriteHeadProperty() { return getExcelWriteHeadProperty(); diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java index a48e39e8..cfbfcf4d 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java +++ b/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 cellStyleMap; + /** + * Used to font. + */ + private Map fontMap; /** - * Used to cache data Format. + * Used to data format. */ - private Map dataFormatCache; + private Map 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; } diff --git a/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java b/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java index 8661897b..4b76805b 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/style/WriteCellStyle.java +++ b/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 true 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 Note: Ensure Foreground color is set prior to background color. * * @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()); diff --git a/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java index 9442e4e2..9a918b27 100644 --- a/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java +++ b/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> 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()); } /** diff --git a/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java index 4ae5ac6a..8ba8bd2c 100644 --- a/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java +++ b/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>> headCellStyleCache = MapUtils.newHashMap(); - private final Map>> 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 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) { - return; - } - Map styleMap = getStyleMap(contentCellStyleCache, writeSheetHolder, writeTableHolder); - - int columnIndex = head.getColumnIndex(); - if (styleMap.containsKey(columnIndex)) { - CellStyle cellStyle = styleMap.get(columnIndex); - if (cellStyle != null) { - cell.setCellStyle(cellStyle); - } + protected void setContentCellStyle(CellWriteHandlerContext context) { + if (!continueProcessing(context)) { 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 getStyleMap(Map>> cellStyleCache, - WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder) { - Map> tableStyleMap = cellStyleCache.computeIfAbsent( - writeSheetHolder.getSheetNo(), key -> MapUtils.newHashMap()); - Integer tableNo = 0; - if (writeTableHolder != null) { - tableNo = writeTableHolder.getTableNo(); + protected boolean continueProcessing(CellWriteHandlerContext context) { + List> cellDataList = context.getCellDataList(); + if (CollectionUtils.isEmpty(cellDataList) || cellDataList.size() > 1) { + return false; } - return tableStyleMap.computeIfAbsent(tableNo, key -> MapUtils.newHashMap()); + return context.getHeadData() != null; } - } diff --git a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java index c8914f55..0d4228f5 100644 --- a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java +++ b/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 contentWriteCellStyleList; + private WriteCellStyle headWriteCellStyle; + private List contentWriteCellStyleList; public HorizontalCellStyleStrategy(WriteCellStyle headWriteCellStyle, List 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()); } } diff --git a/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java index 3037fbc9..e33f74e0 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/AbstractColumnWidthStyleStrategy.java +++ b/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> 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> cellDataList, Cell cell, - Head head, Integer relativeRowIndex, Boolean isHead); + protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List> cellDataList, Cell cell, + Head head, Integer relativeRowIndex, Boolean isHead) { + throw new UnsupportedOperationException("Custom styles must override the setColumnWidth method."); + } } diff --git a/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java index b388bc44..e18c845c 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java @@ -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> cellDataList, Cell cell, Head head, + protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { boolean needSetWidth = relativeRowIndex != null && (isHead || relativeRowIndex == 0); if (!needSetWidth) { diff --git a/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java index 1010163e..d248de13 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/LongestMatchColumnWidthStyleStrategy.java +++ b/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. *

@@ -24,10 +25,11 @@ public class LongestMatchColumnWidthStyleStrategy extends AbstractColumnWidthSty private static final int MAX_COLUMN_WIDTH = 255; - private Map> cache = new HashMap>(8); + private final Map> cache = MapUtils.newHashMapWithExpectedSize(8); @Override - protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List> cellDataList, Cell cell, Head head, + protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List> 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> cellDataList, Cell cell, Boolean isHead) { + private Integer dataLength(List> 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; diff --git a/src/main/java/com/alibaba/excel/write/style/row/AbstractRowHeightStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/row/AbstractRowHeightStyleStrategy.java index 303c8180..6c908eb6 100644 --- a/src/main/java/com/alibaba/excel/write/style/row/AbstractRowHeightStyleStrategy.java +++ b/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()); } } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java index 3108f97a..6971c076 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java +++ b/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 { 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))); } } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java index fdedb1ef..61d2809c 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java +++ b/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 data() throws Exception { List list = new ArrayList(); 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 integer1 = new CellData(); 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; diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityData.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityData.java deleted file mode 100644 index c0d9d89f..00000000 --- a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityData.java +++ /dev/null @@ -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; -} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataListener.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataListener.java deleted file mode 100644 index 29774ba9..00000000 --- a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataListener.java +++ /dev/null @@ -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> { - private static final Logger LOGGER = LoggerFactory.getLogger(AnnotationDataListener.class); - List> list = new ArrayList>(); - - @Override - public void invoke(List data, AnalysisContext context) { - list.add(data); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - Assert.assertEquals(list.size(), 10); - List data = list.get(0); - Assert.assertEquals(data.get(0), "字符串00"); - LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0))); - } -} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java deleted file mode 100644 index 87edf636..00000000 --- a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java +++ /dev/null @@ -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 data = EasyExcel.read(inputStream, new Sheet(1, 1)); - Assert.assertEquals(data.size(), 1); - List dataList = (List)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> head() { - List> list = new ArrayList>(); - List head0 = new ArrayList(); - head0.add("字符串标题0"); - List head1 = new ArrayList(); - head1.add("字符串标题1"); - list.add(head0); - list.add(head1); - return list; - } - - private List> listData() { - List> list = new ArrayList>(); - List data0 = new ArrayList(); - data0.add("字符串00"); - data0.add(11); - list.add(data0); - return list; - } - - private List data() { - List list = new ArrayList(); - 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; - } -} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java deleted file mode 100644 index 9890f894..00000000 --- a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java +++ /dev/null @@ -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 data() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - CompatibilityData data = new CompatibilityData(); - data.setString0("字符串0" + i); - data.setString1("字符串1" + i); - list.add(data); - } - return list; - } - -} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java deleted file mode 100644 index 6ff7bbfb..00000000 --- a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java +++ /dev/null @@ -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; -} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java index 619415c6..68daf41e 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java +++ b/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; } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java index 3b3b8d1a..4725595c 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java +++ b/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; } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java b/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java index 0a852c0f..a6f07014 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandler.java +++ b/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> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { + List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { if (isHead) { Assert.assertEquals(1L, beforeCellCreate); Assert.assertEquals(1L, afterCellCreate); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java index 4e170944..843ac964 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java +++ b/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); diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/read/CustomStringStringConverter.java b/src/test/java/com/alibaba/easyexcel/test/demo/read/CustomStringStringConverter.java index 6116c852..406b2896 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/read/CustomStringStringConverter.java +++ b/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 { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return String.class; } @@ -34,7 +35,7 @@ public class CustomStringStringConverter implements Converter { * @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 { * @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); } } diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java index e9567a27..960eda40 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomCellWriteHandler.java +++ b/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> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { + List> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { // 这里可以对cell进行任何操作 LOGGER.info("第{}行,第{}列写入完成。", cell.getRowIndex(), cell.getColumnIndex()); if (isHead && cell.getColumnIndex() == 0) { diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomStringStringConverter.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomStringStringConverter.java index 53aec631..5ea599be 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/CustomStringStringConverter.java +++ b/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 { @Override - public Class supportJavaTypeKey() { + public Class supportJavaTypeKey() { return String.class; } @@ -25,16 +26,13 @@ public class CustomStringStringConverter implements Converter { /** * 这里是读的时候会调用 不用管 * - * @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 { /** * 这里是写的时候会调用 不用管 * - * @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); } } diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatData.java b/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatData.java index ae663254..86303729 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatData.java +++ b/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 date; - private CellData num; + private ReadCellData date; + private ReadCellData num; } diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatTest.java index 53902240..4440f350 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatTest.java +++ b/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) { diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/read/HeadReadTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/read/HeadReadTest.java index 40aa4b8f..99fccd70 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/read/HeadReadTest.java +++ b/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 { diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java b/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java index d8825f0c..b92005c7 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/simple/WriteCellHandler.java +++ b/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(); From 4d2b025592b3d25e253ee8fc5ed66491393b7f11 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Thu, 6 May 2021 22:33:52 +0800 Subject: [PATCH 064/129] =?UTF-8?q?=E5=AE=8C=E6=88=90=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handlers/AbstractCellValueTagHandler.java | 4 +- .../excel/metadata/data/DataFormatData.java | 8 ++++ .../excel/metadata/data/FormulaData.java | 7 ++++ .../excel/metadata/data/ReadCellData.java | 18 +++++++-- .../alibaba/excel/support/ExcelTypeEnum.java | 6 +-- .../alibaba/excel/util/ConverterUtils.java | 30 +++++++++------ .../core/celldata/CellDataDataListener.java | 10 ++--- .../test/core/celldata/CellDataDataTest.java | 13 +++---- .../test/core/celldata/CellDataReadData.java | 18 +++++++++ ...llDataData.java => CellDataWriteData.java} | 10 ++--- .../core/converter/ConverterDataListener.java | 16 ++++---- .../core/converter/ConverterDataTest.java | 34 ++++++++--------- .../core/converter/ConverterReadData.java | 38 +++++++++++++++++++ ...erterData.java => ConverterWriteData.java} | 2 +- .../test/core/encrypt/EncryptDataTest.java | 12 +++--- 15 files changed, 156 insertions(+), 70 deletions(-) create mode 100644 src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataReadData.java rename src/test/java/com/alibaba/easyexcel/test/core/celldata/{CellDataData.java => CellDataWriteData.java} (55%) create mode 100644 src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterReadData.java rename src/test/java/com/alibaba/easyexcel/test/core/converter/{ConverterData.java => ConverterWriteData.java} (96%) diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java index ac2b8457..e37ea6bc 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java @@ -4,7 +4,7 @@ import java.math.BigDecimal; import com.alibaba.excel.context.xlsx.XlsxReadContext; import com.alibaba.excel.enums.CellDataTypeEnum; -import com.alibaba.excel.metadata.data.CellData; +import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder; import com.alibaba.excel.util.BooleanUtils; import com.alibaba.excel.util.StringUtils; @@ -19,7 +19,7 @@ public abstract class AbstractCellValueTagHandler extends AbstractXlsxTagHandler @Override public void endElement(XlsxReadContext xlsxReadContext, String name) { XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder(); - CellData tempCellData = xlsxReadSheetHolder.getTempCellData(); + ReadCellData tempCellData = xlsxReadSheetHolder.getTempCellData(); StringBuilder tempData = xlsxReadSheetHolder.getTempData(); String tempDataString = tempData.toString(); CellDataTypeEnum oldType = tempCellData.getType(); diff --git a/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java b/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java index 3ac70781..7f1a14c8 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java +++ b/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java @@ -18,4 +18,12 @@ public class DataFormatData { * format */ private String format; + + @Override + public DataFormatData clone() { + DataFormatData dataFormatData = new DataFormatData(); + dataFormatData.setIndex(getIndex()); + dataFormatData.setFormat(getFormat()); + return dataFormatData; + } } diff --git a/src/main/java/com/alibaba/excel/metadata/data/FormulaData.java b/src/main/java/com/alibaba/excel/metadata/data/FormulaData.java index cdf91055..36d0206b 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/FormulaData.java +++ b/src/main/java/com/alibaba/excel/metadata/data/FormulaData.java @@ -13,4 +13,11 @@ public class FormulaData { * formula */ private String formulaValue; + + @Override + public FormulaData clone() { + FormulaData formulaData = new FormulaData(); + formulaData.setFormulaValue(getFormulaValue()); + return formulaData; + } } diff --git a/src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java b/src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java index 90cf9a5a..68231a19 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java +++ b/src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java @@ -20,7 +20,6 @@ public class ReadCellData extends CellData { */ private DataFormatData dataFormatData; - public ReadCellData(CellDataTypeEnum type) { super(); if (type == null) { @@ -104,10 +103,21 @@ public class ReadCellData extends CellData { return cellData; } - @Override - public ReadCellData clone(){ - return new ReadCellData<>(""); + public ReadCellData clone() { + ReadCellData readCellData = new ReadCellData<>(); + readCellData.setType(getType()); + readCellData.setNumberValue(getNumberValue()); + readCellData.setStringValue(getStringValue()); + readCellData.setBooleanValue(getBooleanValue()); + readCellData.setData(getData()); + if (getDataFormatData() != null) { + readCellData.setDataFormatData(getDataFormatData().clone()); + } + if (getFormulaData() != null) { + readCellData.setFormulaData(getFormulaData().clone()); + } + return readCellData; } } diff --git a/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java b/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java index cdca07fd..fd90e485 100644 --- a/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java +++ b/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java @@ -5,13 +5,13 @@ import java.io.File; import java.io.FileInputStream; import java.io.InputStream; -import org.apache.poi.poifs.filesystem.FileMagic; - import com.alibaba.excel.exception.ExcelAnalysisException; import com.alibaba.excel.exception.ExcelCommonException; import com.alibaba.excel.read.metadata.ReadWorkbook; import com.alibaba.excel.util.StringUtils; +import org.apache.poi.poifs.filesystem.FileMagic; + /** * @author jipengfei */ @@ -78,8 +78,6 @@ public enum ExcelTypeEnum { return recognitionExcelType(inputStream); } catch (ExcelCommonException e) { throw e; - } catch (ExcelAnalysisException e) { - throw e; } catch (Exception e) { throw new ExcelCommonException( "Convert excel format exception.You can try specifying the 'excelType' yourself", e); diff --git a/src/main/java/com/alibaba/excel/util/ConverterUtils.java b/src/main/java/com/alibaba/excel/util/ConverterUtils.java index 029c8196..e0e139f7 100644 --- a/src/main/java/com/alibaba/excel/util/ConverterUtils.java +++ b/src/main/java/com/alibaba/excel/util/ConverterUtils.java @@ -11,7 +11,6 @@ import com.alibaba.excel.converters.ConverterKeyBuild; import com.alibaba.excel.converters.ReadConverterContext; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.exception.ExcelDataConvertException; -import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; @@ -22,6 +21,7 @@ import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; * @author Jiaju Zhuang **/ public class ConverterUtils { + public static Class defaultClassGeneric = String.class; private ConverterUtils() {} @@ -87,16 +87,8 @@ public class ConverterUtils { } else { clazz = field.getType(); } - if (clazz == CellData.class) { - Type type = field.getGenericType(); - Class classGeneric; - if (type instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType)type; - classGeneric = (Class)parameterizedType.getActualTypeArguments()[0]; - } else { - classGeneric = String.class; - } - + if (clazz == ReadCellData.class) { + Class classGeneric = getClassGeneric(field.getGenericType()); ReadCellData cellDataReturn = cellData.clone(); cellDataReturn.setData(doConvertToJavaObject(cellData, classGeneric, contentProperty, converterMap, context, rowIndex, columnIndex)); @@ -106,6 +98,22 @@ public class ConverterUtils { columnIndex); } + private static Class getClassGeneric(Type type) { + if (!(type instanceof ParameterizedType)) { + return defaultClassGeneric; + } + ParameterizedType parameterizedType = (ParameterizedType)type; + Type[] types = parameterizedType.getActualTypeArguments(); + if (types == null || types.length == 0) { + return defaultClassGeneric; + } + Type actualType = types[0]; + if (!(actualType instanceof Class)) { + return defaultClassGeneric; + } + return (Class)actualType; + } + /** * @param cellData * @param clazz diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java index 6971c076..cb6a1105 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java @@ -14,21 +14,21 @@ import org.slf4j.LoggerFactory; /** * @author Jiaju Zhuang */ -public class CellDataDataListener extends AnalysisEventListener { +public class CellDataDataListener extends AnalysisEventListener { private static final Logger LOGGER = LoggerFactory.getLogger(CellDataDataListener.class); - List list = new ArrayList(); + List list = new ArrayList<>(); @Override - public void invoke(CellDataData data, AnalysisContext context) { + public void invoke(CellDataReadData data, AnalysisContext context) { list.add(data); } @Override public void doAfterAllAnalysed(AnalysisContext context) { Assert.assertEquals(list.size(), 1); - CellDataData cellDataData = list.get(0); + CellDataReadData cellDataData = list.get(0); - Assert.assertEquals(cellDataData.getDate().getStringValue(), "2020年01月01日"); + Assert.assertEquals(cellDataData.getDate().getData(), "2020年01月01日"); Assert.assertEquals((long)cellDataData.getInteger1().getData(), 2L); Assert.assertEquals((long)cellDataData.getInteger2(), 2L); Assert.assertEquals(cellDataData.getFormulaValue().getFormulaData().getFormulaValue(), "B2+C2"); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java index 61d2809c..db4bf80b 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java @@ -8,7 +8,6 @@ import java.util.List; 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; @@ -44,15 +43,15 @@ public class CellDataDataTest { } private void readAndWrite(File file) throws Exception { - EasyExcel.write(file, CellDataData.class).sheet().doWrite(data()); - EasyExcel.read(file, CellDataData.class, new CellDataDataListener()).sheet().doRead(); + EasyExcel.write(file, CellDataWriteData.class).sheet().doWrite(data()); + EasyExcel.read(file, CellDataReadData.class, new CellDataDataListener()).sheet().doRead(); } - private List data() throws Exception { - List list = new ArrayList(); - CellDataData cellDataData = new CellDataData(); + private List data() throws Exception { + List list = new ArrayList<>(); + CellDataWriteData cellDataData = new CellDataWriteData(); cellDataData.setDate(new WriteCellData<>(DateUtils.parseDate("2020-01-01 01:01:01"))); - CellData integer1 = new CellData(); + WriteCellData integer1 = new WriteCellData<>(); integer1.setType(CellDataTypeEnum.NUMBER); integer1.setNumberValue(BigDecimal.valueOf(2L)); cellDataData.setInteger1(integer1); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataReadData.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataReadData.java new file mode 100644 index 00000000..b8322073 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataReadData.java @@ -0,0 +1,18 @@ +package com.alibaba.easyexcel.test.core.celldata; + +import com.alibaba.excel.annotation.format.DateTimeFormat; +import com.alibaba.excel.metadata.data.ReadCellData; + +import lombok.Data; + +/** + * @author Jiaju Zhuang + */ +@Data +public class CellDataReadData { + @DateTimeFormat("yyyy年MM月dd日") + private ReadCellData date; + private ReadCellData integer1; + private Integer integer2; + private ReadCellData formulaValue; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataData.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataWriteData.java similarity index 55% rename from src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataData.java rename to src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataWriteData.java index bed0685d..69ed7bbf 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataData.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataWriteData.java @@ -3,7 +3,7 @@ package com.alibaba.easyexcel.test.core.celldata; import java.util.Date; import com.alibaba.excel.annotation.format.DateTimeFormat; -import com.alibaba.excel.metadata.data.CellData; +import com.alibaba.excel.metadata.data.WriteCellData; import lombok.Data; @@ -11,10 +11,10 @@ import lombok.Data; * @author Jiaju Zhuang */ @Data -public class CellDataData { +public class CellDataWriteData { @DateTimeFormat("yyyy年MM月dd日") - private CellData date; - private CellData integer1; + private WriteCellData date; + private WriteCellData integer1; private Integer integer2; - private CellData formulaValue; + private WriteCellData formulaValue; } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataListener.java b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataListener.java index 210ca142..411700f0 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataListener.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataListener.java @@ -5,32 +5,32 @@ import java.text.ParseException; 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.excel.exception.ExcelCommonException; import com.alibaba.excel.util.DateUtils; import com.alibaba.fastjson.JSON; +import org.junit.Assert; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * @author Jiaju Zhuang */ -public class ConverterDataListener extends AnalysisEventListener { +public class ConverterDataListener extends AnalysisEventListener { private static final Logger LOGGER = LoggerFactory.getLogger(ConverterDataListener.class); - List list = new ArrayList(); + private List list = new ArrayList<>(); @Override - public void invoke(ConverterData data, AnalysisContext context) { + public void invoke(ConverterReadData data, AnalysisContext context) { list.add(data); } @Override public void doAfterAllAnalysed(AnalysisContext context) { Assert.assertEquals(list.size(), 1); - ConverterData data = list.get(0); + ConverterReadData data = list.get(0); try { Assert.assertEquals(DateUtils.parseDate("2020-01-01 01:01:01"), data.getDate()); } catch (ParseException e) { diff --git a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java index 4725595c..45f09be1 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterDataTest.java @@ -48,8 +48,8 @@ public class ConverterDataTest { } private void readAndWrite(File file) throws Exception { - EasyExcel.write(file, ConverterData.class).sheet().doWrite(data()); - EasyExcel.read(file, ConverterData.class, new ConverterDataListener()).sheet().doRead(); + EasyExcel.write(file, ConverterWriteData.class).sheet().doWrite(data()); + EasyExcel.read(file, ConverterReadData.class, new ConverterDataListener()).sheet().doRead(); } @Test @@ -97,21 +97,21 @@ public class ConverterDataTest { .sheet().doRead(); } - private List data() throws Exception { - List list = new ArrayList(); - ConverterData converterData = new ConverterData(); - converterData.setDate(DateUtils.parseDate("2020-01-01 01:01:01")); - converterData.setBooleanData(Boolean.TRUE); - converterData.setBigDecimal(BigDecimal.ONE); - converterData.setLongData(1L); - converterData.setIntegerData(1); - converterData.setShortData((short)1); - converterData.setByteData((byte)1); - converterData.setDoubleData(1.0); - converterData.setFloatData((float)1.0); - converterData.setString("测试"); - converterData.setCellData(new WriteCellData<>("自定义")); - list.add(converterData); + private List data() throws Exception { + List list = new ArrayList(); + ConverterWriteData converterWriteData = new ConverterWriteData(); + converterWriteData.setDate(DateUtils.parseDate("2020-01-01 01:01:01")); + converterWriteData.setBooleanData(Boolean.TRUE); + converterWriteData.setBigDecimal(BigDecimal.ONE); + converterWriteData.setLongData(1L); + converterWriteData.setIntegerData(1); + converterWriteData.setShortData((short)1); + converterWriteData.setByteData((byte)1); + converterWriteData.setDoubleData(1.0); + converterWriteData.setFloatData((float)1.0); + converterWriteData.setString("测试"); + converterWriteData.setCellData(new WriteCellData<>("自定义")); + list.add(converterWriteData); return list; } } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterReadData.java b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterReadData.java new file mode 100644 index 00000000..bf7af176 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterReadData.java @@ -0,0 +1,38 @@ +package com.alibaba.easyexcel.test.core.converter; + +import java.math.BigDecimal; +import java.util.Date; + +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.metadata.data.ReadCellData; + +import lombok.Data; + +/** + * @author Jiaju Zhuang + */ +@Data +public class ConverterReadData { + @ExcelProperty("日期") + private Date date; + @ExcelProperty("布尔") + private Boolean booleanData; + @ExcelProperty("大数") + private BigDecimal bigDecimal; + @ExcelProperty("长整型") + private long longData; + @ExcelProperty("整型") + private Integer integerData; + @ExcelProperty("短整型") + private Short shortData; + @ExcelProperty("字节型") + private Byte byteData; + @ExcelProperty("双精度浮点型") + private double doubleData; + @ExcelProperty("浮点型") + private Float floatData; + @ExcelProperty("字符串") + private String string; + @ExcelProperty("自定义") + private ReadCellData cellData; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterWriteData.java similarity index 96% rename from src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java rename to src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterWriteData.java index 68daf41e..009fae2e 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterData.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/converter/ConverterWriteData.java @@ -12,7 +12,7 @@ import lombok.Data; * @author Jiaju Zhuang */ @Data -public class ConverterData { +public class ConverterWriteData { @ExcelProperty("日期") private Date date; @ExcelProperty("布尔") diff --git a/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataTest.java index 375f9bea..5569492e 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataTest.java @@ -6,16 +6,16 @@ import java.io.FileOutputStream; 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.core.simple.SimpleData; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.support.ExcelTypeEnum; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + /** * * @author Jiaju Zhuang @@ -30,7 +30,7 @@ public class EncryptDataTest { @BeforeClass public static void init() { - file07 = TestFileUtil.createNewFile("encrypt07.xlsx"); + file07 = TestFileUtil.createNewFile("encrypt07111.xlsx"); file03 = TestFileUtil.createNewFile("encrypt03.xls"); file07OutputStream = TestFileUtil.createNewFile("encryptOutputStream07.xlsx"); file03OutputStream = TestFileUtil.createNewFile("encryptOutputStream03.xls"); From d0a55912cad8c1af4762ddd8d9dc27b30f8fd509 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 7 May 2021 10:30:20 +0800 Subject: [PATCH 065/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8A=A0=E5=AF=86?= =?UTF-8?q?=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/context/WriteContextImpl.java | 38 +++------ .../alibaba/excel/metadata/NullObject.java | 9 +++ .../com/alibaba/excel/util/FieldUtils.java | 54 ++++++++----- .../java/com/alibaba/excel/util/MapUtils.java | 2 + .../write/executor/ExcelWriteAddExecutor.java | 11 +-- .../executor/ExcelWriteFillExecutor.java | 5 +- .../test/core/encrypt/EncryptDataTest.java | 2 +- .../test/temp/poi/PoiEncryptTest.java | 79 +++++++++++++++++++ 8 files changed, 142 insertions(+), 58 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/metadata/NullObject.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/poi/PoiEncryptTest.java diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java index 2b7ced3e..da12189c 100644 --- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java @@ -50,7 +50,7 @@ import org.slf4j.LoggerFactory; public class WriteContextImpl implements WriteContext { private static final Logger LOGGER = LoggerFactory.getLogger(WriteContextImpl.class); - private static final String NO_SHEETS="no sheets"; + private static final String NO_SHEETS = "no sheets"; /** * The Workbook currently written @@ -248,7 +248,8 @@ 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, (WriteCellData) null, cell, head, relativeRowIndex, Boolean.TRUE); + WriteHandlerUtils.afterCellDispose(this, (WriteCellData)null, cell, head, relativeRowIndex, + Boolean.TRUE); } } @@ -351,7 +352,7 @@ public class WriteContextImpl implements WriteContext { try { Workbook workbook = writeWorkbookHolder.getWorkbook(); if (workbook instanceof SXSSFWorkbook) { - ((SXSSFWorkbook) workbook).dispose(); + ((SXSSFWorkbook)workbook).dispose(); } } catch (Throwable t) { throwable = t; @@ -446,14 +447,9 @@ public class WriteContextImpl implements WriteContext { throw e; } } - POIFSFileSystem fileSystem = null; - try { - fileSystem = openFileSystemAndEncrypt(tempXlsx); + try (POIFSFileSystem fileSystem = openFileSystemAndEncrypt(tempXlsx)) { fileSystem.writeFilesystem(writeWorkbookHolder.getOutputStream()); } finally { - if (fileSystem != null) { - fileSystem.close(); - } if (!tempXlsx.delete()) { throw new ExcelGenerateException("Can not delete temp File!"); } @@ -472,19 +468,9 @@ public class WriteContextImpl implements WriteContext { if (writeWorkbookHolder.getFile() == null) { return; } - FileOutputStream fileOutputStream = null; - POIFSFileSystem fileSystem = null; - try { - fileSystem = openFileSystemAndEncrypt(writeWorkbookHolder.getFile()); - fileOutputStream = new FileOutputStream(writeWorkbookHolder.getFile()); + try (POIFSFileSystem fileSystem = openFileSystemAndEncrypt(writeWorkbookHolder.getFile()); + FileOutputStream fileOutputStream = new FileOutputStream(writeWorkbookHolder.getFile())) { fileSystem.writeFilesystem(fileOutputStream); - } finally { - if (fileOutputStream != null) { - fileOutputStream.close(); - } - if (fileSystem != null) { - fileSystem.close(); - } } } @@ -492,15 +478,9 @@ public class WriteContextImpl implements WriteContext { POIFSFileSystem fileSystem = new POIFSFileSystem(); Encryptor encryptor = new EncryptionInfo(EncryptionMode.standard).getEncryptor(); encryptor.confirmPassword(writeWorkbookHolder.getPassword()); - OPCPackage opcPackage = null; - try { - opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE); - OutputStream outputStream = encryptor.getDataStream(fileSystem); + try (OPCPackage opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE); + OutputStream outputStream = encryptor.getDataStream(fileSystem)) { opcPackage.save(outputStream); - } finally { - if (opcPackage != null) { - opcPackage.close(); - } } return fileSystem; } diff --git a/src/main/java/com/alibaba/excel/metadata/NullObject.java b/src/main/java/com/alibaba/excel/metadata/NullObject.java new file mode 100644 index 00000000..845d98a1 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/NullObject.java @@ -0,0 +1,9 @@ +package com.alibaba.excel.metadata; + +/** + * Null object. + * + * @author Jiaju Zhuang + */ +public class NullObject { +} diff --git a/src/main/java/com/alibaba/excel/util/FieldUtils.java b/src/main/java/com/alibaba/excel/util/FieldUtils.java index 1e788907..fd692235 100644 --- a/src/main/java/com/alibaba/excel/util/FieldUtils.java +++ b/src/main/java/com/alibaba/excel/util/FieldUtils.java @@ -2,7 +2,12 @@ package com.alibaba.excel.util; import java.lang.reflect.Field; import java.lang.reflect.Modifier; +import java.util.Map; +import com.alibaba.excel.metadata.NullObject; +import com.alibaba.excel.write.metadata.RowData; + +import net.sf.cglib.beans.BeanMap; /** * Field utils @@ -11,8 +16,29 @@ import java.lang.reflect.Modifier; **/ public class FieldUtils { + public static Class nullObjectClass = NullObject.class; + private static final int START_RESOLVE_FIELD_LENGTH = 2; + public static Class getFieldClass(Map dataMap, String filedName) { + if (dataMap instanceof BeanMap) { + return ((BeanMap)dataMap).getPropertyType(filedName); + } + Object value = dataMap.get(filedName); + if (value != null) { + return value.getClass(); + } + return nullObjectClass; + } + + public static Class getFieldClass(RowData rowData, int dataIndex) { + Object value = rowData.get(dataIndex); + if (value != null) { + return value.getClass(); + } + return nullObjectClass; + } + /** * Parsing the name matching cglib。 *
    @@ -51,17 +77,13 @@ public class FieldUtils { return firstChar + fieldName.substring(1); } - /** * Gets an accessible {@link Field} by name respecting scope. Superclasses/interfaces will be considered. * - * @param cls - * the {@link Class} to reflect, must not be {@code null} - * @param fieldName - * the field name to obtain + * @param cls the {@link Class} to reflect, must not be {@code null} + * @param fieldName the field name to obtain * @return the Field object - * @throws IllegalArgumentException - * if the class is {@code null}, or the field name is blank or empty + * @throws IllegalArgumentException if the class is {@code null}, or the field name is blank or empty */ public static Field getField(final Class cls, final String fieldName) { final Field field = getField(cls, fieldName, false); @@ -69,20 +91,16 @@ public class FieldUtils { return field; } - - /** * Gets an accessible {@link Field} by name, breaking scope if requested. Superclasses/interfaces will be * considered. * - * @param cls - * the {@link Class} to reflect, must not be {@code null} - * @param fieldName - * the field name to obtain - * @param forceAccess - * whether to break scope restrictions using the - * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only - * match {@code public} fields. + * @param cls the {@link Class} to reflect, must not be {@code null} + * @param fieldName the field name to obtain + * @param forceAccess whether to break scope restrictions using the + * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will + * only + * match {@code public} fields. * @return the Field object * @throws NullPointerException if the class is {@code null} * @throws IllegalArgumentException if the field name is blank or empty or is matched at multiple places @@ -140,6 +158,4 @@ public class FieldUtils { return match; } - - } diff --git a/src/main/java/com/alibaba/excel/util/MapUtils.java b/src/main/java/com/alibaba/excel/util/MapUtils.java index 2ecee78a..eb4409a3 100644 --- a/src/main/java/com/alibaba/excel/util/MapUtils.java +++ b/src/main/java/com/alibaba/excel/util/MapUtils.java @@ -9,8 +9,10 @@ import java.util.LinkedHashMap; * @author Jiaju Zhuang **/ public class MapUtils { + private MapUtils() {} + /** * Creates a mutable, empty {@code HashMap} instance. * diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index b1777c02..d2677d3d 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -113,8 +113,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { WriteHandlerUtils.afterCellCreate(writeContext, cell, head, relativeRowIndex, Boolean.FALSE); Object value = oneRowData.get(dataIndex); WriteCellData cellData = converterAndSet(writeContext.currentWriteHolder(), - value == null ? null : value.getClass(), - null, cell, value, null, head, relativeRowIndex); + FieldUtils.getFieldClass(oneRowData, dataIndex), null, cell, value, null, head, relativeRowIndex); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE); } @@ -143,8 +142,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { Object value = beanMap.get(name); WriteCellData cellData = converterAndSet(currentWriteHolder, excelContentProperty.getField().getType(), - null, - cell, value, excelContentProperty, head, relativeRowIndex); + null, cell, value, excelContentProperty, head, relativeRowIndex); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE); beanMapHandledSet.add(name); } @@ -168,9 +166,8 @@ 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); - WriteCellData cellData = converterAndSet(currentWriteHolder, value == null ? null : value.getClass(), - null, cell, - value, null, null, relativeRowIndex); + WriteCellData cellData = converterAndSet(currentWriteHolder, + FieldUtils.getFieldClass(beanMap, filedName), null, cell, value, null, null, relativeRowIndex); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, relativeRowIndex, Boolean.FALSE); } } diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 7675bcf3..fd3802c0 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -16,6 +16,7 @@ import com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum; import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; +import com.alibaba.excel.util.FieldUtils; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.util.WriteHandlerUtils; import com.alibaba.excel.write.metadata.fill.AnalysisCell; @@ -198,8 +199,8 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { continue; } Object value = dataMap.get(variable); - WriteCellData cellData = converterAndSet(writeSheetHolder, value == null ? null : value.getClass(), null, - cell, value, fieldNameContentPropertyMap.get(variable), null, relativeRowIndex); + WriteCellData cellData = converterAndSet(writeSheetHolder, FieldUtils.getFieldClass(dataMap, variable), + null, cell, value, fieldNameContentPropertyMap.get(variable), null, relativeRowIndex); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, relativeRowIndex, Boolean.FALSE); } else { StringBuilder cellValueBuild = new StringBuilder(); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataTest.java index 5569492e..d2c12a70 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataTest.java @@ -30,7 +30,7 @@ public class EncryptDataTest { @BeforeClass public static void init() { - file07 = TestFileUtil.createNewFile("encrypt07111.xlsx"); + file07 = TestFileUtil.createNewFile("encrypt07.xlsx"); file03 = TestFileUtil.createNewFile("encrypt03.xls"); file07OutputStream = TestFileUtil.createNewFile("encryptOutputStream07.xlsx"); file03OutputStream = TestFileUtil.createNewFile("encryptOutputStream03.xls"); diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/poi/PoiEncryptTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/poi/PoiEncryptTest.java new file mode 100644 index 00000000..67b6cfc7 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/poi/PoiEncryptTest.java @@ -0,0 +1,79 @@ +package com.alibaba.easyexcel.test.temp.poi; + +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.easyexcel.test.core.encrypt.EncryptData; +import com.alibaba.easyexcel.test.core.simple.SimpleData; +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; + +import org.apache.poi.poifs.crypt.EncryptionInfo; +import org.apache.poi.poifs.crypt.EncryptionMode; +import org.apache.poi.poifs.crypt.Encryptor; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.Ignore; +import org.junit.Test; + +/** + * TODO + * + * @author Jiaju Zhuang + */ +@Ignore +public class PoiEncryptTest { + @Test + public void encrypt() throws Exception { + + + + XSSFWorkbook workbook = new XSSFWorkbook(); + SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(workbook); + + Sheet sheet = sxssfWorkbook.createSheet("sheet1"); + sheet.createRow(0).createCell(0).setCellValue("T2"); + + + POIFSFileSystem fs = new POIFSFileSystem(); + EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile); + + Encryptor enc = info.getEncryptor(); + enc.confirmPassword("123456"); + + // write the workbook into the encrypted OutputStream + OutputStream encos = enc.getDataStream(fs); + sxssfWorkbook.write(encos); + sxssfWorkbook.dispose(); + sxssfWorkbook.close(); + encos.close(); // this is necessary before writing out the FileSystem + + OutputStream os = new FileOutputStream( + TestFileUtil.createNewFile("encrypt" + System.currentTimeMillis() + ".xlsx")); + fs.writeFilesystem(os); + os.close(); + fs.close(); + } + + @Test + public void encryptExcel() throws Exception { + EasyExcel.write(TestFileUtil.createNewFile("encryptv2" + System.currentTimeMillis() + ".xlsx"), + EncryptData.class).password("123456") + .sheet().doWrite(data()); + } + + private List data() { + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + SimpleData simpleData = new SimpleData(); + simpleData.setName("姓名" + i); + list.add(simpleData); + } + return list; + } + +} From 54c9c36a64798cbfdb89451a4ea943a0554fec29 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 7 May 2021 10:35:52 +0800 Subject: [PATCH 066/129] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../annotation/write/style/ImagePosition.java | 61 -------- .../property/ImagePositionProperty.java | 135 ------------------ .../alibaba/excel/support/ExcelTypeEnum.java | 10 +- .../demo/write/ImageDataWithAnnotation.java | 6 - .../easyexcel/test/demo/write/WriteTest.java | 45 +----- 5 files changed, 8 insertions(+), 249 deletions(-) delete mode 100644 src/main/java/com/alibaba/excel/annotation/write/style/ImagePosition.java delete mode 100644 src/main/java/com/alibaba/excel/metadata/property/ImagePositionProperty.java diff --git a/src/main/java/com/alibaba/excel/annotation/write/style/ImagePosition.java b/src/main/java/com/alibaba/excel/annotation/write/style/ImagePosition.java deleted file mode 100644 index 8a401122..00000000 --- a/src/main/java/com/alibaba/excel/annotation/write/style/ImagePosition.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.alibaba.excel.annotation.write.style; - - -import org.apache.poi.ss.usermodel.ClientAnchor; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.annotation.Retention; - -/** - * This annotation is used to set the position of a picture. - * See {@link ClientAnchor} - */ - -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -@Inherited -public @interface ImagePosition { - - /** - * The x coordinate within the first cell. - */ - int dx1(); - - /** - * The y coordinate within the first cell. - */ - int dy1(); - - /** - * The x coordinate within the second cell. - */ - int dx2(); - - /** - * The y coordinate within the second cell - */ - int dy2(); - - /** - * 0-based column of the first cell. - */ - short col1(); - - /** - * 0-based row of the first cell. - */ - int row1(); - - /** - * 0-based column of the second cell. - */ - short col2(); - - /** - * 0-based row of the second cell. - */ - int row2(); -} diff --git a/src/main/java/com/alibaba/excel/metadata/property/ImagePositionProperty.java b/src/main/java/com/alibaba/excel/metadata/property/ImagePositionProperty.java deleted file mode 100644 index 5bd6fb30..00000000 --- a/src/main/java/com/alibaba/excel/metadata/property/ImagePositionProperty.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.alibaba.excel.metadata.property; - -import com.alibaba.excel.annotation.write.style.ImagePosition; - -/** - * Keep the image position information from an annotation. - * - * @author Pengliang Zhao - */ -public class ImagePositionProperty { - - /** - * The x coordinate within the first cell. - */ - private int dx1; - - /** - * The y coordinate within the first cell. - */ - private int dy1; - - /** - * The x coordinate within the second cell. - */ - private int dx2; - - /** - * The y coordinate within the second cell - */ - private int dy2; - - /** - * 0-based column of the first cell. - */ - private short col1; - - /** - * 0-based row of the first cell. - */ - private int row1; - - /** - * 0-based column of the second cell. - */ - private short col2; - - /** - * 0-based row of the second cell. - */ - private int row2; - - public static ImagePositionProperty build(ImagePosition imagePosition) { - if (imagePosition == null) { - return null; - } - return new ImagePositionProperty(imagePosition.dx1(), imagePosition.dy1(), imagePosition.dx2(), - imagePosition.dy2(), imagePosition.col1(), imagePosition.row1(), imagePosition.col2(), - imagePosition.row2()); - } - - public ImagePositionProperty(int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2) { - this.dx1 = dx1; - this.dy1 = dy1; - this.dx2 = dx2; - this.dy2 = dy2; - this.col1 = col1; - this.row1 = row1; - this.col2 = col2; - this.row2 = row2; - } - - public int getDx1() { - return dx1; - } - - public void setDx1(int dx1) { - this.dx1 = dx1; - } - - public int getDy1() { - return dy1; - } - - public void setDy1(int dy1) { - this.dy1 = dy1; - } - - public int getDx2() { - return dx2; - } - - public void setDx2(int dx2) { - this.dx2 = dx2; - } - - public int getDy2() { - return dy2; - } - - public void setDy2(int dy2) { - this.dy2 = dy2; - } - - public short getCol1() { - return col1; - } - - public void setCol1(short col1) { - this.col1 = col1; - } - - public int getRow1() { - return row1; - } - - public void setRow1(int row1) { - this.row1 = row1; - } - - public short getCol2() { - return col2; - } - - public void setCol2(short col2) { - this.col2 = col2; - } - - public int getRow2() { - return row2; - } - - public void setRow2(int row2) { - this.row2 = row2; - } -} diff --git a/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java b/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java index fd90e485..7158a69c 100644 --- a/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java +++ b/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java @@ -48,11 +48,8 @@ public enum ExcelTypeEnum { } // If there is a password, use the FileMagic first if (!StringUtils.isEmpty(readWorkbook.getPassword())) { - BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file)); - try { + try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) { return recognitionExcelType(bufferedInputStream); - } finally { - bufferedInputStream.close(); } } // Use the name to determine the type @@ -63,11 +60,8 @@ public enum ExcelTypeEnum { return XLS; } if (StringUtils.isEmpty(readWorkbook.getPassword())) { - BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file)); - try { + try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) { return recognitionExcelType(bufferedInputStream); - } finally { - bufferedInputStream.close(); } } } diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDataWithAnnotation.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDataWithAnnotation.java index d76715f6..a7bd7caa 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDataWithAnnotation.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDataWithAnnotation.java @@ -7,7 +7,6 @@ import java.net.URL; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; -import com.alibaba.excel.annotation.write.style.ImagePosition; import com.alibaba.excel.converters.string.StringImageConverter; import lombok.Data; @@ -20,23 +19,18 @@ import lombok.Data; @ContentRowHeight(100) @ColumnWidth(100 / 8) public class ImageDataWithAnnotation { - @ImagePosition(dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0, col1 = 0, row1 = 3, col2 = 1, row2 = 4) private File file; - @ImagePosition(dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0, col1 = 0, row1 = 1, col2 = 2, row2 = 2) private InputStream inputStream; /** * 如果string类型 必须指定转换器,string默认转换成string */ @ExcelProperty(converter = StringImageConverter.class) - @ImagePosition(dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0, col1 = 2, row1 = 1, col2 = 3, row2 = 3) private String string; - @ImagePosition(dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0, col1 = 3, row1 = 1, col2 = 4, row2 = 5) private byte[] byteArray; /** * 根据url导出 * * @since 2.1.1 */ - @ImagePosition(dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0, col1 = 4, row1 = 1, col2 = 5, row2 = 2) private URL url; } diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java index 80cd631f..ced2ffde 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java @@ -9,12 +9,6 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.junit.Ignore; -import org.junit.Test; - import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; @@ -33,6 +27,12 @@ import com.alibaba.excel.write.metadata.style.WriteFont; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy; import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy; +import org.apache.poi.ss.usermodel.FillPatternType; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.xssf.streaming.SXSSFSheet; +import org.junit.Ignore; +import org.junit.Test; + /** * 写的常见写法 * @@ -257,39 +257,6 @@ public class WriteTest { } } - /** - * 使用注解设置图片位置,然后导出 - *

    - * 1. 创建excel对应的实体对象 参照{@link ImageData} - *

    - * 2. 直接写即可 - */ - @Test - public void imageWriteWithAnnotation() throws Exception { - String fileName = TestFileUtil.getPath() + "imageWriteWithAnnotation" + System.currentTimeMillis() + ".xlsx"; - // 如果使用流 记得关闭 - InputStream inputStream = null; - try { - List list = new ArrayList(); - ImageDataWithAnnotation imageData = new ImageDataWithAnnotation(); - list.add(imageData); - String imagePath = TestFileUtil.getPath() + "converter" + File.separator + "img.jpg"; - // 放入五种类型的图片 实际使用只要选一种即可 - imageData.setByteArray(FileUtils.readFileToByteArray(new File(imagePath))); - imageData.setFile(new File(imagePath)); - imageData.setString(imagePath); - inputStream = FileUtils.openInputStream(new File(imagePath)); - imageData.setInputStream(inputStream); - imageData.setUrl(new URL( - "https://raw.githubusercontent.com/alibaba/easyexcel/master/src/test/resources/converter/img.jpg")); - EasyExcel.write(fileName, ImageDataWithAnnotation.class).sheet().doWrite(list); - } finally { - if (inputStream != null) { - inputStream.close(); - } - } - } - /** * 根据模板写入 *

    From b435424383307944a7b47c7283f740c00752d012 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 7 May 2021 13:44:53 +0800 Subject: [PATCH 067/129] =?UTF-8?q?=E5=AE=8C=E6=88=90=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E5=86=99=E5=85=A5=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 1 + .../excel/metadata/data/ClientAnchorData.java | 3 +- .../java/com/alibaba/excel/util/MapUtils.java | 2 +- .../com/alibaba/excel/util/StyleUtil.java | 5 +- .../executor/AbstractExcelWriteExecutor.java | 19 ++++-- .../alibaba/excel/write/metadata/RowData.java | 4 ++ .../{ImageData.java => ImageDemoData.java} | 10 ++- .../easyexcel/test/demo/write/WriteTest.java | 66 ++++++++++++++----- 8 files changed, 82 insertions(+), 28 deletions(-) rename src/test/java/com/alibaba/easyexcel/test/demo/write/{ImageData.java => ImageDemoData.java} (78%) diff --git a/pom.xml b/pom.xml index b5ae5cbf..6477cfef 100644 --- a/pom.xml +++ b/pom.xml @@ -163,6 +163,7 @@ com/alibaba/excel/event/AnalysisEventListener.java com/alibaba/excel/metadata/DataFormatter.java com/alibaba/excel/util/DateUtils.java + com/alibaba/excel/util/MapUtils.java com/alibaba/excel/metadata/format/DataFormatter.java com/alibaba/excel/metadata/format/ExcelGeneralNumberFormat.java diff --git a/src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java b/src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java index 86a93d48..2416635d 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java +++ b/src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java @@ -102,8 +102,7 @@ public class ClientAnchorData extends CoordinateData { ClientAnchor.AnchorType value; - // disallow non-sequential enum instance creation - private AnchorType(ClientAnchor.AnchorType value) { + AnchorType(ClientAnchor.AnchorType value) { this.value = value; } diff --git a/src/main/java/com/alibaba/excel/util/MapUtils.java b/src/main/java/com/alibaba/excel/util/MapUtils.java index eb4409a3..d46da90a 100644 --- a/src/main/java/com/alibaba/excel/util/MapUtils.java +++ b/src/main/java/com/alibaba/excel/util/MapUtils.java @@ -27,7 +27,7 @@ public class MapUtils { * @return a new, empty {@code HashMap} */ public static HashMap newHashMap() { - return new HashMap<>(); + return new HashMap<>(16); } /** diff --git a/src/main/java/com/alibaba/excel/util/StyleUtil.java b/src/main/java/com/alibaba/excel/util/StyleUtil.java index 4f10a1b0..0b70cf9b 100644 --- a/src/main/java/com/alibaba/excel/util/StyleUtil.java +++ b/src/main/java/com/alibaba/excel/util/StyleUtil.java @@ -18,6 +18,7 @@ import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.util.Units; import org.apache.poi.xssf.usermodel.XSSFRichTextString; /** @@ -25,8 +26,6 @@ import org.apache.poi.xssf.usermodel.XSSFRichTextString; */ public class StyleUtil { - public static int baseCoordinate = 10000; - private StyleUtil() {} /** @@ -191,7 +190,7 @@ public class StyleUtil { if (coordinate == null) { return 0; } - return baseCoordinate * coordinate; + return Units.toEMU(coordinate); } public static int getCellCoordinate(Integer currentCoordinate, Integer absoluteCoordinate, diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index 879d16c2..aa8a2578 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -32,6 +32,7 @@ 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.Picture; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFClientAnchor; @@ -61,6 +62,8 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { // Fill in picture information fillImage(cell, cellData.getImageDataList()); + //setImageValue(cellData,cell); + // Fill in comment information fillComment(cell, cellData.getCommentData()); @@ -197,10 +200,10 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { anchor.setDy1(StyleUtil.getCoordinate(imageData.getTop())); } if (imageData.getRight() != null) { - anchor.setDx2(StyleUtil.getCoordinate(imageData.getRight())); + anchor.setDx2(-StyleUtil.getCoordinate(imageData.getRight())); } if (imageData.getBottom() != null) { - anchor.setDy2(StyleUtil.getCoordinate(imageData.getBottom())); + anchor.setDy2(-StyleUtil.getCoordinate(imageData.getBottom())); } if (imageData.getLeft() != null) { anchor.setDx1(StyleUtil.getCoordinate(imageData.getLeft())); @@ -210,20 +213,24 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { anchor.setCol1(StyleUtil.getCellCoordinate(cell.getColumnIndex(), imageData.getFirstColumnIndex(), imageData.getRelativeFirstColumnIndex())); anchor.setRow2(StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), imageData.getLastRowIndex(), - imageData.getRelativeLastRowIndex())); + imageData.getRelativeLastRowIndex()) + 1); anchor.setCol2(StyleUtil.getCellCoordinate(cell.getColumnIndex(), imageData.getLastColumnIndex(), - imageData.getRelativeLastColumnIndex())); + imageData.getRelativeLastColumnIndex()) + 1); if (imageData.getAnchorType() != null) { anchor.setAnchorType(imageData.getAnchorType().getValue()); } - drawing.createPicture(anchor, index); + Picture picture = drawing.createPicture(anchor, index); + //picture.resize(0.5, 0.5); } } 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 WriteCellData) { + if (clazz == WriteCellData.class) { + if (value == null) { + return new WriteCellData<>(CellDataTypeEnum.EMPTY); + } WriteCellData cellDataValue = (WriteCellData)value; if (cellDataValue.getType() != null) { return cellDataValue; diff --git a/src/main/java/com/alibaba/excel/write/metadata/RowData.java b/src/main/java/com/alibaba/excel/write/metadata/RowData.java index 937395b9..cb86a3e0 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/RowData.java +++ b/src/main/java/com/alibaba/excel/write/metadata/RowData.java @@ -6,9 +6,13 @@ package com.alibaba.excel.write.metadata; * @author Jiaju Zhuang */ public interface RowData { + /** * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. + * + * @param index + * @return data */ Object get(int index); diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageData.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDemoData.java similarity index 78% rename from src/test/java/com/alibaba/easyexcel/test/demo/write/ImageData.java rename to src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDemoData.java index 3fcb9484..ba80d6f1 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageData.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/ImageDemoData.java @@ -8,6 +8,7 @@ import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.converters.string.StringImageConverter; +import com.alibaba.excel.metadata.data.WriteCellData; import lombok.Data; @@ -19,7 +20,7 @@ import lombok.Data; @Data @ContentRowHeight(100) @ColumnWidth(100 / 8) -public class ImageData { +public class ImageDemoData { private File file; private InputStream inputStream; /** @@ -34,4 +35,11 @@ public class ImageData { * @since 2.1.1 */ private URL url; + + /** + * 根据文件导出 并设置导出的位置。 + * + * @since 3.0.0-beta1 + */ + private WriteCellData writeCellDataFile; } diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java index ced2ffde..a0c44853 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java @@ -18,6 +18,10 @@ import com.alibaba.excel.annotation.format.NumberFormat; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.HeadRowHeight; +import com.alibaba.excel.enums.CellDataTypeEnum; +import com.alibaba.excel.metadata.data.ImageData; +import com.alibaba.excel.metadata.data.ImageData.ImageType; +import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.write.merge.LoopMergeStrategy; import com.alibaba.excel.write.metadata.WriteSheet; @@ -194,7 +198,8 @@ public class WriteTest { excelWriter = EasyExcel.write(fileName).build(); // 去调用写入,这里我调用了五次,实际使用时根据数据库分页的总的页数来。这里最终会写到5个sheet里面 for (int i = 0; i < 5; i++) { - // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样。这里注意DemoData.class 可以每次都变,我这里为了方便 所以用的同一个class 实际上可以一直变 + // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样。这里注意DemoData.class 可以每次都变,我这里为了方便 所以用的同一个class + // 实际上可以一直变 WriteSheet writeSheet = EasyExcel.writerSheet(i, "模板" + i).head(DemoData.class).build(); // 分页去数据库查询数据 这里可以去数据库查询每一页的数据 List data = data(); @@ -227,7 +232,7 @@ public class WriteTest { /** * 图片导出 *

    - * 1. 创建excel对应的实体对象 参照{@link ImageData} + * 1. 创建excel对应的实体对象 参照{@link ImageDemoData} *

    * 2. 直接写即可 */ @@ -237,19 +242,49 @@ public class WriteTest { // 如果使用流 记得关闭 InputStream inputStream = null; try { - List list = new ArrayList(); - ImageData imageData = new ImageData(); - list.add(imageData); + List list = new ArrayList<>(); + ImageDemoData imageDemoData = new ImageDemoData(); + list.add(imageDemoData); String imagePath = TestFileUtil.getPath() + "converter" + File.separator + "img.jpg"; // 放入五种类型的图片 实际使用只要选一种即可 - imageData.setByteArray(FileUtils.readFileToByteArray(new File(imagePath))); - imageData.setFile(new File(imagePath)); - imageData.setString(imagePath); + imageDemoData.setByteArray(FileUtils.readFileToByteArray(new File(imagePath))); + imageDemoData.setFile(new File(imagePath)); + imageDemoData.setString(imagePath); inputStream = FileUtils.openInputStream(new File(imagePath)); - imageData.setInputStream(inputStream); - imageData.setUrl(new URL( - "https://raw.githubusercontent.com/alibaba/easyexcel/master/src/test/resources/converter/img.jpg")); - EasyExcel.write(fileName, ImageData.class).sheet().doWrite(list); + imageDemoData.setInputStream(inputStream); + imageDemoData.setUrl(new URL( + "https://raw.githubusercontent.com/alibaba/easyexcel/master/src/test/resources/converter/img.jpg")); + + // 这里演示 图片 不想顶格放 且占用2个单元格的情况 + WriteCellData writeCellData = new WriteCellData<>(); + imageDemoData.setWriteCellDataFile(writeCellData); + // 设置为空 代表当前单元格不需要写图片以外的数据 + writeCellData.setType(CellDataTypeEnum.EMPTY); + // 可以放入多个图片 + List imageDataList = new ArrayList<>(); + ImageData imageData = new ImageData(); + imageDataList.add(imageData); + writeCellData.setImageDataList(imageDataList); + // 放入2进制图片 + imageData.setImage(FileUtils.readFileToByteArray(new File(imagePath))); + // 图片类型 + imageData.setImageType(ImageType.PICTURE_TYPE_PNG); + // 上 右 下 左 需要留空 + // 这里实测 不能设置太大 超过单元格原始大小后 打开会提示修复。暂时未找到很好的解法。 + imageData.setTop(5); + imageData.setRight(5); + imageData.setBottom(5); + imageData.setLeft(5); + // 设置图片的位置 假设 现在目标 是 覆盖 当前单元格 和当前单元格右边的单元格 + // 起点相对于当前单元格为0 当然可以不写 + imageData.setRelativeFirstRowIndex(0); + imageData.setRelativeFirstColumnIndex(0); + imageData.setRelativeLastRowIndex(0); + // 前面3个可以不写 下面这个需要写 也就是 结尾 需要相对当前单元格 往右移动一格 + imageData.setRelativeLastColumnIndex(1); + + // 写入数据 + EasyExcel.write(fileName, ImageDemoData.class).sheet().doWrite(list); } finally { if (inputStream != null) { inputStream.close(); @@ -325,7 +360,7 @@ public class WriteTest { // 背景设置为红色 headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); WriteFont headWriteFont = new WriteFont(); - headWriteFont.setFontHeightInPoints((short) 20); + headWriteFont.setFontHeightInPoints((short)20); headWriteCellStyle.setWriteFont(headWriteFont); // 内容的策略 WriteCellStyle contentWriteCellStyle = new WriteCellStyle(); @@ -335,7 +370,7 @@ public class WriteTest { contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); WriteFont contentWriteFont = new WriteFont(); // 字体大小 - contentWriteFont.setFontHeightInPoints((short) 20); + contentWriteFont.setFontHeightInPoints((short)20); contentWriteCellStyle.setWriteFont(contentWriteFont); // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现 HorizontalCellStyleStrategy horizontalCellStyleStrategy = @@ -428,7 +463,8 @@ public class WriteTest { /** * 自动列宽(不太精确) *

    - * 这个目前不是很好用,比如有数字就会导致换行。而且长度也不是刚好和实际长度一致。 所以需要精确到刚好列宽的慎用。 当然也可以自己参照 {@link LongestMatchColumnWidthStyleStrategy}重新实现. + * 这个目前不是很好用,比如有数字就会导致换行。而且长度也不是刚好和实际长度一致。 所以需要精确到刚好列宽的慎用。 当然也可以自己参照 {@link LongestMatchColumnWidthStyleStrategy} + * 重新实现. *

    * poi 自带{@link SXSSFSheet#autoSizeColumn(int)} 对中文支持也不太好。目前没找到很好的算法。 有的话可以推荐下。 * From bd8fc61149c8769125ab24355f4f9c40f97c0b44 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 7 May 2021 14:39:28 +0800 Subject: [PATCH 068/129] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=85=AC=E5=BC=8F=20?= =?UTF-8?q?=E8=B6=85=E9=93=BE=E6=8E=A5=E7=AD=89=E6=A1=88=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../executor/AbstractExcelWriteExecutor.java | 12 ++-- .../test/demo/write/WriteCellDemoData.java | 41 ++++++++++++ .../easyexcel/test/demo/write/WriteTest.java | 62 +++++++++++++++++++ 3 files changed, 110 insertions(+), 5 deletions(-) create mode 100644 src/test/java/com/alibaba/easyexcel/test/demo/write/WriteCellDemoData.java diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index aa8a2578..93b5539e 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -138,6 +138,7 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { hyperlinkData.getRelativeLastRowIndex())); hyperlink.setLastColumn(StyleUtil.getCellCoordinate(cell.getColumnIndex(), hyperlinkData.getLastColumnIndex(), hyperlinkData.getRelativeLastColumnIndex())); + cell.setHyperlink(hyperlink); } private void fillComment(Cell cell, CommentData commentData) { @@ -155,9 +156,9 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), commentData.getFirstRowIndex(), commentData.getRelativeFirstRowIndex()), StyleUtil.getCellCoordinate(cell.getColumnIndex(), commentData.getLastColumnIndex(), - commentData.getRelativeLastColumnIndex()), + commentData.getRelativeLastColumnIndex()) + 1, StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), commentData.getLastRowIndex(), - commentData.getRelativeLastRowIndex())); + commentData.getRelativeLastRowIndex()) + 1); } else { anchor = new HSSFClientAnchor(StyleUtil.getCoordinate(commentData.getLeft()), StyleUtil.getCoordinate(commentData.getTop()), @@ -167,10 +168,10 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { commentData.getRelativeFirstColumnIndex()), StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), commentData.getFirstRowIndex(), commentData.getRelativeFirstRowIndex()), - (short)StyleUtil.getCellCoordinate(cell.getColumnIndex(), commentData.getLastColumnIndex(), - commentData.getRelativeLastColumnIndex()), + (short)(StyleUtil.getCellCoordinate(cell.getColumnIndex(), commentData.getLastColumnIndex(), + commentData.getRelativeLastColumnIndex()) + 1), StyleUtil.getCellCoordinate(cell.getRow().getRowNum(), commentData.getLastRowIndex(), - commentData.getRelativeLastRowIndex())); + commentData.getRelativeLastRowIndex()) + 1); } Comment comment = cell.getSheet().createDrawingPatriarch().createCellComment(anchor); if (commentData.getRichTextStringData() != null) { @@ -180,6 +181,7 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { if (commentData.getAuthor() != null) { comment.setAuthor(commentData.getAuthor()); } + cell.setCellComment(comment); } protected void fillImage(Cell cell, List imageDataList) { diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteCellDemoData.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteCellDemoData.java new file mode 100644 index 00000000..31eeee41 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteCellDemoData.java @@ -0,0 +1,41 @@ +package com.alibaba.easyexcel.test.demo.write; + +import com.alibaba.excel.metadata.data.WriteCellData; + +import lombok.Data; + +/** + * 根据WriteCellData写 + * + * @author Jiaju Zhuang + */ +@Data +public class WriteCellDemoData { + /** + * 超链接 + * + * @since 3.0.0-beta1 + */ + private WriteCellData hyperlink; + + /** + * 备注 + * + * @since 3.0.0-beta1 + */ + private WriteCellData commentData; + + /** + * 公式 + * + * @since 3.0.0-beta1 + */ + private WriteCellData formulaData; + + /** + * 指定单元格的样式。当然样式 也可以用注解等方式。 + * + * @since 3.0.0-beta1 + */ + private WriteCellData writeCellStyle; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java index a0c44853..00d1b059 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java @@ -19,8 +19,13 @@ import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.HeadRowHeight; import com.alibaba.excel.enums.CellDataTypeEnum; +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.HyperlinkData.HyperlinkType; import com.alibaba.excel.metadata.data.ImageData; import com.alibaba.excel.metadata.data.ImageData.ImageType; +import com.alibaba.excel.metadata.data.RichTextStringData; import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.write.merge.LoopMergeStrategy; @@ -292,6 +297,63 @@ public class WriteTest { } } + /** + * 超链接、备注、公式、指定单个单元格的样式 + *

    + * 1. 创建excel对应的实体对象 参照{@link WriteCellDemoData} + *

    + * 2. 直接写即可 + */ + @Test + public void writeCellDataWrite() throws Exception { + String fileName = TestFileUtil.getPath() + "writeCellDataWrite" + System.currentTimeMillis() + ".xlsx"; + WriteCellDemoData writeCellDemoData = new WriteCellDemoData(); + + // 设置超链接 + WriteCellData hyperlink = new WriteCellData<>("官方网站"); + writeCellDemoData.setHyperlink(hyperlink); + HyperlinkData hyperlinkData = new HyperlinkData(); + hyperlink.setHyperlinkData(hyperlinkData); + hyperlinkData.setAddress("https://github.com/alibaba/easyexcel"); + hyperlinkData.setHyperlinkType(HyperlinkType.URL); + + // 设置备注 + WriteCellData comment = new WriteCellData<>("备注的单元格信息"); + writeCellDemoData.setCommentData(comment); + CommentData commentData = new CommentData(); + comment.setCommentData(commentData); + commentData.setAuthor("Jiaju Zhuang"); + commentData.setRichTextStringData(new RichTextStringData("这是一个备注")); + // 备注的默认大小是按照单元格的大小 这里想调整到4个单元格那么大 所以向后 向下 各额外占用了一个单元格 + commentData.setRelativeLastColumnIndex(1); + commentData.setRelativeLastRowIndex(1); + + + // 设置公式 + WriteCellData formula = new WriteCellData<>(); + writeCellDemoData.setFormulaData(formula); + FormulaData formulaData = new FormulaData(); + formula.setFormulaData(formulaData); + // 将 123456789 中的第一个数字替换成 2 + // 这里只是例子 如果真的涉及到公式 能内存算好尽量内存算好 公式能不用尽量不用 + formulaData.setFormulaValue("REPLACE(123456789,1,1,2)"); + + + // 设置单个单元格的样式 当然样式 很多的话 也可以用注解等方式。 + WriteCellData writeCellStyle = new WriteCellData<>("单元格样式"); + writeCellDemoData.setWriteCellStyle(writeCellStyle); + WriteCellStyle writeCellStyleData = new WriteCellStyle(); + writeCellStyle.setWriteCellStyle(writeCellStyleData); + // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色. + writeCellStyleData.setFillPatternType(FillPatternType.SOLID_FOREGROUND); + // 背景绿色 + writeCellStyleData.setFillForegroundColor(IndexedColors.GREEN.getIndex()); + + List data = new ArrayList<>(); + data.add(writeCellDemoData); + EasyExcel.write(fileName, WriteCellDemoData.class).inMemory(true).sheet("模板").doWrite(data); + } + /** * 根据模板写入 *

    From 9ee2b63538d14445fac575b7e796b392fa57379b Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 7 May 2021 16:02:12 +0800 Subject: [PATCH 069/129] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/write/executor/AbstractExcelWriteExecutor.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index 93b5539e..9f32153e 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -32,7 +32,6 @@ 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.Picture; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFClientAnchor; @@ -62,8 +61,6 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { // Fill in picture information fillImage(cell, cellData.getImageDataList()); - //setImageValue(cellData,cell); - // Fill in comment information fillComment(cell, cellData.getCommentData()); @@ -221,8 +218,7 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { if (imageData.getAnchorType() != null) { anchor.setAnchorType(imageData.getAnchorType().getValue()); } - Picture picture = drawing.createPicture(anchor, index); - //picture.resize(0.5, 0.5); + drawing.createPicture(anchor, index); } } From fee773f04b3180621530494fad8590babf2040e7 Mon Sep 17 00:00:00 2001 From: zjr2000 <71474767+zjr2000@users.noreply.github.com> Date: Sun, 9 May 2021 17:09:25 +0800 Subject: [PATCH 070/129] =?UTF-8?q?fix=20#1651=EF=BC=9A=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E5=A1=AB=E5=85=85=E5=AF=BC=E5=87=BA=E7=9A=84?= =?UTF-8?q?=E6=97=B6=E5=80=99=E8=AE=BE=E7=BD=AE=E8=87=AA=E5=8A=A8=E6=8D=A2?= =?UTF-8?q?=E8=A1=8C=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/excel/write/style/HorizontalCellStyleStrategy.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java index 295cd556..504570fa 100644 --- a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java @@ -60,9 +60,10 @@ public class HorizontalCellStyleStrategy extends AbstractCellStyleStrategy { @Override protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) { - if (contentCellStyleList == null || contentCellStyleList.isEmpty()) { + if (contentCellStyleList == null || contentCellStyleList.isEmpty() || relativeRowIndex == null) { return; } + cell.setCellStyle(contentCellStyleList.get(relativeRowIndex % contentCellStyleList.size())); } From e2e2971bfb519e50e64a7227b8c28bdef16974e0 Mon Sep 17 00:00:00 2001 From: lethal233 <11811407@mail.sustech.edu.cn> Date: Wed, 19 May 2021 22:18:37 +0800 Subject: [PATCH 071/129] bugfix-1662 --- .../property/ExcelWriteHeadProperty.java | 4 +- .../test/temp/issue1662/Data1662.java | 20 +++++++++ .../test/temp/issue1662/Issue1662Test.java | 42 +++++++++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Data1662.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Issue1662Test.java diff --git a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java index 979a7750..2ba4ff9d 100644 --- a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java +++ b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java @@ -158,7 +158,9 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty { int lastCol = i; int lastRow = j; for (int k = i + 1; k < headList.size(); k++) { - if (headList.get(k).getHeadNameList().get(j).equals(headName)) { + if (headList.get(k).getHeadNameList().get(j).equals(headName) + && (j - 1 >= 0) + && !headList.get(k).getHeadNameList().get(j-1).equals(headName)) { alreadyRangeSet.add(k + "-" + j); lastCol = k; } else { diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Data1662.java b/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Data1662.java new file mode 100644 index 00000000..53a1a5c8 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Data1662.java @@ -0,0 +1,20 @@ +package com.alibaba.easyexcel.test.temp.issue1662; + +import com.alibaba.excel.annotation.ExcelProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class Data1662 { + @ExcelProperty(index = 0) + private String str; + @ExcelProperty(index = 1) + private Date date; + @ExcelProperty(index = 2) + private double r; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Issue1662Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Issue1662Test.java new file mode 100644 index 00000000..5d311c45 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Issue1662Test.java @@ -0,0 +1,42 @@ +package com.alibaba.easyexcel.test.temp.issue1662; + +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; +import org.junit.Test; + + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +public class Issue1662Test { + @Test + public void test1662() { + String fileName = TestFileUtil.getPath() + "Test1939" + ".xlsx"; + System.out.println(fileName); + EasyExcel.write(fileName).head(head()).sheet("模板").doWrite(dataList()); + } + + + private List> head() { + List> list = new ArrayList<>(); + List head0 = new ArrayList<>(); + List head1 = new ArrayList<>(); + head0.add("xx"); + head0.add("日期"); + list.add(head0); + head1.add("日期"); + list.add(head1); + return list; + } + + private List> dataList() { + List> list = new ArrayList<>(); + List data = new ArrayList<>(); + data.add("字符串"); + data.add(new Date()); + data.add(0.56); + list.add(data); + return list; + } +} From e1bc4743f3b125718ebdf612355edc718d29e653 Mon Sep 17 00:00:00 2001 From: lethal233 <11811407@mail.sustech.edu.cn> Date: Thu, 20 May 2021 12:19:34 +0800 Subject: [PATCH 072/129] modify if-statement to satisfy pmd check --- .../alibaba/excel/write/property/ExcelWriteHeadProperty.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java index 2ba4ff9d..8e3cb45c 100644 --- a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java +++ b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java @@ -158,9 +158,8 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty { int lastCol = i; int lastRow = j; for (int k = i + 1; k < headList.size(); k++) { - if (headList.get(k).getHeadNameList().get(j).equals(headName) - && (j - 1 >= 0) - && !headList.get(k).getHeadNameList().get(j-1).equals(headName)) { + boolean flag = (j - 1 >= 0) && !headList.get(k).getHeadNameList().get(j - 1).equals(headName); + if (headList.get(k).getHeadNameList().get(j).equals(headName) && flag) { alreadyRangeSet.add(k + "-" + j); lastCol = k; } else { From 8b11873c8b5b58df5aa4d4624e7cb0a3be8ba6cd Mon Sep 17 00:00:00 2001 From: lethal233 <11811407@mail.sustech.edu.cn> Date: Thu, 20 May 2021 12:27:07 +0800 Subject: [PATCH 073/129] modify diamond compatibility using source 1.6 --- .../easyexcel/test/temp/issue1662/Issue1662Test.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Issue1662Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Issue1662Test.java index 5d311c45..8fa5a842 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Issue1662Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Issue1662Test.java @@ -19,9 +19,9 @@ public class Issue1662Test { private List> head() { - List> list = new ArrayList<>(); - List head0 = new ArrayList<>(); - List head1 = new ArrayList<>(); + List> list = new ArrayList>(); + List head0 = new ArrayList(); + List head1 = new ArrayList(); head0.add("xx"); head0.add("日期"); list.add(head0); @@ -31,8 +31,8 @@ public class Issue1662Test { } private List> dataList() { - List> list = new ArrayList<>(); - List data = new ArrayList<>(); + List> list = new ArrayList>(); + List data = new ArrayList(); data.add("字符串"); data.add(new Date()); data.add(0.56); From 405e79366db1ff629e5213c729b9540a1e5757d1 Mon Sep 17 00:00:00 2001 From: SometimesNaive Date: Thu, 3 Jun 2021 17:08:34 +0800 Subject: [PATCH 074/129] fix issue 1967 --- .../alibaba/excel/write/executor/ExcelWriteFillExecutor.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 5930a311..cab79750 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import com.alibaba.excel.exception.ExcelCommonException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; @@ -368,6 +369,9 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { return analysisCellList; } Sheet sheet = writeContext.writeSheetHolder().getCachedSheet(); + if (sheet.getLastRowNum() == 0) { + throw new ExcelCommonException(sheet.getSheetName() + " not exists in the excel to be written"); + } Map> firstRowCache = new HashMap>(8); for (int i = 0; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); From c7dc8fd08e1f34da20f28cbfcdf19fd4245ca438 Mon Sep 17 00:00:00 2001 From: Samuel Date: Tue, 8 Jun 2021 14:47:02 +0800 Subject: [PATCH 075/129] fix grammar errors --- .../analysis/v07/handlers/CellTagHandler.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java index fe5a6421..1588f1ae 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java @@ -27,13 +27,13 @@ public class CellTagHandler extends AbstractXlsxTagHandler { xlsxReadSheetHolder.setColumnIndex(PositionUtils.getCol(attributes.getValue(ExcelXmlConstants.ATTRIBUTE_R), xlsxReadSheetHolder.getColumnIndex())); - // t="s" ,it's means String - // t="str" ,it's means String,but does not need to be read in the 'sharedStrings.xml' - // t="inlineStr" ,it's means String - // t="b" ,it's means Boolean - // t="e" ,it's means Error - // t="n" ,it's means Number - // t is null ,it's means Empty or Number + // t="s" ,it means String + // t="str" ,it means String,but does not need to be read in the 'sharedStrings.xml' + // t="inlineStr" ,it means String + // t="b" ,it means Boolean + // t="e" ,it means Error + // t="n" ,it means Number + // t is null ,it means Empty or Number CellDataTypeEnum type = CellDataTypeEnum.buildFromCellType(attributes.getValue(ExcelXmlConstants.ATTRIBUTE_T)); xlsxReadSheetHolder.setTempCellData(new CellData(type)); xlsxReadSheetHolder.setTempData(new StringBuilder()); From ac79beaf6fbcbdd02906d1bbf93ea53984cc17ea Mon Sep 17 00:00:00 2001 From: lethal233 <11811407@mail.sustech.edu.cn> Date: Wed, 9 Jun 2021 20:48:24 +0800 Subject: [PATCH 076/129] fix comment typo like #1971 --- .../analysis/v07/handlers/CellTagHandler.java | 14 +++++++------- .../alibaba/excel/annotation/ExcelProperty.java | 2 +- .../annotation/write/style/ContentFontStyle.java | 2 +- .../annotation/write/style/HeadFontStyle.java | 2 +- .../java/com/alibaba/excel/metadata/CellExtra.java | 8 ++++---- .../excel/metadata/property/FontProperty.java | 2 +- .../excel/read/builder/ExcelReaderBuilder.java | 8 ++++---- .../alibaba/excel/read/metadata/ReadWorkbook.java | 6 +++--- .../read/metadata/holder/ReadWorkbookHolder.java | 6 +++--- .../excel/write/builder/ExcelWriterBuilder.java | 2 +- .../write/executor/AbstractExcelWriteExecutor.java | 4 ++-- .../write/executor/ExcelWriteAddExecutor.java | 2 +- .../excel/write/metadata/WriteWorkbook.java | 10 +++++----- .../write/metadata/holder/WriteSheetHolder.java | 4 ++-- .../write/metadata/holder/WriteWorkbookHolder.java | 8 ++++---- .../excel/write/metadata/style/WriteFont.java | 2 +- .../AbstractHeadColumnWidthStyleStrategy.java | 2 +- .../core/compatibility/CompatibilityDataTest.java | 4 ++-- 18 files changed, 44 insertions(+), 44 deletions(-) diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java index fe5a6421..2224c19f 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java @@ -27,13 +27,13 @@ public class CellTagHandler extends AbstractXlsxTagHandler { xlsxReadSheetHolder.setColumnIndex(PositionUtils.getCol(attributes.getValue(ExcelXmlConstants.ATTRIBUTE_R), xlsxReadSheetHolder.getColumnIndex())); - // t="s" ,it's means String - // t="str" ,it's means String,but does not need to be read in the 'sharedStrings.xml' - // t="inlineStr" ,it's means String - // t="b" ,it's means Boolean - // t="e" ,it's means Error - // t="n" ,it's means Number - // t is null ,it's means Empty or Number + // t="s", it means String + // t="str", it means String, but does not need to be read in the 'sharedStrings.xml' + // t="inlineStr", it means String + // t="b", it means Boolean + // t="e", it means Error + // t="n", it means Number + // t is null, it means Empty or Number CellDataTypeEnum type = CellDataTypeEnum.buildFromCellType(attributes.getValue(ExcelXmlConstants.ATTRIBUTE_T)); xlsxReadSheetHolder.setTempCellData(new CellData(type)); xlsxReadSheetHolder.setTempData(new StringBuilder()); diff --git a/src/main/java/com/alibaba/excel/annotation/ExcelProperty.java b/src/main/java/com/alibaba/excel/annotation/ExcelProperty.java index 5c778a84..28e1ccd3 100644 --- a/src/main/java/com/alibaba/excel/annotation/ExcelProperty.java +++ b/src/main/java/com/alibaba/excel/annotation/ExcelProperty.java @@ -32,7 +32,7 @@ public @interface ExcelProperty { /** * Index of column * - * Read or write it on the index of column,If it's equal to -1, it's sorted by Java class. + * Read or write it on the index of column, If it's equal to -1, it's sorted by Java class. * * priority: index > order > default sort * diff --git a/src/main/java/com/alibaba/excel/annotation/write/style/ContentFontStyle.java b/src/main/java/com/alibaba/excel/annotation/write/style/ContentFontStyle.java index d593aef3..533ae6aa 100644 --- a/src/main/java/com/alibaba/excel/annotation/write/style/ContentFontStyle.java +++ b/src/main/java/com/alibaba/excel/annotation/write/style/ContentFontStyle.java @@ -52,7 +52,7 @@ public @interface ContentFontStyle { short color() default -1; /** - * Set normal,super or subscript. + * Set normal, super or subscript. * * @see Font#SS_NONE * @see Font#SS_SUPER diff --git a/src/main/java/com/alibaba/excel/annotation/write/style/HeadFontStyle.java b/src/main/java/com/alibaba/excel/annotation/write/style/HeadFontStyle.java index 957e50f5..d25dad77 100644 --- a/src/main/java/com/alibaba/excel/annotation/write/style/HeadFontStyle.java +++ b/src/main/java/com/alibaba/excel/annotation/write/style/HeadFontStyle.java @@ -52,7 +52,7 @@ public @interface HeadFontStyle { short color() default -1; /** - * Set normal,super or subscript. + * Set normal, super or subscript. * * @see Font#SS_NONE * @see Font#SS_SUPER diff --git a/src/main/java/com/alibaba/excel/metadata/CellExtra.java b/src/main/java/com/alibaba/excel/metadata/CellExtra.java index 937b9ac7..778f95fc 100644 --- a/src/main/java/com/alibaba/excel/metadata/CellExtra.java +++ b/src/main/java/com/alibaba/excel/metadata/CellExtra.java @@ -20,19 +20,19 @@ public class CellExtra extends AbstractCell { */ private String text; /** - * First row index,if this object is an interval + * First row index, if this object is an interval */ private Integer firstRowIndex; /** - * Last row index,if this object is an interval + * Last row index, if this object is an interval */ private Integer lastRowIndex; /** - * First column index,if this object is an interval + * First column index, if this object is an interval */ private Integer firstColumnIndex; /** - * Last column index,if this object is an interval + * Last column index, if this object is an interval */ private Integer lastColumnIndex; diff --git a/src/main/java/com/alibaba/excel/metadata/property/FontProperty.java b/src/main/java/com/alibaba/excel/metadata/property/FontProperty.java index 04caf9bb..06aec863 100644 --- a/src/main/java/com/alibaba/excel/metadata/property/FontProperty.java +++ b/src/main/java/com/alibaba/excel/metadata/property/FontProperty.java @@ -40,7 +40,7 @@ public class FontProperty { */ private Short color; /** - * Set normal,super or subscript. + * Set normal, super or subscript. * * @see Font#SS_NONE * @see Font#SS_SUPER diff --git a/src/main/java/com/alibaba/excel/read/builder/ExcelReaderBuilder.java b/src/main/java/com/alibaba/excel/read/builder/ExcelReaderBuilder.java index 81f35862..b630eea2 100644 --- a/src/main/java/com/alibaba/excel/read/builder/ExcelReaderBuilder.java +++ b/src/main/java/com/alibaba/excel/read/builder/ExcelReaderBuilder.java @@ -41,7 +41,7 @@ public class ExcelReaderBuilder extends AbstractExcelReaderParameterBuilder - * If 'inputStream' and 'file' all not empty,file first + * If 'inputStream' and 'file' all not empty, file first */ public ExcelReaderBuilder file(InputStream inputStream) { readWorkbook.setInputStream(inputStream); @@ -51,7 +51,7 @@ public class ExcelReaderBuilder extends AbstractExcelReaderParameterBuilder - * If 'inputStream' and 'file' all not empty,file first + * If 'inputStream' and 'file' all not empty, file first */ public ExcelReaderBuilder file(File file) { readWorkbook.setFile(file); @@ -61,7 +61,7 @@ public class ExcelReaderBuilder extends AbstractExcelReaderParameterBuilder - * If 'inputStream' and 'file' all not empty,file first + * If 'inputStream' and 'file' all not empty, file first */ public ExcelReaderBuilder file(String pathName) { return file(new File(pathName)); @@ -70,7 +70,7 @@ public class ExcelReaderBuilder extends AbstractExcelReaderParameterBuilder - * if false,Will transfer 'inputStream' to temporary files to improve efficiency + * if false, Will transfer 'inputStream' to temporary files to improve efficiency */ public ExcelReaderBuilder mandatoryUseInputStream(Boolean mandatoryUseInputStream) { readWorkbook.setMandatoryUseInputStream(mandatoryUseInputStream); diff --git a/src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java b/src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java index c9e4db93..1ef7032f 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java +++ b/src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java @@ -27,19 +27,19 @@ public class ReadWorkbook extends ReadBasicParameter { /** * Read InputStream *

    - * If 'inputStream' and 'file' all not empty,file first + * If 'inputStream' and 'file' all not empty, file first */ private InputStream inputStream; /** * Read file *

    - * If 'inputStream' and 'file' all not empty,file first + * If 'inputStream' and 'file' all not empty, file first */ private File file; /** * Mandatory use 'inputStream' .Default is false. *

    - * if false,Will transfer 'inputStream' to temporary files to improve efficiency + * if false, Will transfer 'inputStream' to temporary files to improve efficiency */ private Boolean mandatoryUseInputStream; /** diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java index 375e32cc..c6462d94 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java @@ -33,19 +33,19 @@ public class ReadWorkbookHolder extends AbstractReadHolder { /** * Read InputStream *

    - * If 'inputStream' and 'file' all not empty,file first + * If 'inputStream' and 'file' all not empty, file first */ private InputStream inputStream; /** * Read file *

    - * If 'inputStream' and 'file' all not empty,file first + * If 'inputStream' and 'file' all not empty, file first */ private File file; /** * Mandatory use 'inputStream' .Default is false. *

    - * if false,Will transfer 'inputStream' to temporary files to improve efficiency + * if false, Will transfer 'inputStream' to temporary files to improve efficiency */ private Boolean mandatoryUseInputStream; /** diff --git a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java index 12c2f22f..3fb03236 100644 --- a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java +++ b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java @@ -49,7 +49,7 @@ public class ExcelWriterBuilder extends AbstractExcelWriterParameterBuilder * Comment and RichTextString are only supported in memory mode. */ diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index 4eb115c5..38f6558b 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -117,12 +117,12 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { } catch (Exception e) { throw new ExcelDataConvertException(cell.getRow().getRowNum(), cell.getColumnIndex(), new CellData(CellDataTypeEnum.EMPTY), excelContentProperty, - "Convert data:" + value + " error,at row:" + cell.getRow().getRowNum(), e); + "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, - "Convert data:" + value + " return null,at row:" + cell.getRow().getRowNum()); + "Convert data:" + value + " return null, at row:" + cell.getRow().getRowNum()); } return cellData; } diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 9f229029..981293d3 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -48,7 +48,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { if (writeSheetHolder.isNew() && !writeSheetHolder.getExcelWriteHeadProperty().hasHead()) { newRowIndex += writeContext.currentWriteHolder().relativeHeadRowIndex(); } - // BeanMap is out of order,so use sortedAllFiledMap + // BeanMap is out of order, so use sortedAllFiledMap Map sortedAllFiledMap = new TreeMap(); int relativeRowIndex = 0; for (Object oneRowData : data) { diff --git a/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java b/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java index c28e0412..d5850405 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java +++ b/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java @@ -20,26 +20,26 @@ public class WriteWorkbook extends WriteBasicParameter { /** * Final output file *

    - * If 'outputStream' and 'file' all not empty,file first + * If 'outputStream' and 'file' all not empty, file first */ private File file; /** * Final output stream *

    - * If 'outputStream' and 'file' all not empty,file first + * If 'outputStream' and 'file' all not empty, file first */ private OutputStream outputStream; /** * Template input stream *

    - * If 'inputStream' and 'file' all not empty,file first + * If 'inputStream' and 'file' all not empty, file first */ private InputStream templateInputStream; /** * Template file *

    - * If 'inputStream' and 'file' all not empty,file first + * If 'inputStream' and 'file' all not empty, file first */ private File templateFile; /** @@ -58,7 +58,7 @@ public class WriteWorkbook extends WriteBasicParameter { */ private String password; /** - * Write excel in memory. Default false,the cache file is created and finally written to excel. + * Write excel in memory. Default false, the cache file is created and finally written to excel. *

    * Comment and RichTextString are only supported in memory mode. */ diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java index 56fc7e4e..15b88292 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java @@ -148,12 +148,12 @@ public class WriteSheetHolder extends AbstractWriteHolder { } /** - * Get the last line of index,you have to make sure that the data is written next + * Get the last line of index, you have to make sure that the data is written next * * @return */ public int getNewRowIndexAndStartDoWrite() { - // 'getLastRowNum' doesn't matter if it has one or zero,is's zero + // 'getLastRowNum' doesn't matter if it has one or zero, it's zero int newRowIndex = 0; switch (writeLastRowTypeEnum) { case TEMPLATE_EMPTY: diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java index 8c84f1dc..999e7f10 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java @@ -52,7 +52,7 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { /** * Final output file *

    - * If 'outputStream' and 'file' all not empty,file first + * If 'outputStream' and 'file' all not empty, file first */ private File file; /** @@ -62,13 +62,13 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { /** * Template input stream *

    - * If 'inputStream' and 'file' all not empty,file first + * If 'inputStream' and 'file' all not empty, file first */ private InputStream templateInputStream; /** * Template file *

    - * If 'inputStream' and 'file' all not empty,file first + * If 'inputStream' and 'file' all not empty, file first */ private File templateFile; /** @@ -102,7 +102,7 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { */ private String password; /** - * Write excel in memory. Default false,the cache file is created and finally written to excel. + * Write excel in memory. Default false, the cache file is created and finally written to excel. *

    * Comment and RichTextString are only supported in memory mode. */ diff --git a/src/main/java/com/alibaba/excel/write/metadata/style/WriteFont.java b/src/main/java/com/alibaba/excel/write/metadata/style/WriteFont.java index 6ed4c2a7..35fe7b92 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/style/WriteFont.java +++ b/src/main/java/com/alibaba/excel/write/metadata/style/WriteFont.java @@ -37,7 +37,7 @@ public class WriteFont { */ private Short color; /** - * Set normal,super or subscript. + * Set normal, super or subscript. * * @see Font#SS_NONE * @see Font#SS_SUPER diff --git a/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java index 1a88eff6..14a76c71 100644 --- a/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java @@ -33,7 +33,7 @@ public abstract class AbstractHeadColumnWidthStyleStrategy extends AbstractColum * Returns the column width corresponding to each column head. * *

    - * if return null,ignore + * if return null, ignore * * @param head * Nullable. diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java index 258f055c..39ceff92 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java @@ -58,7 +58,7 @@ public class CompatibilityDataTest { generateParam.setOutputStream(out); generateParam.setClazz(null); ExcelWriter writer = new ExcelWriter(generateParam); - // sheet1 width,string head,string data + // sheet1 width, string head, string data Sheet sheet1 = new Sheet(1, 3); sheet1.setSheetName("第一个sheet"); Map columnWidth = new HashMap(); @@ -68,7 +68,7 @@ public class CompatibilityDataTest { sheet1.setHead(head()); writer.write1(listData(), sheet1); - // sheet2 style,class head + // sheet2 style, class head Sheet sheet2 = new Sheet(2, 3, CompatibilityData.class, "第二个sheet", null); sheet2.setStartRow(5); sheet2.setTableStyle(style()); From c2b8d2333c28ccb68631d7b29a7f94cfd31dbd02 Mon Sep 17 00:00:00 2001 From: Hccake Date: Fri, 11 Jun 2021 00:47:44 +0800 Subject: [PATCH 077/129] =?UTF-8?q?:bug:=20fix=20=E5=BD=93=E8=BF=9B?= =?UTF-8?q?=E8=A1=8C=E5=8A=A0=E5=AF=86=E5=AF=BC=E5=87=BA=E6=97=B6=EF=BC=8C?= =?UTF-8?q?=E7=94=B1=E4=BA=8E=E8=BE=93=E5=87=BA=E6=B5=81=E6=9C=AA=E5=85=B3?= =?UTF-8?q?=E9=97=AD=E5=AF=BC=E8=87=B4=E7=9A=84=E6=96=87=E4=BB=B6=E6=8D=9F?= =?UTF-8?q?=E5=9D=8F=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/excel/context/WriteContextImpl.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java index c1f89f02..5b4efb18 100644 --- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java @@ -488,14 +488,18 @@ public class WriteContextImpl implements WriteContext { Encryptor encryptor = new EncryptionInfo(EncryptionMode.standard).getEncryptor(); encryptor.confirmPassword(writeWorkbookHolder.getPassword()); OPCPackage opcPackage = null; + OutputStream outputStream = null; try { opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE); - OutputStream outputStream = encryptor.getDataStream(fileSystem); + outputStream = encryptor.getDataStream(fileSystem); opcPackage.save(outputStream); } finally { if (opcPackage != null) { opcPackage.close(); } + if (outputStream != null) { + outputStream.close(); + } } return fileSystem; } From ad14f28d277538fb42dacc8d420b3a93caf0f9e6 Mon Sep 17 00:00:00 2001 From: Hccake Date: Fri, 11 Jun 2021 01:21:17 +0800 Subject: [PATCH 078/129] =?UTF-8?q?:arrow=5Fup:=20=E5=8D=87=E7=BA=A7=20poi?= =?UTF-8?q?=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/pom.xml b/pom.xml index 9f1a4c72..251651e9 100644 --- a/pom.xml +++ b/pom.xml @@ -57,20 +57,10 @@ - - org.apache.poi - poi - 3.17 - org.apache.poi poi-ooxml - 3.17 - - - org.apache.poi - poi-ooxml-schemas - 3.17 + 4.1.2 cglib From 9faaef64c88d57f9505db591ea1e31d84d7d0660 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Thu, 24 Jun 2021 11:47:41 +0800 Subject: [PATCH 079/129] Update README.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增5群 --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c0401aea..672fbc15 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,8 @@ EasyExcel [钉钉1群(已满): 21960511](https://qr.dingtalk.com/action/joingroup?code=v1,k1,cchz6k12ci9B08NNqhNRFGXocNVHrZtW0kaOtTKg/Rk=&_dt_no_comment=1&origin=11) [钉钉2群(已满): 32796397](https://qr.dingtalk.com/action/joingroup?code=v1,k1,jyU9GtEuNU5S0QTyklqYcYJ8qDZtUuTPMM7uPZTS8Hs=&_dt_no_comment=1&origin=11) [钉钉3群(已满): 33797247](https://qr.dingtalk.com/action/joingroup?code=v1,k1,3UGlEScTGQaHpW2cIRo+gkxJ9EVZ5fz26M6nW3uFP30=&_dt_no_comment=1&origin=11) -[钉钉4群: 33491624](https://qr.dingtalk.com/action/joingroup?code=v1,k1,V14Pb65Too70rQkEaJ9ohb6lZBZbtp6jIL/q9EWh9vA=&_dt_no_comment=1&origin=11) +[钉钉4群(已满): 33491624](https://qr.dingtalk.com/action/joingroup?code=v1,k1,V14Pb65Too70rQkEaJ9ohb6lZBZbtp6jIL/q9EWh9vA=&_dt_no_comment=1&origin=11) +[钉钉5群: 32134498](https://h5.dingtalk.com/circle/healthCheckin.html?dtaction=os&corpId=dingb9fa1325d9dccc3ecac589edd02f1650&5233a=71a83&cbdbhh=qwertyuiop) [官方网站: https://yuque.com/easyexcel](https://www.yuque.com/easyexcel/doc/easyexcel) [常见问题](https://www.yuque.com/easyexcel/faq) From 62855db969a6347c2411b103adf6291317345c57 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Thu, 24 Jun 2021 11:48:02 +0800 Subject: [PATCH 080/129] Update README.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增5群 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 672fbc15..a108ff3c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ EasyExcel [钉钉1群(已满): 21960511](https://qr.dingtalk.com/action/joingroup?code=v1,k1,cchz6k12ci9B08NNqhNRFGXocNVHrZtW0kaOtTKg/Rk=&_dt_no_comment=1&origin=11) [钉钉2群(已满): 32796397](https://qr.dingtalk.com/action/joingroup?code=v1,k1,jyU9GtEuNU5S0QTyklqYcYJ8qDZtUuTPMM7uPZTS8Hs=&_dt_no_comment=1&origin=11) [钉钉3群(已满): 33797247](https://qr.dingtalk.com/action/joingroup?code=v1,k1,3UGlEScTGQaHpW2cIRo+gkxJ9EVZ5fz26M6nW3uFP30=&_dt_no_comment=1&origin=11) -[钉钉4群(已满): 33491624](https://qr.dingtalk.com/action/joingroup?code=v1,k1,V14Pb65Too70rQkEaJ9ohb6lZBZbtp6jIL/q9EWh9vA=&_dt_no_comment=1&origin=11) +[钉钉4群(已满): 33491624](https://qr.dingtalk.com/action/joingroup?code=v1,k1,V14Pb65Too70rQkEaJ9ohb6lZBZbtp6jIL/q9EWh9vA=&_dt_no_comment=1&origin=11) [钉钉5群: 32134498](https://h5.dingtalk.com/circle/healthCheckin.html?dtaction=os&corpId=dingb9fa1325d9dccc3ecac589edd02f1650&5233a=71a83&cbdbhh=qwertyuiop) [官方网站: https://yuque.com/easyexcel](https://www.yuque.com/easyexcel/doc/easyexcel) From 2b0abe9a5cb9e1ec075876edb2e134194c47dc7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?wbzl771398=E5=BC=A0=E7=A3=8A?= Date: Wed, 30 Jun 2021 15:46:13 +0800 Subject: [PATCH 081/129] =?UTF-8?q?initSheet=E8=BE=93=E5=87=BA=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/alibaba/excel/context/WriteContextImpl.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java index c1f89f02..5af30cec 100644 --- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java @@ -179,6 +179,7 @@ public class WriteContextImpl implements WriteContext { .setCachedSheet(writeWorkbookHolder.getCachedWorkbook().getSheet(writeSheetHolder.getSheetName())); } } catch (Exception e) { + LOGGER.error("initSheet exception ",e); currentSheet = createSheet(); } if (currentSheet == null) { From c5b90d31c37eb80e0177884f5590ce64189dcb0e Mon Sep 17 00:00:00 2001 From: glxm <2633680461@qq.com> Date: Sun, 25 Jul 2021 15:07:21 +0800 Subject: [PATCH 082/129] =?UTF-8?q?=E5=8D=87=E7=BA=A7poi=E5=88=B05.0.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 8 ++++---- .../alibaba/excel/analysis/v07/XlsxSaxAnalyser.java | 11 +++++++---- .../excel/write/executor/ExcelWriteFillExecutor.java | 2 +- .../com/alibaba/easyexcel/test/temp/Lock2Test.java | 2 +- .../com/alibaba/easyexcel/test/temp/WriteV33Test.java | 9 --------- .../test/temp/dataformat/DataFormatter1.java | 4 ++-- 6 files changed, 15 insertions(+), 21 deletions(-) diff --git a/pom.xml b/pom.xml index 9f1a4c72..f6025685 100644 --- a/pom.xml +++ b/pom.xml @@ -60,17 +60,17 @@ org.apache.poi poi - 3.17 + 5.0.0 org.apache.poi poi-ooxml - 3.17 + 5.0.0 org.apache.poi - poi-ooxml-schemas - 3.17 + poi-ooxml-full + 5.0.0 cglib diff --git a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java index a0a9af0e..4e9da159 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java @@ -5,6 +5,7 @@ import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; @@ -215,10 +216,12 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor { if (commentsTable == null) { return; } - Map cellComments = commentsTable.getCellComments(); - for (XSSFComment xssfComment : cellComments.values()) { - CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.COMMENT, xssfComment.getString().toString(), - xssfComment.getRow(), xssfComment.getColumn()); + Iterator cellAddresses = commentsTable.getCellAddresses(); + for (Iterator it = cellAddresses; it.hasNext(); ) { + CellAddress cellAddress = it.next(); + XSSFComment cellComment = commentsTable.findCellComment(cellAddress); + CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.COMMENT, cellComment.getString().toString(), + cellAddress.getRow(), cellAddress.getColumn()); xlsxReadContext.readSheetHolder().setCellExtra(cellExtra); xlsxReadContext.analysisEventProcessor().extra(xlsxReadContext); } diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 5930a311..4989c311 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -399,7 +399,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { * @return Returns the data that the cell needs to replace */ private String prepareData(Cell cell, int rowIndex, int columnIndex, Map> firstRowCache) { - if (!CellType.STRING.equals(cell.getCellTypeEnum())) { + if (!CellType.STRING.equals(cell.getCellType())) { return null; } String value = cell.getStringCellValue(); diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java index 92202642..9ced586d 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java @@ -5,9 +5,9 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import org.apache.poi.hssf.util.CellReference; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.ss.util.CellReference; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/WriteV33Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/WriteV33Test.java index f8db7f9c..ea7b39a2 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/WriteV33Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/WriteV33Test.java @@ -1,13 +1,8 @@ package com.alibaba.easyexcel.test.temp; -import java.io.File; import java.util.ArrayList; -import java.util.Date; import java.util.List; -import org.apache.poi.hssf.util.CellReference; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.IndexedColors; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; @@ -19,10 +14,6 @@ import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy; import com.alibaba.excel.write.metadata.WriteSheet; -import com.alibaba.excel.write.metadata.style.WriteCellStyle; -import com.alibaba.excel.write.metadata.style.WriteFont; -import com.alibaba.excel.write.style.HorizontalCellStyleStrategy; -import com.alibaba.fastjson.JSON; /** * 临时测试 diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatter1.java b/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatter1.java index 0239ed5b..c4dce8d3 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatter1.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatter1.java @@ -968,12 +968,12 @@ public class DataFormatter1 implements Observer { return ""; } - CellType cellType = cell.getCellTypeEnum(); + CellType cellType = cell.getCellType(); if (cellType == CellType.FORMULA) { if (evaluator == null) { return cell.getCellFormula(); } - cellType = evaluator.evaluateFormulaCellEnum(cell); + cellType = evaluator.evaluateFormulaCell(cell); } switch (cellType) { case NUMERIC: From ef4184d52023d1feb208cfd54b783dc042d4a7c9 Mon Sep 17 00:00:00 2001 From: yizhi Date: Tue, 27 Jul 2021 20:12:00 +0800 Subject: [PATCH 083/129] fix issue-2014 --- .../excel/read/listener/ModelBuildEventListener.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java index 78b57e0a..8ac2ea22 100644 --- a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java +++ b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java @@ -26,9 +26,12 @@ import net.sf.cglib.beans.BeanMap; * @author jipengfei */ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener> { + private int headSize; @Override - public void invokeHead(Map cellDataMap, AnalysisContext context) {} + public void invokeHead(Map cellDataMap, AnalysisContext context) { + this.headSize = cellDataMap.size(); + } @Override public void invoke(Map cellDataMap, AnalysisContext context) { @@ -62,7 +65,8 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener (String)ConverterUtils.convertToJavaObject(cellData, null, null, currentReadHolder.converterMap(), currentReadHolder.globalConfiguration(), context.readRowHolder().getRowIndex(), key)); } - int headSize = currentReadHolder.excelReadHeadProperty().getHeadMap().size(); + int headSize = currentReadHolder.excelReadHeadProperty().getHeadMap().size() == 0 + ? this.headSize : currentReadHolder.excelReadHeadProperty().getHeadMap().size(); while (index < headSize) { map.put(index, null); index++; @@ -87,7 +91,8 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener (String)ConverterUtils.convertToJavaObject(cellData, null, null, currentReadHolder.converterMap(), currentReadHolder.globalConfiguration(), context.readRowHolder().getRowIndex(), key)); } - int headSize = currentReadHolder.excelReadHeadProperty().getHeadMap().size(); + int headSize = currentReadHolder.excelReadHeadProperty().getHeadMap().size() == 0 + ? this.headSize : currentReadHolder.excelReadHeadProperty().getHeadMap().size(); while (index < headSize) { list.add(null); index++; From 63c830f2121e706e501eb49be70351617beed87e Mon Sep 17 00:00:00 2001 From: duanqiaoyanyu <825388931@qq.com> Date: Mon, 9 Aug 2021 17:55:55 +0800 Subject: [PATCH 084/129] fix: Fix the continuous occurrence of {}{} filled templates in excel, causing rendering failure after the first one --- .../alibaba/excel/write/executor/ExcelWriteFillExecutor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 5930a311..eac548cc 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -455,7 +455,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { analysisCell.setCellType(WriteTemplateAnalysisCellTypeEnum.COLLECTION); } analysisCell.getVariableList().add(variable); - if (lastPrepareDataIndex == prefixIndex) { + if (lastPrepareDataIndex == prefixIndex && 0 == prefixIndex) { analysisCell.getPrepareDataList().add(StringUtils.EMPTY); } else { String data = convertPrepareData(value.substring(lastPrepareDataIndex, prefixIndex)); From 6a21626085ea09013eb2c44ab06672989e2c2585 Mon Sep 17 00:00:00 2001 From: duanqiaoyanyu <825388931@qq.com> Date: Tue, 10 Aug 2021 10:34:21 +0800 Subject: [PATCH 085/129] fix: Fix the continuous occurrence of {}{} filled templates in excel, causing rendering failure after the first one --- .../excel/write/executor/ExcelWriteFillExecutor.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index eac548cc..b115be13 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -412,6 +412,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { int startIndex = 0; int length = value.length(); int lastPrepareDataIndex = 0; + int variableCount = 0; out: while (startIndex < length) { int prefixIndex = value.indexOf(FILL_PREFIX, startIndex); if (prefixIndex < 0) { @@ -442,7 +443,10 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { String variable = value.substring(prefixIndex + 1, suffixIndex); if (StringUtils.isEmpty(variable)) { continue; + } else { + ++variableCount; } + int collectPrefixIndex = variable.indexOf(COLLECTION_PREFIX); if (collectPrefixIndex > -1) { if (collectPrefixIndex != 0) { @@ -455,16 +459,20 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { analysisCell.setCellType(WriteTemplateAnalysisCellTypeEnum.COLLECTION); } analysisCell.getVariableList().add(variable); - if (lastPrepareDataIndex == prefixIndex && 0 == prefixIndex) { + if (lastPrepareDataIndex == prefixIndex) { analysisCell.getPrepareDataList().add(StringUtils.EMPTY); } else { String data = convertPrepareData(value.substring(lastPrepareDataIndex, prefixIndex)); preparedData.append(data); analysisCell.getPrepareDataList().add(data); - analysisCell.setOnlyOneVariable(Boolean.FALSE); } lastPrepareDataIndex = suffixIndex + 1; } + + if (variableCount >= 1) { + analysisCell.setOnlyOneVariable(Boolean.FALSE); + } + return dealAnalysisCell(analysisCell, value, rowIndex, lastPrepareDataIndex, length, firstRowCache, preparedData); } From 38371a62bb1e0ddec0395ba4b33f3f336e8af0cb Mon Sep 17 00:00:00 2001 From: duanqiaoyanyu <825388931@qq.com> Date: Tue, 10 Aug 2021 11:26:28 +0800 Subject: [PATCH 086/129] fix: Fix the continuous occurrence of {}{} filled templates in excel, causing rendering failure after the first one --- .../alibaba/excel/write/executor/ExcelWriteFillExecutor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index b115be13..526802a0 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -469,7 +469,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { lastPrepareDataIndex = suffixIndex + 1; } - if (variableCount >= 1) { + if (variableCount > 1) { analysisCell.setOnlyOneVariable(Boolean.FALSE); } From 5797cb3476009a9b8906c16c73c40bc06b234000 Mon Sep 17 00:00:00 2001 From: jipengfei-jpf <1558143046@qq.com> Date: Tue, 17 Aug 2021 21:50:01 +0800 Subject: [PATCH 087/129] Update README.md ok --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a108ff3c..bc091e8c 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都 * [贡献代码](https://www.yuque.com/easyexcel/doc/contribute) ## 维护者 -玉霄、庄家钜、怀宇 +姬朋飞(玉霄)、庄家钜、怀宇 ## 快速开始 ### 读Excel DEMO代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/demo/read/ReadTest.java](/src/test/java/com/alibaba/easyexcel/test/demo/read/ReadTest.java) From af1c88a22010ebb444e7e2378e530df014e3f878 Mon Sep 17 00:00:00 2001 From: James Date: Sat, 21 Aug 2021 20:14:33 +0800 Subject: [PATCH 088/129] =?UTF-8?q?=E4=B8=8B=E8=BD=BD=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=BF=9E=E6=8E=A5=E5=92=8C=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E7=9A=84=E8=B6=85=E6=97=B6=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在默认情况下,如果连接成功建立,但是下载速度极慢,在 Spring Web 应用中同步执行 Excel 的导出任务,会造成线程长时间被占用,最终造成 Tomcat 连接数超限,对应用造成毁灭性灾难。 --- .../alibaba/excel/converters/url/UrlImageConverter.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java b/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java index b622d66d..d178a5e9 100644 --- a/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java @@ -3,6 +3,7 @@ package com.alibaba.excel.converters.url; import java.io.IOException; import java.io.InputStream; import java.net.URL; +import java.net.URLConnection; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CellDataTypeEnum; @@ -39,8 +40,12 @@ public class UrlImageConverter implements Converter { GlobalConfiguration globalConfiguration) throws IOException { InputStream inputStream = null; try { - inputStream = value.openStream(); - byte[] bytes = IoUtils.toByteArray(inputStream); + + URLConnection conn = value.openConnection(); + conn.setConnectTimeout(1000); + conn.setReadTimeout(5000); + inputStream = con.getInputStream(); + byte[] bytes = IoUtils.toByteArray(inputStream); return new CellData(bytes); } finally { if (inputStream != null) { From 5a9f073643053358756a0f4fe6051de29d41d13f Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Tue, 7 Sep 2021 18:36:12 +0800 Subject: [PATCH 089/129] =?UTF-8?q?=E5=AE=8C=E6=88=90=E9=83=A8=E5=88=86?= =?UTF-8?q?=E6=94=AF=E6=8C=81csv?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 5 + .../java/com/alibaba/excel/csv/CsvCell.java | 225 ++++++ .../com/alibaba/excel/csv/CsvCellStyle.java | 301 ++++++++ .../com/alibaba/excel/csv/CsvDataFormat.java | 15 + .../java/com/alibaba/excel/csv/CsvRow.java | 143 ++++ .../java/com/alibaba/excel/csv/CsvSheet.java | 676 ++++++++++++++++++ .../com/alibaba/excel/csv/CsvWorkbook.java | 358 ++++++++++ .../alibaba/excel/support/ExcelTypeEnum.java | 6 + .../com/alibaba/excel/util/WorkBookUtil.java | 76 +- .../excel/write/metadata/WriteSheet.java | 59 +- .../metadata/holder/WriteWorkbookHolder.java | 17 +- .../easyexcel/test/demo/web/WebTest.java | 15 +- .../alibaba/easyexcel/test/temp/LockTest.java | 10 +- .../easyexcel/test/temp/csv/CsvData.java | 28 + .../easyexcel/test/temp/csv/CsvReadTest.java | 86 +++ .../test/temp/read/HeadReadTest.java | 1 + 16 files changed, 1919 insertions(+), 102 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/csv/CsvCell.java create mode 100644 src/main/java/com/alibaba/excel/csv/CsvCellStyle.java create mode 100644 src/main/java/com/alibaba/excel/csv/CsvDataFormat.java create mode 100644 src/main/java/com/alibaba/excel/csv/CsvRow.java create mode 100644 src/main/java/com/alibaba/excel/csv/CsvSheet.java create mode 100644 src/main/java/com/alibaba/excel/csv/CsvWorkbook.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvData.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java diff --git a/pom.xml b/pom.xml index 6477cfef..2466e22f 100644 --- a/pom.xml +++ b/pom.xml @@ -72,6 +72,11 @@ poi-ooxml-schemas 4.1.2 + + org.apache.commons + commons-csv + 1.8 + cglib cglib diff --git a/src/main/java/com/alibaba/excel/csv/CsvCell.java b/src/main/java/com/alibaba/excel/csv/CsvCell.java new file mode 100644 index 00000000..9c3a5d22 --- /dev/null +++ b/src/main/java/com/alibaba/excel/csv/CsvCell.java @@ -0,0 +1,225 @@ +package com.alibaba.excel.csv; + +import java.time.LocalDateTime; +import java.util.Calendar; +import java.util.Date; + +import org.apache.poi.ss.formula.FormulaParseException; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Comment; +import org.apache.poi.ss.usermodel.Hyperlink; +import org.apache.poi.ss.usermodel.RichTextString; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.util.CellAddress; +import org.apache.poi.ss.util.CellRangeAddress; + +/** + * TODO + * + * @author Jiaju Zhuang + */ +public class CsvCell implements Cell { + + @Override + public int getColumnIndex() { + return 0; + } + + @Override + public int getRowIndex() { + return 0; + } + + @Override + public Sheet getSheet() { + return null; + } + + @Override + public Row getRow() { + return null; + } + + @Override + public void setCellType(CellType cellType) { + + } + + @Override + public void setBlank() { + + } + + @Override + public CellType getCellType() { + return null; + } + + @Override + public CellType getCellTypeEnum() { + return null; + } + + @Override + public CellType getCachedFormulaResultType() { + return null; + } + + @Override + public CellType getCachedFormulaResultTypeEnum() { + return null; + } + + @Override + public void setCellValue(double value) { + + } + + @Override + public void setCellValue(Date value) { + + } + + @Override + public void setCellValue(LocalDateTime value) { + + } + + @Override + public void setCellValue(Calendar value) { + + } + + @Override + public void setCellValue(RichTextString value) { + + } + + @Override + public void setCellValue(String value) { + + } + + @Override + public void setCellFormula(String formula) throws FormulaParseException, IllegalStateException { + + } + + @Override + public void removeFormula() throws IllegalStateException { + + } + + @Override + public String getCellFormula() { + return null; + } + + @Override + public double getNumericCellValue() { + return 0; + } + + @Override + public Date getDateCellValue() { + return null; + } + + @Override + public LocalDateTime getLocalDateTimeCellValue() { + return null; + } + + @Override + public RichTextString getRichStringCellValue() { + return null; + } + + @Override + public String getStringCellValue() { + return null; + } + + @Override + public void setCellValue(boolean value) { + + } + + @Override + public void setCellErrorValue(byte value) { + + } + + @Override + public boolean getBooleanCellValue() { + return false; + } + + @Override + public byte getErrorCellValue() { + return 0; + } + + @Override + public void setCellStyle(CellStyle style) { + + } + + @Override + public CellStyle getCellStyle() { + return null; + } + + @Override + public void setAsActiveCell() { + + } + + @Override + public CellAddress getAddress() { + return null; + } + + @Override + public void setCellComment(Comment comment) { + + } + + @Override + public Comment getCellComment() { + return null; + } + + @Override + public void removeCellComment() { + + } + + @Override + public Hyperlink getHyperlink() { + return null; + } + + @Override + public void setHyperlink(Hyperlink link) { + + } + + @Override + public void removeHyperlink() { + + } + + @Override + public CellRangeAddress getArrayFormulaRange() { + return null; + } + + @Override + public boolean isPartOfArrayFormulaGroup() { + return false; + } +} diff --git a/src/main/java/com/alibaba/excel/csv/CsvCellStyle.java b/src/main/java/com/alibaba/excel/csv/CsvCellStyle.java new file mode 100644 index 00000000..318b42a4 --- /dev/null +++ b/src/main/java/com/alibaba/excel/csv/CsvCellStyle.java @@ -0,0 +1,301 @@ +package com.alibaba.excel.csv; + +import org.apache.poi.ss.usermodel.BorderStyle; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.Color; +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.VerticalAlignment; + +/** + * TODO + * + * @author Jiaju Zhuang + */ +public class CsvCellStyle implements CellStyle { + @Override + public short getIndex() { + return 0; + } + + @Override + public void setDataFormat(short fmt) { + + } + + @Override + public short getDataFormat() { + return 0; + } + + @Override + public String getDataFormatString() { + return null; + } + + @Override + public void setFont(Font font) { + + } + + @Override + public short getFontIndex() { + return 0; + } + + @Override + public int getFontIndexAsInt() { + return 0; + } + + @Override + public void setHidden(boolean hidden) { + + } + + @Override + public boolean getHidden() { + return false; + } + + @Override + public void setLocked(boolean locked) { + + } + + @Override + public boolean getLocked() { + return false; + } + + @Override + public void setQuotePrefixed(boolean quotePrefix) { + + } + + @Override + public boolean getQuotePrefixed() { + return false; + } + + @Override + public void setAlignment(HorizontalAlignment align) { + + } + + @Override + public HorizontalAlignment getAlignment() { + return null; + } + + @Override + public HorizontalAlignment getAlignmentEnum() { + return null; + } + + @Override + public void setWrapText(boolean wrapped) { + + } + + @Override + public boolean getWrapText() { + return false; + } + + @Override + public void setVerticalAlignment(VerticalAlignment align) { + + } + + @Override + public VerticalAlignment getVerticalAlignment() { + return null; + } + + @Override + public VerticalAlignment getVerticalAlignmentEnum() { + return null; + } + + @Override + public void setRotation(short rotation) { + + } + + @Override + public short getRotation() { + return 0; + } + + @Override + public void setIndention(short indent) { + + } + + @Override + public short getIndention() { + return 0; + } + + @Override + public void setBorderLeft(BorderStyle border) { + + } + + @Override + public BorderStyle getBorderLeft() { + return null; + } + + @Override + public BorderStyle getBorderLeftEnum() { + return null; + } + + @Override + public void setBorderRight(BorderStyle border) { + + } + + @Override + public BorderStyle getBorderRight() { + return null; + } + + @Override + public BorderStyle getBorderRightEnum() { + return null; + } + + @Override + public void setBorderTop(BorderStyle border) { + + } + + @Override + public BorderStyle getBorderTop() { + return null; + } + + @Override + public BorderStyle getBorderTopEnum() { + return null; + } + + @Override + public void setBorderBottom(BorderStyle border) { + + } + + @Override + public BorderStyle getBorderBottom() { + return null; + } + + @Override + public BorderStyle getBorderBottomEnum() { + return null; + } + + @Override + public void setLeftBorderColor(short color) { + + } + + @Override + public short getLeftBorderColor() { + return 0; + } + + @Override + public void setRightBorderColor(short color) { + + } + + @Override + public short getRightBorderColor() { + return 0; + } + + @Override + public void setTopBorderColor(short color) { + + } + + @Override + public short getTopBorderColor() { + return 0; + } + + @Override + public void setBottomBorderColor(short color) { + + } + + @Override + public short getBottomBorderColor() { + return 0; + } + + @Override + public void setFillPattern(FillPatternType fp) { + + } + + @Override + public FillPatternType getFillPattern() { + return null; + } + + @Override + public FillPatternType getFillPatternEnum() { + return null; + } + + @Override + public void setFillBackgroundColor(short bg) { + + } + + @Override + public short getFillBackgroundColor() { + return 0; + } + + @Override + public Color getFillBackgroundColorColor() { + return null; + } + + @Override + public void setFillForegroundColor(short bg) { + + } + + @Override + public short getFillForegroundColor() { + return 0; + } + + @Override + public Color getFillForegroundColorColor() { + return null; + } + + @Override + public void cloneStyleFrom(CellStyle source) { + + } + + @Override + public void setShrinkToFit(boolean shrinkToFit) { + + } + + @Override + public boolean getShrinkToFit() { + return false; + } +} diff --git a/src/main/java/com/alibaba/excel/csv/CsvDataFormat.java b/src/main/java/com/alibaba/excel/csv/CsvDataFormat.java new file mode 100644 index 00000000..2961fbf1 --- /dev/null +++ b/src/main/java/com/alibaba/excel/csv/CsvDataFormat.java @@ -0,0 +1,15 @@ +package com.alibaba.excel.csv; + +import org.apache.poi.ss.usermodel.DataFormat; + +public class CsvDataFormat implements DataFormat { + @Override + public short getFormat(String format) { + return 0; + } + + @Override + public String getFormat(short index) { + return null; + } +} diff --git a/src/main/java/com/alibaba/excel/csv/CsvRow.java b/src/main/java/com/alibaba/excel/csv/CsvRow.java new file mode 100644 index 00000000..6a979417 --- /dev/null +++ b/src/main/java/com/alibaba/excel/csv/CsvRow.java @@ -0,0 +1,143 @@ +package com.alibaba.excel.csv; + +import java.util.Iterator; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; + +/** + * TODO + * + * @author Jiaju Zhuang + */ +public class CsvRow implements Row { + + + @Override + public Cell createCell(int column) { + return new CsvCell(); + } + + @Override + public Cell createCell(int column, CellType type) { + return null; + } + + @Override + public void removeCell(Cell cell) { + + } + + @Override + public void setRowNum(int rowNum) { + + } + + @Override + public int getRowNum() { + return 0; + } + + @Override + public Cell getCell(int cellnum) { + return null; + } + + @Override + public Cell getCell(int cellnum, MissingCellPolicy policy) { + return null; + } + + @Override + public short getFirstCellNum() { + return 0; + } + + @Override + public short getLastCellNum() { + return 0; + } + + @Override + public int getPhysicalNumberOfCells() { + return 0; + } + + @Override + public void setHeight(short height) { + + } + + @Override + public void setZeroHeight(boolean zHeight) { + + } + + @Override + public boolean getZeroHeight() { + return false; + } + + @Override + public void setHeightInPoints(float height) { + + } + + @Override + public short getHeight() { + return 0; + } + + @Override + public float getHeightInPoints() { + return 0; + } + + @Override + public boolean isFormatted() { + return false; + } + + @Override + public CellStyle getRowStyle() { + return null; + } + + @Override + public void setRowStyle(CellStyle style) { + + } + + @Override + public Iterator cellIterator() { + return null; + } + + @Override + public Sheet getSheet() { + return null; + } + + @Override + public int getOutlineLevel() { + return 0; + } + + @Override + public void shiftCellsRight(int firstShiftColumnIndex, int lastShiftColumnIndex, int step) { + + } + + @Override + public void shiftCellsLeft(int firstShiftColumnIndex, int lastShiftColumnIndex, int step) { + + } + + @Override + public Iterator iterator() { + return null; + } +} diff --git a/src/main/java/com/alibaba/excel/csv/CsvSheet.java b/src/main/java/com/alibaba/excel/csv/CsvSheet.java new file mode 100644 index 00000000..eda6484a --- /dev/null +++ b/src/main/java/com/alibaba/excel/csv/CsvSheet.java @@ -0,0 +1,676 @@ +package com.alibaba.excel.csv; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.Charset; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.alibaba.excel.util.ListUtils; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.poi.ss.usermodel.AutoFilter; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellRange; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.Comment; +import org.apache.poi.ss.usermodel.DataValidation; +import org.apache.poi.ss.usermodel.DataValidationHelper; +import org.apache.poi.ss.usermodel.Drawing; +import org.apache.poi.ss.usermodel.Footer; +import org.apache.poi.ss.usermodel.Header; +import org.apache.poi.ss.usermodel.Hyperlink; +import org.apache.poi.ss.usermodel.PrintSetup; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.SheetConditionalFormatting; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.util.CellAddress; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.util.PaneInformation; + +/** + * TODO + * + * @author Jiaju Zhuang + */ +public class CsvSheet implements Sheet { + + public static int rowCacheCount = 500; + public static Charset defaultCharset = Charset.defaultCharset(); + + public CSVPrinter csvPrinter; + + private int lastRowNum = -1; + + private List rowCache = ListUtils.newArrayListWithExpectedSize(rowCacheCount); + + public CsvSheet(File file) throws IOException { + csvPrinter = CSVFormat.DEFAULT.print(file, defaultCharset); + } + + public CsvSheet(OutputStream outputStream) throws IOException { + csvPrinter = CSVFormat.DEFAULT.print(new OutputStreamWriter(outputStream)); + } + + @Override + public Row createRow(int rownum) { + lastRowNum++; + assert rownum == lastRowNum : "csv create row must be in order."; + printData(); + CsvRow csvRow = new CsvRow(); + rowCache.add(csvRow); + return csvRow; + } + + @Override + public void removeRow(Row row) { + + } + + @Override + public Row getRow(int rownum) { + return null; + } + + @Override + public int getPhysicalNumberOfRows() { + return 0; + } + + @Override + public int getFirstRowNum() { + return 0; + } + + @Override + public int getLastRowNum() { + return 0; + } + + @Override + public void setColumnHidden(int columnIndex, boolean hidden) { + + } + + @Override + public boolean isColumnHidden(int columnIndex) { + return false; + } + + @Override + public void setRightToLeft(boolean value) { + + } + + @Override + public boolean isRightToLeft() { + return false; + } + + @Override + public void setColumnWidth(int columnIndex, int width) { + + } + + @Override + public int getColumnWidth(int columnIndex) { + return 0; + } + + @Override + public float getColumnWidthInPixels(int columnIndex) { + return 0; + } + + @Override + public void setDefaultColumnWidth(int width) { + + } + + @Override + public int getDefaultColumnWidth() { + return 0; + } + + @Override + public short getDefaultRowHeight() { + return 0; + } + + @Override + public float getDefaultRowHeightInPoints() { + return 0; + } + + @Override + public void setDefaultRowHeight(short height) { + + } + + @Override + public void setDefaultRowHeightInPoints(float height) { + + } + + @Override + public CellStyle getColumnStyle(int column) { + return null; + } + + @Override + public int addMergedRegion(CellRangeAddress region) { + return 0; + } + + @Override + public int addMergedRegionUnsafe(CellRangeAddress region) { + return 0; + } + + @Override + public void validateMergedRegions() { + + } + + @Override + public void setVerticallyCenter(boolean value) { + + } + + @Override + public void setHorizontallyCenter(boolean value) { + + } + + @Override + public boolean getHorizontallyCenter() { + return false; + } + + @Override + public boolean getVerticallyCenter() { + return false; + } + + @Override + public void removeMergedRegion(int index) { + + } + + @Override + public void removeMergedRegions(Collection indices) { + + } + + @Override + public int getNumMergedRegions() { + return 0; + } + + @Override + public CellRangeAddress getMergedRegion(int index) { + return null; + } + + @Override + public List getMergedRegions() { + return null; + } + + @Override + public Iterator rowIterator() { + return null; + } + + @Override + public void setForceFormulaRecalculation(boolean value) { + + } + + @Override + public boolean getForceFormulaRecalculation() { + return false; + } + + @Override + public void setAutobreaks(boolean value) { + + } + + @Override + public void setDisplayGuts(boolean value) { + + } + + @Override + public void setDisplayZeros(boolean value) { + + } + + @Override + public boolean isDisplayZeros() { + return false; + } + + @Override + public void setFitToPage(boolean value) { + + } + + @Override + public void setRowSumsBelow(boolean value) { + + } + + @Override + public void setRowSumsRight(boolean value) { + + } + + @Override + public boolean getAutobreaks() { + return false; + } + + @Override + public boolean getDisplayGuts() { + return false; + } + + @Override + public boolean getFitToPage() { + return false; + } + + @Override + public boolean getRowSumsBelow() { + return false; + } + + @Override + public boolean getRowSumsRight() { + return false; + } + + @Override + public boolean isPrintGridlines() { + return false; + } + + @Override + public void setPrintGridlines(boolean show) { + + } + + @Override + public boolean isPrintRowAndColumnHeadings() { + return false; + } + + @Override + public void setPrintRowAndColumnHeadings(boolean show) { + + } + + @Override + public PrintSetup getPrintSetup() { + return null; + } + + @Override + public Header getHeader() { + return null; + } + + @Override + public Footer getFooter() { + return null; + } + + @Override + public void setSelected(boolean value) { + + } + + @Override + public double getMargin(short margin) { + return 0; + } + + @Override + public void setMargin(short margin, double size) { + + } + + @Override + public boolean getProtect() { + return false; + } + + @Override + public void protectSheet(String password) { + + } + + @Override + public boolean getScenarioProtect() { + return false; + } + + @Override + public void setZoom(int scale) { + + } + + @Override + public short getTopRow() { + return 0; + } + + @Override + public short getLeftCol() { + return 0; + } + + @Override + public void showInPane(int topRow, int leftCol) { + + } + + @Override + public void shiftRows(int startRow, int endRow, int n) { + + } + + @Override + public void shiftRows(int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight) { + + } + + @Override + public void shiftColumns(int startColumn, int endColumn, int n) { + + } + + @Override + public void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow) { + + } + + @Override + public void createFreezePane(int colSplit, int rowSplit) { + + } + + @Override + public void createSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, int activePane) { + + } + + @Override + public PaneInformation getPaneInformation() { + return null; + } + + @Override + public void setDisplayGridlines(boolean show) { + + } + + @Override + public boolean isDisplayGridlines() { + return false; + } + + @Override + public void setDisplayFormulas(boolean show) { + + } + + @Override + public boolean isDisplayFormulas() { + return false; + } + + @Override + public void setDisplayRowColHeadings(boolean show) { + + } + + @Override + public boolean isDisplayRowColHeadings() { + return false; + } + + @Override + public void setRowBreak(int row) { + + } + + @Override + public boolean isRowBroken(int row) { + return false; + } + + @Override + public void removeRowBreak(int row) { + + } + + @Override + public int[] getRowBreaks() { + return new int[0]; + } + + @Override + public int[] getColumnBreaks() { + return new int[0]; + } + + @Override + public void setColumnBreak(int column) { + + } + + @Override + public boolean isColumnBroken(int column) { + return false; + } + + @Override + public void removeColumnBreak(int column) { + + } + + @Override + public void setColumnGroupCollapsed(int columnNumber, boolean collapsed) { + + } + + @Override + public void groupColumn(int fromColumn, int toColumn) { + + } + + @Override + public void ungroupColumn(int fromColumn, int toColumn) { + + } + + @Override + public void groupRow(int fromRow, int toRow) { + + } + + @Override + public void ungroupRow(int fromRow, int toRow) { + + } + + @Override + public void setRowGroupCollapsed(int row, boolean collapse) { + + } + + @Override + public void setDefaultColumnStyle(int column, CellStyle style) { + + } + + @Override + public void autoSizeColumn(int column) { + + } + + @Override + public void autoSizeColumn(int column, boolean useMergedCells) { + + } + + @Override + public Comment getCellComment(CellAddress ref) { + return null; + } + + @Override + public Map getCellComments() { + return null; + } + + @Override + public Drawing getDrawingPatriarch() { + return null; + } + + @Override + public Drawing createDrawingPatriarch() { + return null; + } + + @Override + public Workbook getWorkbook() { + return null; + } + + @Override + public String getSheetName() { + return null; + } + + @Override + public boolean isSelected() { + return false; + } + + @Override + public CellRange setArrayFormula( + String formula, CellRangeAddress range) { + return null; + } + + @Override + public CellRange removeArrayFormula(Cell cell) { + return null; + } + + @Override + public DataValidationHelper getDataValidationHelper() { + return null; + } + + @Override + public List getDataValidations() { + return null; + } + + @Override + public void addValidationData(DataValidation dataValidation) { + + } + + @Override + public AutoFilter setAutoFilter(CellRangeAddress range) { + return null; + } + + @Override + public SheetConditionalFormatting getSheetConditionalFormatting() { + return null; + } + + @Override + public CellRangeAddress getRepeatingRows() { + return null; + } + + @Override + public CellRangeAddress getRepeatingColumns() { + return null; + } + + @Override + public void setRepeatingRows(CellRangeAddress rowRangeRef) { + + } + + @Override + public void setRepeatingColumns(CellRangeAddress columnRangeRef) { + + } + + @Override + public int getColumnOutlineLevel(int columnIndex) { + return 0; + } + + @Override + public Hyperlink getHyperlink(int row, int column) { + return null; + } + + @Override + public Hyperlink getHyperlink(CellAddress addr) { + return null; + } + + @Override + public List getHyperlinkList() { + return null; + } + + @Override + public CellAddress getActiveCell() { + return null; + } + + @Override + public void setActiveCell(CellAddress address) { + + } + + @Override + public Iterator iterator() { + return null; + } + + public void printData() { + if (rowCache.size() >= rowCacheCount) { + flushData(); + rowCache.clear(); + } + } + + public void flushData() { + try { + csvPrinter.printRecord(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/alibaba/excel/csv/CsvWorkbook.java b/src/main/java/com/alibaba/excel/csv/CsvWorkbook.java new file mode 100644 index 00000000..20002d83 --- /dev/null +++ b/src/main/java/com/alibaba/excel/csv/CsvWorkbook.java @@ -0,0 +1,358 @@ +package com.alibaba.excel.csv; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Iterator; +import java.util.List; + +import lombok.Data; +import org.apache.poi.ss.SpreadsheetVersion; +import org.apache.poi.ss.formula.udf.UDFFinder; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.CreationHelper; +import org.apache.poi.ss.usermodel.DataFormat; +import org.apache.poi.ss.usermodel.Font; +import org.apache.poi.ss.usermodel.Name; +import org.apache.poi.ss.usermodel.PictureData; +import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.SheetVisibility; +import org.apache.poi.ss.usermodel.Workbook; + +/** + * TODO + * + * @author Jiaju Zhuang + */ +@Data +public class CsvWorkbook implements Workbook { + + private CsvSheet csvSheet; + + public CsvWorkbook(InputStream inputStream, File file) { + try { + this.csvSheet = new CsvSheet(file); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public int getActiveSheetIndex() { + return 0; + } + + @Override + public void setActiveSheet(int sheetIndex) { + + } + + @Override + public int getFirstVisibleTab() { + return 0; + } + + @Override + public void setFirstVisibleTab(int sheetIndex) { + + } + + @Override + public void setSheetOrder(String sheetname, int pos) { + + } + + @Override + public void setSelectedTab(int index) { + + } + + @Override + public void setSheetName(int sheet, String name) { + + } + + @Override + public String getSheetName(int sheet) { + return null; + } + + @Override + public int getSheetIndex(String name) { + return 0; + } + + @Override + public int getSheetIndex(Sheet sheet) { + return 0; + } + + @Override + public Sheet createSheet() { + return csvSheet; + } + + @Override + public Sheet createSheet(String sheetname) { + return csvSheet; + } + + @Override + public Sheet cloneSheet(int sheetNum) { + return null; + } + + @Override + public Iterator sheetIterator() { + return null; + } + + @Override + public int getNumberOfSheets() { + return 0; + } + + @Override + public Sheet getSheetAt(int index) { + return null; + } + + @Override + public Sheet getSheet(String name) { + return null; + } + + @Override + public void removeSheetAt(int index) { + + } + + @Override + public Font createFont() { + return null; + } + + @Override + public Font findFont(boolean bold, short color, short fontHeight, String name, boolean italic, boolean strikeout, + short typeOffset, byte underline) { + return null; + } + + @Override + public short getNumberOfFonts() { + return 0; + } + + @Override + public int getNumberOfFontsAsInt() { + return 0; + } + + @Override + public Font getFontAt(short idx) { + return null; + } + + @Override + public Font getFontAt(int idx) { + return null; + } + + @Override + public CellStyle createCellStyle() { + return new CsvCellStyle(); + } + + @Override + public int getNumCellStyles() { + return 0; + } + + @Override + public CellStyle getCellStyleAt(int idx) { + return null; + } + + @Override + public void write(OutputStream stream) throws IOException { + csvSheet.csvPrinter.flush(); + csvSheet.csvPrinter.close(); + } + + @Override + public void close() throws IOException { + + } + + @Override + public int getNumberOfNames() { + return 0; + } + + @Override + public Name getName(String name) { + return null; + } + + @Override + public List getNames(String name) { + return null; + } + + @Override + public List getAllNames() { + return null; + } + + @Override + public Name getNameAt(int nameIndex) { + return null; + } + + @Override + public Name createName() { + return null; + } + + @Override + public int getNameIndex(String name) { + return 0; + } + + @Override + public void removeName(int index) { + + } + + @Override + public void removeName(String name) { + + } + + @Override + public void removeName(Name name) { + + } + + @Override + public int linkExternalWorkbook(String name, Workbook workbook) { + return 0; + } + + @Override + public void setPrintArea(int sheetIndex, String reference) { + + } + + @Override + public void setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow) { + + } + + @Override + public String getPrintArea(int sheetIndex) { + return null; + } + + @Override + public void removePrintArea(int sheetIndex) { + + } + + @Override + public MissingCellPolicy getMissingCellPolicy() { + return null; + } + + @Override + public void setMissingCellPolicy(MissingCellPolicy missingCellPolicy) { + + } + + @Override + public DataFormat createDataFormat() { + return new CsvDataFormat(); + } + + @Override + public int addPicture(byte[] pictureData, int format) { + return 0; + } + + @Override + public List getAllPictures() { + return null; + } + + @Override + public CreationHelper getCreationHelper() { + return null; + } + + @Override + public boolean isHidden() { + return false; + } + + @Override + public void setHidden(boolean hiddenFlag) { + + } + + @Override + public boolean isSheetHidden(int sheetIx) { + return false; + } + + @Override + public boolean isSheetVeryHidden(int sheetIx) { + return false; + } + + @Override + public void setSheetHidden(int sheetIx, boolean hidden) { + + } + + @Override + public SheetVisibility getSheetVisibility(int sheetIx) { + return null; + } + + @Override + public void setSheetVisibility(int sheetIx, SheetVisibility visibility) { + + } + + @Override + public void addToolPack(UDFFinder toopack) { + + } + + @Override + public void setForceFormulaRecalculation(boolean value) { + + } + + @Override + public boolean getForceFormulaRecalculation() { + return false; + } + + @Override + public SpreadsheetVersion getSpreadsheetVersion() { + return null; + } + + @Override + public int addOlePackage(byte[] oleData, String label, String fileName, String command) throws IOException { + return 0; + } + + @Override + public Iterator iterator() { + return null; + } +} diff --git a/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java b/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java index 7158a69c..eb4c4cbd 100644 --- a/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java +++ b/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java @@ -16,6 +16,10 @@ import org.apache.poi.poifs.filesystem.FileMagic; * @author jipengfei */ public enum ExcelTypeEnum { + /** + * csv + */ + CSV(".csv"), /** * xls */ @@ -58,6 +62,8 @@ public enum ExcelTypeEnum { return XLSX; } else if (fileName.endsWith(XLS.getValue())) { return XLS; + } else if (fileName.endsWith(CSV.getValue())) { + return CSV; } if (StringUtils.isEmpty(readWorkbook.getPassword())) { try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) { diff --git a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java index 8aa2bfbf..0760e895 100644 --- a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java +++ b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java @@ -2,9 +2,9 @@ package com.alibaba.excel.util; import java.io.IOException; +import com.alibaba.excel.csv.CsvWorkbook; import com.alibaba.excel.metadata.data.DataFormatData; import com.alibaba.excel.metadata.data.WriteCellData; -import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; import com.alibaba.excel.write.metadata.style.WriteCellStyle; @@ -29,39 +29,57 @@ public class WorkBookUtil { private WorkBookUtil() {} public static void createWorkBook(WriteWorkbookHolder writeWorkbookHolder) throws IOException { - if (ExcelTypeEnum.XLSX.equals(writeWorkbookHolder.getExcelType())) { - if (writeWorkbookHolder.getTempTemplateInputStream() != null) { - XSSFWorkbook xssfWorkbook = new XSSFWorkbook(writeWorkbookHolder.getTempTemplateInputStream()); - writeWorkbookHolder.setCachedWorkbook(xssfWorkbook); + switch (writeWorkbookHolder.getExcelType()) { + case XLSX: + if (writeWorkbookHolder.getTempTemplateInputStream() != null) { + XSSFWorkbook xssfWorkbook = new XSSFWorkbook(writeWorkbookHolder.getTempTemplateInputStream()); + writeWorkbookHolder.setCachedWorkbook(xssfWorkbook); + if (writeWorkbookHolder.getInMemory()) { + writeWorkbookHolder.setWorkbook(xssfWorkbook); + } else { + writeWorkbookHolder.setWorkbook(new SXSSFWorkbook(xssfWorkbook, ROW_ACCESS_WINDOW_SIZE)); + } + return; + } + Workbook workbook; if (writeWorkbookHolder.getInMemory()) { - writeWorkbookHolder.setWorkbook(xssfWorkbook); + workbook = new XSSFWorkbook(); } else { - writeWorkbookHolder.setWorkbook(new SXSSFWorkbook(xssfWorkbook, ROW_ACCESS_WINDOW_SIZE)); + workbook = new SXSSFWorkbook(ROW_ACCESS_WINDOW_SIZE); } + writeWorkbookHolder.setCachedWorkbook(workbook); + writeWorkbookHolder.setWorkbook(workbook); return; - } - Workbook workbook = null; - if (writeWorkbookHolder.getInMemory()) { - workbook = new XSSFWorkbook(); - } else { - workbook = new SXSSFWorkbook(ROW_ACCESS_WINDOW_SIZE); - } - writeWorkbookHolder.setCachedWorkbook(workbook); - writeWorkbookHolder.setWorkbook(workbook); - return; - } - HSSFWorkbook hssfWorkbook; - if (writeWorkbookHolder.getTempTemplateInputStream() != null) { - hssfWorkbook = new HSSFWorkbook(new POIFSFileSystem(writeWorkbookHolder.getTempTemplateInputStream())); - } else { - hssfWorkbook = new HSSFWorkbook(); - } - writeWorkbookHolder.setCachedWorkbook(hssfWorkbook); - writeWorkbookHolder.setWorkbook(hssfWorkbook); - if (writeWorkbookHolder.getPassword() != null) { - Biff8EncryptionKey.setCurrentUserPassword(writeWorkbookHolder.getPassword()); - hssfWorkbook.writeProtectWorkbook(writeWorkbookHolder.getPassword(), StringUtils.EMPTY); + case XLS: + HSSFWorkbook hssfWorkbook; + if (writeWorkbookHolder.getTempTemplateInputStream() != null) { + hssfWorkbook = new HSSFWorkbook( + new POIFSFileSystem(writeWorkbookHolder.getTempTemplateInputStream())); + } else { + hssfWorkbook = new HSSFWorkbook(); + } + writeWorkbookHolder.setCachedWorkbook(hssfWorkbook); + writeWorkbookHolder.setWorkbook(hssfWorkbook); + if (writeWorkbookHolder.getPassword() != null) { + Biff8EncryptionKey.setCurrentUserPassword(writeWorkbookHolder.getPassword()); + hssfWorkbook.writeProtectWorkbook(writeWorkbookHolder.getPassword(), StringUtils.EMPTY); + } + return; + case CSV: + CsvWorkbook csvWorkbook; + if (writeWorkbookHolder.getTempTemplateInputStream() != null) { + csvWorkbook = new CsvWorkbook(writeWorkbookHolder.getTempTemplateInputStream(), + writeWorkbookHolder.getFile()); + } else { + csvWorkbook = new CsvWorkbook(null, writeWorkbookHolder.getFile()); + } + writeWorkbookHolder.setCachedWorkbook(csvWorkbook); + writeWorkbookHolder.setWorkbook(csvWorkbook); + return; + default: + throw new UnsupportedOperationException("Wrong excel type."); } + } public static Sheet createSheet(Workbook workbook, String sheetName) { diff --git a/src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java b/src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java index 96e88c2e..04bfb822 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java +++ b/src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java @@ -1,18 +1,13 @@ package com.alibaba.excel.write.metadata; -import java.util.HashMap; -import java.util.Map; - -import com.alibaba.excel.write.style.HorizontalCellStyleStrategy; -import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy; - -import org.apache.poi.ss.usermodel.TableStyle; +import lombok.Data; /** * Write sheet * * @author jipengfei */ +@Data public class WriteSheet extends WriteBasicParameter { /** * Starting from 0 @@ -22,54 +17,4 @@ public class WriteSheet extends WriteBasicParameter { * sheet name */ private String sheetName; - /** - * column with - * - * @deprecated please use {@link SimpleColumnWidthStyleStrategy} - */ - @Deprecated - private Map columnWidthMap = new HashMap(); - /** - * - * @deprecated please use{@link HorizontalCellStyleStrategy} - */ - @Deprecated - private TableStyle tableStyle; - - public Integer getSheetNo() { - return sheetNo; - } - - public void setSheetNo(Integer sheetNo) { - this.sheetNo = sheetNo; - } - - public String getSheetName() { - return sheetName; - } - - public void setSheetName(String sheetName) { - this.sheetName = sheetName; - } - - public Map getColumnWidthMap() { - return columnWidthMap; - } - - public void setColumnWidthMap(Map columnWidthMap) { - this.columnWidthMap = columnWidthMap; - } - - public TableStyle getTableStyle() { - return tableStyle; - } - - public void setTableStyle(TableStyle tableStyle) { - this.tableStyle = tableStyle; - } - - @Override - public String toString() { - return "WriteSheet{" + "sheetNo=" + sheetNo + ", sheetName='" + sheetName + '\'' + "} " + super.toString(); - } } diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java index cfbfcf4d..a2a0d113 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java @@ -164,7 +164,14 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { if (isXls) { this.excelType = ExcelTypeEnum.XLS; } else { - this.excelType = ExcelTypeEnum.XLSX; + boolean isCsv = (file != null && file.getName().endsWith(ExcelTypeEnum.CSV.getValue())) + || (writeWorkbook.getTemplateFile() != null + && writeWorkbook.getTemplateFile().getName().endsWith(ExcelTypeEnum.CSV.getValue())); + if (isCsv) { + this.excelType = ExcelTypeEnum.CSV; + } else { + this.excelType = ExcelTypeEnum.XLSX; + } } } else { this.excelType = writeWorkbook.getExcelType(); @@ -174,8 +181,8 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { } else { this.mandatoryUseInputStream = writeWorkbook.getMandatoryUseInputStream(); } - this.hasBeenInitializedSheetIndexMap = new HashMap(); - this.hasBeenInitializedSheetNameMap = new HashMap(); + this.hasBeenInitializedSheetIndexMap = new HashMap<>(); + this.hasBeenInitializedSheetNameMap = new HashMap<>(); this.password = writeWorkbook.getPassword(); if (writeWorkbook.getInMemory() == null) { this.inMemory = Boolean.FALSE; @@ -188,8 +195,8 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { this.writeExcelOnException = writeWorkbook.getWriteExcelOnException(); } this.cellStyleMap = MapUtils.newHashMap(); - this.fontMap= MapUtils.newHashMap(); - this.dataFormatMap=MapUtils.newHashMap(); + this.fontMap = MapUtils.newHashMap(); + this.dataFormatMap = MapUtils.newHashMap(); } private void copyTemplate() throws IOException { diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java index 0a147564..af2dfce5 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java @@ -10,6 +10,9 @@ import java.util.Map; import javax.servlet.http.HttpServletResponse; +import com.alibaba.excel.EasyExcel; +import com.alibaba.fastjson.JSON; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @@ -17,10 +20,6 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; -import com.alibaba.excel.EasyExcel; -import com.alibaba.excel.support.ExcelTypeEnum; -import com.alibaba.fastjson.JSON; - /** * web读写案例 * @@ -49,7 +48,13 @@ public class WebTest { // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系 String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20"); response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); - EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data()); + + ArrayList> list = new ArrayList<>(); + ArrayList sublist = new ArrayList(); + sublist.add("t1"); + sublist.add("t2"); + list.add(sublist); + EasyExcel.write(response.getOutputStream()).sheet("模板").doWrite(list); } /** diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/LockTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/LockTest.java index ad09717f..031e5114 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/LockTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/LockTest.java @@ -1,18 +1,17 @@ package com.alibaba.easyexcel.test.temp; -import java.io.File; import java.io.FileInputStream; import java.util.List; import java.util.Map; +import com.alibaba.excel.EasyExcel; +import com.alibaba.fastjson.JSON; + import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.alibaba.excel.EasyExcel; -import com.alibaba.fastjson.JSON; - /** * 临时测试 * @@ -24,9 +23,8 @@ public class LockTest { @Test public void test() throws Exception { - List list = - EasyExcel.read(new FileInputStream("/Users/zhuangjiaju/Downloads/点位配置表 (1).xlsx")).doReadAllSync(); + EasyExcel.read(new FileInputStream("/Users/zhuangjiaju/test/pic.xls")).doReadAllSync(); for (Object data : list) { LOGGER.info("返回数据:{}", JSON.toJSONString(data)); } diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvData.java b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvData.java new file mode 100644 index 00000000..2f645339 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvData.java @@ -0,0 +1,28 @@ +package com.alibaba.easyexcel.test.temp.csv; + +import java.util.Date; + +import com.alibaba.excel.annotation.ExcelIgnore; +import com.alibaba.excel.annotation.ExcelProperty; + +import lombok.Data; + +/** + * TODO + * + * @author Jiaju Zhuang + */ +@Data +public class CsvData { + @ExcelProperty("字符串标题") + private String string; + @ExcelProperty("日期标题") + private Date date; + @ExcelProperty("数字标题") + private Double doubleData; + /** + * 忽略这个字段 + */ + @ExcelIgnore + private String ignore; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java new file mode 100644 index 00000000..b9af89e4 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java @@ -0,0 +1,86 @@ +package com.alibaba.easyexcel.test.temp.csv; + +import java.io.File; +import java.io.FileInputStream; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.poi.poifs.filesystem.FileMagic; +import org.junit.Ignore; +import org.junit.Test; + +@Ignore +@Slf4j +public class CsvReadTest { + + @Test + public void write() throws Exception { + Appendable out = new PrintWriter(TestFileUtil.createNewFile("csvWrite.csv")); + CSVPrinter printer = CSVFormat.DEFAULT.withHeader("userId", "userName") + .print(out); + for (int i = 0; i < 10; i++) { + printer.printRecord("userId" + i, "userName" + i); + } + printer.flush(); + printer.close(); + } + + @Test + public void csvWrite() throws Exception { + // 写法1 + String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".csv"; + // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 + // 如果这里想使用03 则 传入excelType参数即可 + EasyExcel.write(fileName, CsvData.class).sheet().doWrite(data()); + } + + @Test + public void writev2() throws Exception { + // 写法1 + String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".csv"; + // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 + // 如果这里想使用03 则 传入excelType参数即可 + EasyExcel.write(fileName, CsvData.class).sheet().doWrite(data()); + } + + @Test + public void writeFile() throws Exception { + FileInputStream fileInputStream = new FileInputStream(new File("/Users/zhuangjiaju/test/test1.csv")); + FileMagic fileMagic = FileMagic.valueOf(fileInputStream); + log.info("{}", fileMagic); + } + + private List data() { + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + CsvData data = new CsvData(); + data.setString("字符串" + i); + data.setDate(new Date()); + data.setDoubleData(0.56); + data.setIgnore("忽略" + i); + list.add(data); + } + return list; + } + + @Test + public void read() { + // + //Iterable records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(in); + //for (CSVRecord record : records) { + // String lastName = record.get("id"); + // String firstName = record.get("name"); + // System.out.println(lastName); + // System.out.println(firstName); + //} + + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/read/HeadReadTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/read/HeadReadTest.java index 99fccd70..6649c2fe 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/read/HeadReadTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/read/HeadReadTest.java @@ -38,4 +38,5 @@ public class HeadReadTest { EasyExcel.read(file, HeadReadData.class, new HDListener()).readCache(new Ehcache(20)).sheet(0).doRead(); } + } From fbb79df74c0dbe972939aa2ac3c98464256086e9 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Tue, 7 Sep 2021 19:03:59 +0800 Subject: [PATCH 090/129] =?UTF-8?q?=E8=B7=91=E9=80=9Acsv=20=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/alibaba/excel/csv/CsvCell.java | 12 +++++++++--- src/main/java/com/alibaba/excel/csv/CsvRow.java | 11 ++++++++--- src/main/java/com/alibaba/excel/csv/CsvSheet.java | 5 ++++- src/main/java/com/alibaba/excel/csv/CsvWorkbook.java | 1 + .../alibaba/easyexcel/test/temp/csv/CsvReadTest.java | 2 +- 5 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/alibaba/excel/csv/CsvCell.java b/src/main/java/com/alibaba/excel/csv/CsvCell.java index 9c3a5d22..84808bf0 100644 --- a/src/main/java/com/alibaba/excel/csv/CsvCell.java +++ b/src/main/java/com/alibaba/excel/csv/CsvCell.java @@ -23,6 +23,8 @@ import org.apache.poi.ss.util.CellRangeAddress; */ public class CsvCell implements Cell { + private String value; + @Override public int getColumnIndex() { return 0; @@ -75,11 +77,12 @@ public class CsvCell implements Cell { @Override public void setCellValue(double value) { - + this.value = value + ""; } @Override public void setCellValue(Date value) { + this.value = value.toString(); } @@ -100,7 +103,7 @@ public class CsvCell implements Cell { @Override public void setCellValue(String value) { - + this.value = value; } @Override @@ -140,7 +143,7 @@ public class CsvCell implements Cell { @Override public String getStringCellValue() { - return null; + return value; } @Override @@ -222,4 +225,7 @@ public class CsvCell implements Cell { public boolean isPartOfArrayFormulaGroup() { return false; } + + + } diff --git a/src/main/java/com/alibaba/excel/csv/CsvRow.java b/src/main/java/com/alibaba/excel/csv/CsvRow.java index 6a979417..16129263 100644 --- a/src/main/java/com/alibaba/excel/csv/CsvRow.java +++ b/src/main/java/com/alibaba/excel/csv/CsvRow.java @@ -1,6 +1,8 @@ package com.alibaba.excel.csv; +import java.util.ArrayList; import java.util.Iterator; +import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; @@ -15,10 +17,13 @@ import org.apache.poi.ss.usermodel.Sheet; */ public class CsvRow implements Row { + public List list = new ArrayList<>(); @Override public Cell createCell(int column) { - return new CsvCell(); + CsvCell cell = new CsvCell(); + list.add(cell); + return cell; } @Override @@ -43,7 +48,7 @@ public class CsvRow implements Row { @Override public Cell getCell(int cellnum) { - return null; + return list.get(cellnum); } @Override @@ -58,7 +63,7 @@ public class CsvRow implements Row { @Override public short getLastCellNum() { - return 0; + return (short)list.size(); } @Override diff --git a/src/main/java/com/alibaba/excel/csv/CsvSheet.java b/src/main/java/com/alibaba/excel/csv/CsvSheet.java index eda6484a..db21787b 100644 --- a/src/main/java/com/alibaba/excel/csv/CsvSheet.java +++ b/src/main/java/com/alibaba/excel/csv/CsvSheet.java @@ -9,6 +9,7 @@ import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import com.alibaba.excel.util.ListUtils; @@ -668,7 +669,9 @@ public class CsvSheet implements Sheet { public void flushData() { try { - csvPrinter.printRecord(); + for (CsvRow row : rowCache) { + csvPrinter.printRecord(row.list.stream().map(CsvCell::getStringCellValue).collect(Collectors.toList())); + } } catch (IOException e) { e.printStackTrace(); } diff --git a/src/main/java/com/alibaba/excel/csv/CsvWorkbook.java b/src/main/java/com/alibaba/excel/csv/CsvWorkbook.java index 20002d83..082e770d 100644 --- a/src/main/java/com/alibaba/excel/csv/CsvWorkbook.java +++ b/src/main/java/com/alibaba/excel/csv/CsvWorkbook.java @@ -177,6 +177,7 @@ public class CsvWorkbook implements Workbook { @Override public void write(OutputStream stream) throws IOException { + csvSheet.flushData(); csvSheet.csvPrinter.flush(); csvSheet.csvPrinter.close(); } diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java index b9af89e4..6fe42448 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java @@ -23,7 +23,7 @@ public class CsvReadTest { @Test public void write() throws Exception { - Appendable out = new PrintWriter(TestFileUtil.createNewFile("csvWrite.csv")); + Appendable out = new PrintWriter(TestFileUtil.createNewFile("csvWrite1.csv")); CSVPrinter printer = CSVFormat.DEFAULT.withHeader("userId", "userName") .print(out); for (int i = 0; i < 10; i++) { From 8ded0abc5f906d2d918e88c1b359ba742a091c27 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 8 Sep 2021 18:43:50 +0800 Subject: [PATCH 091/129] =?UTF-8?q?=E5=AE=8C=E6=88=90csv=20=E4=B9=A6?= =?UTF-8?q?=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/analysis/ExcelAnalyserImpl.java | 26 ++- .../analysis/csv/CsvExcelReadExecutor.java | 112 +++++++++++++ .../excel/context/AnalysisContextImpl.java | 9 +- .../excel/context/csv/CsvReadContext.java | 26 +++ .../context/csv/DefaultCsvReadContext.java | 29 ++++ .../metadata/holder/AbstractReadHolder.java | 2 + .../read/metadata/holder/ReadSheetHolder.java | 2 + .../metadata/holder/ReadWorkbookHolder.java | 156 +----------------- .../holder/csv/CsvReadSheetHolder.java | 20 +++ .../holder/csv/CsvReadWorkbookHolder.java | 25 +++ .../easyexcel/test/temp/csv/CsvReadTest.java | 22 +++ 11 files changed, 268 insertions(+), 161 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java create mode 100644 src/main/java/com/alibaba/excel/context/csv/CsvReadContext.java create mode 100644 src/main/java/com/alibaba/excel/context/csv/DefaultCsvReadContext.java create mode 100644 src/main/java/com/alibaba/excel/read/metadata/holder/csv/CsvReadSheetHolder.java create mode 100644 src/main/java/com/alibaba/excel/read/metadata/holder/csv/CsvReadWorkbookHolder.java diff --git a/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java b/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java index e049dbfc..743daab9 100644 --- a/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java +++ b/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java @@ -3,18 +3,12 @@ package com.alibaba.excel.analysis; import java.io.InputStream; import java.util.List; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.filesystem.DocumentFactoryHelper; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import com.alibaba.excel.analysis.csv.CsvExcelReadExecutor; import com.alibaba.excel.analysis.v03.XlsSaxAnalyser; import com.alibaba.excel.analysis.v07.XlsxSaxAnalyser; import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.context.csv.CsvReadContext; +import com.alibaba.excel.context.csv.DefaultCsvReadContext; import com.alibaba.excel.context.xls.DefaultXlsReadContext; import com.alibaba.excel.context.xls.XlsReadContext; import com.alibaba.excel.context.xlsx.DefaultXlsxReadContext; @@ -32,6 +26,15 @@ import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.util.NumberDataFormatterUtils; import com.alibaba.excel.util.StringUtils; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; +import org.apache.poi.poifs.crypt.Decryptor; +import org.apache.poi.poifs.filesystem.DocumentFactoryHelper; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.util.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * @author jipengfei */ @@ -98,6 +101,11 @@ public class ExcelAnalyserImpl implements ExcelAnalyser { analysisContext = xlsxReadContext; excelReadExecutor = new XlsxSaxAnalyser(xlsxReadContext, null); break; + case CSV: + CsvReadContext csvReadContext = new DefaultCsvReadContext(readWorkbook, ExcelTypeEnum.CSV); + analysisContext = csvReadContext; + excelReadExecutor = new CsvExcelReadExecutor(csvReadContext); + break; default: break; } diff --git a/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java b/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java new file mode 100644 index 00000000..6f1353ca --- /dev/null +++ b/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java @@ -0,0 +1,112 @@ +package com.alibaba.excel.analysis.csv; + +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.alibaba.excel.analysis.ExcelReadExecutor; +import com.alibaba.excel.context.csv.CsvReadContext; +import com.alibaba.excel.enums.CellDataTypeEnum; +import com.alibaba.excel.enums.RowTypeEnum; +import com.alibaba.excel.exception.ExcelAnalysisException; +import com.alibaba.excel.metadata.Cell; +import com.alibaba.excel.metadata.data.ReadCellData; +import com.alibaba.excel.read.metadata.ReadSheet; +import com.alibaba.excel.read.metadata.holder.ReadRowHolder; +import com.alibaba.excel.read.metadata.holder.csv.CsvReadWorkbookHolder; +import com.alibaba.excel.util.SheetUtils; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVRecord; + +/** + * azz + * + * @author zhuangjiaju + */ +@Slf4j +public class CsvExcelReadExecutor implements ExcelReadExecutor { + + private List sheetList; + private CsvReadContext csvReadContext; + + public CsvExcelReadExecutor(CsvReadContext csvReadContext) { + this.csvReadContext = csvReadContext; + sheetList = new ArrayList<>(); + ReadSheet readSheet = new ReadSheet(); + sheetList.add(readSheet); + readSheet.setSheetNo(0); + } + + @Override + public List sheetList() { + return sheetList; + } + + @Override + public void execute() { + Iterable parseRecords; + try { + parseRecords = parseRecords(); + } catch (IOException e) { + throw new ExcelAnalysisException(e); + } + for (ReadSheet readSheet : sheetList) { + readSheet = SheetUtils.match(readSheet, csvReadContext); + if (readSheet == null) { + continue; + } + csvReadContext.currentSheet(readSheet); + + int rowIndex = 0; + for (CSVRecord record : parseRecords) { + + dealRecord(record, rowIndex++); + } + // The last sheet is read + csvReadContext.analysisEventProcessor().endSheet(csvReadContext); + } + } + + private Iterable parseRecords() throws IOException { + CsvReadWorkbookHolder csvReadWorkbookHolder = csvReadContext.csvReadWorkbookHolder(); + CSVFormat csvFormat = csvReadWorkbookHolder.getCsvFormat(); + + if (csvReadWorkbookHolder.getMandatoryUseInputStream()) { + return csvFormat.parse(new InputStreamReader(csvReadWorkbookHolder.getInputStream())); + } + if (csvReadWorkbookHolder.getFile() != null) { + return csvFormat.parse(new FileReader(csvReadWorkbookHolder.getFile())); + } + return csvFormat.parse(new InputStreamReader(csvReadWorkbookHolder.getInputStream())); + } + + private void dealRecord(CSVRecord record, int rowIndex) { + Map cellMap = new LinkedHashMap<>(); + Iterator cellIterator = record.iterator(); + int cellIndex = 0; + while (cellIterator.hasNext()) { + String cellString = cellIterator.next(); + ReadCellData readCellData = new ReadCellData<>(); + readCellData.setType(CellDataTypeEnum.STRING); + readCellData.setStringValue(cellString); + cellMap.put(cellIndex++, readCellData); + } + + RowTypeEnum rowType = MapUtils.isEmpty(cellMap) ? RowTypeEnum.EMPTY : RowTypeEnum.DATA; + ReadRowHolder readRowHolder = new ReadRowHolder(rowIndex, rowType, + csvReadContext.readWorkbookHolder().getGlobalConfiguration(), cellMap); + csvReadContext.readRowHolder(readRowHolder); + + csvReadContext.csvReadSheetHolder().setCellMap(cellMap); + csvReadContext.csvReadSheetHolder().setRowIndex(rowIndex); + csvReadContext.analysisEventProcessor().endRow(csvReadContext); + } +} diff --git a/src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java b/src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java index 7aeba321..4edaef37 100644 --- a/src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java @@ -10,6 +10,8 @@ import com.alibaba.excel.read.metadata.holder.ReadHolder; import com.alibaba.excel.read.metadata.holder.ReadRowHolder; import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder; +import com.alibaba.excel.read.metadata.holder.csv.CsvReadSheetHolder; +import com.alibaba.excel.read.metadata.holder.csv.CsvReadWorkbookHolder; import com.alibaba.excel.read.metadata.holder.xls.XlsReadSheetHolder; import com.alibaba.excel.read.metadata.holder.xls.XlsReadWorkbookHolder; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder; @@ -57,6 +59,9 @@ public class AnalysisContextImpl implements AnalysisContext { case XLSX: readWorkbookHolder = new XlsxReadWorkbookHolder(readWorkbook); break; + case CSV: + readWorkbookHolder = new CsvReadWorkbookHolder(readWorkbook); + break; default: break; } @@ -76,6 +81,9 @@ public class AnalysisContextImpl implements AnalysisContext { case XLSX: readSheetHolder = new XlsxReadSheetHolder(readSheet, readWorkbookHolder); break; + case CSV: + readSheetHolder = new CsvReadSheetHolder(readSheet, readWorkbookHolder); + break; default: break; } @@ -134,7 +142,6 @@ public class AnalysisContextImpl implements AnalysisContext { } - @Override public ExcelTypeEnum getExcelType() { return readWorkbookHolder.getExcelType(); diff --git a/src/main/java/com/alibaba/excel/context/csv/CsvReadContext.java b/src/main/java/com/alibaba/excel/context/csv/CsvReadContext.java new file mode 100644 index 00000000..00bcd54a --- /dev/null +++ b/src/main/java/com/alibaba/excel/context/csv/CsvReadContext.java @@ -0,0 +1,26 @@ +package com.alibaba.excel.context.csv; + +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.read.metadata.holder.csv.CsvReadSheetHolder; +import com.alibaba.excel.read.metadata.holder.csv.CsvReadWorkbookHolder; + +/** + * A context is the main anchorage point of a ls xls reader. + * + * @author Jiaju Zhuang + **/ +public interface CsvReadContext extends AnalysisContext { + /** + * All information about the workbook you are currently working on. + * + * @return Current workbook holder + */ + CsvReadWorkbookHolder csvReadWorkbookHolder(); + + /** + * All information about the sheet you are currently working on. + * + * @return Current sheet holder + */ + CsvReadSheetHolder csvReadSheetHolder(); +} diff --git a/src/main/java/com/alibaba/excel/context/csv/DefaultCsvReadContext.java b/src/main/java/com/alibaba/excel/context/csv/DefaultCsvReadContext.java new file mode 100644 index 00000000..d8653a88 --- /dev/null +++ b/src/main/java/com/alibaba/excel/context/csv/DefaultCsvReadContext.java @@ -0,0 +1,29 @@ +package com.alibaba.excel.context.csv; + +import com.alibaba.excel.context.AnalysisContextImpl; +import com.alibaba.excel.read.metadata.ReadWorkbook; +import com.alibaba.excel.read.metadata.holder.csv.CsvReadSheetHolder; +import com.alibaba.excel.read.metadata.holder.csv.CsvReadWorkbookHolder; +import com.alibaba.excel.support.ExcelTypeEnum; + +/** + * A context is the main anchorage point of a ls xls reader. + * + * @author Jiaju Zhuang + */ +public class DefaultCsvReadContext extends AnalysisContextImpl implements CsvReadContext { + + public DefaultCsvReadContext(ReadWorkbook readWorkbook, ExcelTypeEnum actualExcelType) { + super(readWorkbook, actualExcelType); + } + + @Override + public CsvReadWorkbookHolder csvReadWorkbookHolder() { + return (CsvReadWorkbookHolder)readWorkbookHolder(); + } + + @Override + public CsvReadSheetHolder csvReadSheetHolder() { + return (CsvReadSheetHolder)readSheetHolder(); + } +} diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java index 641b489f..ab6dfb72 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java @@ -16,6 +16,7 @@ import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty; import com.alibaba.excel.util.ListUtils; import lombok.Data; +import lombok.NoArgsConstructor; /** * Read Holder @@ -23,6 +24,7 @@ import lombok.Data; * @author Jiaju Zhuang */ @Data +@NoArgsConstructor public abstract class AbstractReadHolder extends AbstractHolder implements ReadHolder { /** * Count the number of added heads when read sheet. diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java index 12cd7233..73b00e71 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java @@ -10,6 +10,7 @@ import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.read.metadata.ReadSheet; import lombok.Data; +import lombok.NoArgsConstructor; /** * sheet holder @@ -17,6 +18,7 @@ import lombok.Data; * @author Jiaju Zhuang */ @Data +@NoArgsConstructor public class ReadSheetHolder extends AbstractReadHolder { /** diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java index 375e32cc..6693467f 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java @@ -19,11 +19,16 @@ import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.read.metadata.ReadWorkbook; import com.alibaba.excel.support.ExcelTypeEnum; +import lombok.Data; +import lombok.NoArgsConstructor; + /** * Workbook holder * * @author Jiaju Zhuang */ +@Data +@NoArgsConstructor public class ReadWorkbookHolder extends AbstractReadHolder { /** @@ -171,157 +176,6 @@ public class ReadWorkbookHolder extends AbstractReadHolder { this.password = readWorkbook.getPassword(); } - public ReadWorkbook getReadWorkbook() { - return readWorkbook; - } - - public void setReadWorkbook(ReadWorkbook readWorkbook) { - this.readWorkbook = readWorkbook; - } - - public InputStream getInputStream() { - return inputStream; - } - - public void setInputStream(InputStream inputStream) { - this.inputStream = inputStream; - } - - public File getFile() { - return file; - } - - public void setFile(File file) { - this.file = file; - } - - public Boolean getAutoCloseStream() { - return autoCloseStream; - } - - public void setAutoCloseStream(Boolean autoCloseStream) { - this.autoCloseStream = autoCloseStream; - } - - public ExcelTypeEnum getExcelType() { - return excelType; - } - - public void setExcelType(ExcelTypeEnum excelType) { - this.excelType = excelType; - } - - public Object getCustomObject() { - return customObject; - } - - public void setCustomObject(Object customObject) { - this.customObject = customObject; - } - - public Boolean getIgnoreEmptyRow() { - return ignoreEmptyRow; - } - - public void setIgnoreEmptyRow(Boolean ignoreEmptyRow) { - this.ignoreEmptyRow = ignoreEmptyRow; - } - - public ReadCache getReadCache() { - return readCache; - } - - public void setReadCache(ReadCache readCache) { - this.readCache = readCache; - } - - public ReadCacheSelector getReadCacheSelector() { - return readCacheSelector; - } - - public void setReadCacheSelector(ReadCacheSelector readCacheSelector) { - this.readCacheSelector = readCacheSelector; - } - - public Boolean getMandatoryUseInputStream() { - return mandatoryUseInputStream; - } - - public void setMandatoryUseInputStream(Boolean mandatoryUseInputStream) { - this.mandatoryUseInputStream = mandatoryUseInputStream; - } - - public File getTempFile() { - return tempFile; - } - - public void setTempFile(File tempFile) { - this.tempFile = tempFile; - } - - public Boolean getConvertAllFiled() { - return convertAllFiled; - } - - public void setConvertAllFiled(Boolean convertAllFiled) { - this.convertAllFiled = convertAllFiled; - } - - public Set getHasReadSheet() { - return hasReadSheet; - } - - public void setHasReadSheet(Set hasReadSheet) { - this.hasReadSheet = hasReadSheet; - } - - public Boolean getDefaultReturnMap() { - return defaultReturnMap; - } - - public void setDefaultReturnMap(Boolean defaultReturnMap) { - this.defaultReturnMap = defaultReturnMap; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public Set getExtraReadSet() { - return extraReadSet; - } - - public void setExtraReadSet(Set extraReadSet) { - this.extraReadSet = extraReadSet; - } - - public List getActualSheetDataList() { - return actualSheetDataList; - } - - public void setActualSheetDataList(List actualSheetDataList) { - this.actualSheetDataList = actualSheetDataList; - } - - public List getParameterSheetDataList() { - return parameterSheetDataList; - } - - public void setParameterSheetDataList(List parameterSheetDataList) { - this.parameterSheetDataList = parameterSheetDataList; - } - - public Boolean getReadAll() { - return readAll; - } - - public void setReadAll(Boolean readAll) { - this.readAll = readAll; - } @Override public HolderEnum holderType() { diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/csv/CsvReadSheetHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/csv/CsvReadSheetHolder.java new file mode 100644 index 00000000..d6bf6953 --- /dev/null +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/csv/CsvReadSheetHolder.java @@ -0,0 +1,20 @@ +package com.alibaba.excel.read.metadata.holder.csv; + +import com.alibaba.excel.read.metadata.ReadSheet; +import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; +import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder; + +import lombok.Data; + +/** + * sheet holder + * + * @author Jiaju Zhuang + */ +@Data +public class CsvReadSheetHolder extends ReadSheetHolder { + + public CsvReadSheetHolder(ReadSheet readSheet, ReadWorkbookHolder readWorkbookHolder) { + super(readSheet, readWorkbookHolder); + } +} diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/csv/CsvReadWorkbookHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/csv/CsvReadWorkbookHolder.java new file mode 100644 index 00000000..4e8de41f --- /dev/null +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/csv/CsvReadWorkbookHolder.java @@ -0,0 +1,25 @@ +package com.alibaba.excel.read.metadata.holder.csv; + +import com.alibaba.excel.read.metadata.ReadWorkbook; +import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder; +import com.alibaba.excel.support.ExcelTypeEnum; + +import lombok.Data; +import org.apache.commons.csv.CSVFormat; + +/** + * Workbook holder + * + * @author Jiaju Zhuang + */ +@Data +public class CsvReadWorkbookHolder extends ReadWorkbookHolder { + + private CSVFormat csvFormat; + + public CsvReadWorkbookHolder(ReadWorkbook readWorkbook) { + super(readWorkbook); + setExcelType(ExcelTypeEnum.CSV); + csvFormat = CSVFormat.DEFAULT; + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java index 6fe42448..653eafc6 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java @@ -2,6 +2,7 @@ package com.alibaba.easyexcel.test.temp.csv; import java.io.File; import java.io.FileInputStream; +import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; @@ -9,10 +10,12 @@ import java.util.List; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; +import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.CSVRecord; import org.apache.poi.poifs.filesystem.FileMagic; import org.junit.Ignore; import org.junit.Test; @@ -33,6 +36,18 @@ public class CsvReadTest { printer.close(); } + @Test + public void read1() throws Exception { + Iterable records = CSVFormat.DEFAULT.parse( + new FileReader("/Users/zhuangjiaju/IdeaProjects/easyexcel/target/test-classes/csvWrite1.csv")); + for (CSVRecord record : records) { + String lastName = record.get(0); + String firstName = record.get(1); + log.info("row:{},{}", lastName, firstName); + } + + } + @Test public void csvWrite() throws Exception { // 写法1 @@ -40,6 +55,13 @@ public class CsvReadTest { // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 // 如果这里想使用03 则 传入excelType参数即可 EasyExcel.write(fileName, CsvData.class).sheet().doWrite(data()); + + // 读 + List list = EasyExcel.read(fileName).sheet(0).headRowNumber(0).doReadSync(); + log.info("数据:{}", list.size()); + for (Object data : list) { + log.info("返回数据:{}", JSON.toJSONString(data)); + } } @Test From d475f98b93133180004e8c347a1f3e495a6a4dd3 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 10 Sep 2021 14:31:38 +0800 Subject: [PATCH 092/129] =?UTF-8?q?=E5=AE=8C=E6=88=90=E9=83=A8=E5=88=86csv?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/constant/BuiltinFormats.java | 24 +- .../java/com/alibaba/excel/csv/CsvCell.java | 231 -------------- .../com/alibaba/excel/csv/CsvDataFormat.java | 15 - .../alibaba/excel/metadata/csv/CsvCell.java | 291 ++++++++++++++++++ .../{ => metadata}/csv/CsvCellStyle.java | 21 +- .../excel/metadata/csv/CsvDataFormat.java | 65 ++++ .../excel/metadata/csv/CsvRichTextString.java | 68 ++++ .../excel/{ => metadata}/csv/CsvRow.java | 73 +++-- .../excel/{ => metadata}/csv/CsvSheet.java | 146 +++++++-- .../excel/{ => metadata}/csv/CsvWorkbook.java | 71 +++-- .../com/alibaba/excel/util/WorkBookUtil.java | 15 +- .../metadata/holder/WriteWorkbookHolder.java | 18 +- .../core/annotation/AnnotationDataTest.java | 16 +- 13 files changed, 718 insertions(+), 336 deletions(-) delete mode 100644 src/main/java/com/alibaba/excel/csv/CsvCell.java delete mode 100644 src/main/java/com/alibaba/excel/csv/CsvDataFormat.java create mode 100644 src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java rename src/main/java/com/alibaba/excel/{ => metadata}/csv/CsvCellStyle.java (93%) create mode 100644 src/main/java/com/alibaba/excel/metadata/csv/CsvDataFormat.java create mode 100644 src/main/java/com/alibaba/excel/metadata/csv/CsvRichTextString.java rename src/main/java/com/alibaba/excel/{ => metadata}/csv/CsvRow.java (59%) rename src/main/java/com/alibaba/excel/{ => metadata}/csv/CsvSheet.java (77%) rename src/main/java/com/alibaba/excel/{ => metadata}/csv/CsvWorkbook.java (80%) diff --git a/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java b/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java index b742cb6c..ec7d5c9a 100644 --- a/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java +++ b/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java @@ -1,6 +1,9 @@ package com.alibaba.excel.constant; import java.util.Locale; +import java.util.Map; + +import com.alibaba.excel.util.MapUtils; /** * Excel's built-in format conversion.Currently only supports Chinese. @@ -363,6 +366,10 @@ public class BuiltinFormats { // end }; + public static final Map BUILTIN_FORMATS_MAP_CN = buildMap(BUILTIN_FORMATS_CN); + public static final Map BUILTIN_FORMATS_MAP_US = buildMap(BUILTIN_FORMATS_US); + public static final short MIN_CUSTOM_DATA_FORMAT_INDEX = 82; + public static String getBuiltinFormat(Short index, String defaultFormat, Locale locale) { String[] builtinFormat = switchBuiltinFormats(locale); if (index == null || index < 0 || index >= builtinFormat.length) { @@ -371,11 +378,26 @@ public class BuiltinFormats { return builtinFormat[index]; } - private static String[] switchBuiltinFormats(Locale locale) { + public static String[] switchBuiltinFormats(Locale locale) { if (locale != null && Locale.US.getCountry().equals(locale.getCountry())) { return BUILTIN_FORMATS_US; } return BUILTIN_FORMATS_CN; } + public static Map switchBuiltinFormatsMap(Locale locale) { + if (locale != null && Locale.US.getCountry().equals(locale.getCountry())) { + return BUILTIN_FORMATS_MAP_US; + } + return BUILTIN_FORMATS_MAP_CN; + } + + private static Map buildMap(String[] builtinFormats) { + Map map = MapUtils.newHashMapWithExpectedSize(builtinFormats.length); + for (int i = 0; i < builtinFormats.length; i++) { + map.put(builtinFormats[i], (short)i); + } + return map; + } + } diff --git a/src/main/java/com/alibaba/excel/csv/CsvCell.java b/src/main/java/com/alibaba/excel/csv/CsvCell.java deleted file mode 100644 index 84808bf0..00000000 --- a/src/main/java/com/alibaba/excel/csv/CsvCell.java +++ /dev/null @@ -1,231 +0,0 @@ -package com.alibaba.excel.csv; - -import java.time.LocalDateTime; -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; - -/** - * TODO - * - * @author Jiaju Zhuang - */ -public class CsvCell implements Cell { - - private String value; - - @Override - public int getColumnIndex() { - return 0; - } - - @Override - public int getRowIndex() { - return 0; - } - - @Override - public Sheet getSheet() { - return null; - } - - @Override - public Row getRow() { - return null; - } - - @Override - public void setCellType(CellType cellType) { - - } - - @Override - public void setBlank() { - - } - - @Override - public CellType getCellType() { - return null; - } - - @Override - public CellType getCellTypeEnum() { - return null; - } - - @Override - public CellType getCachedFormulaResultType() { - return null; - } - - @Override - public CellType getCachedFormulaResultTypeEnum() { - return null; - } - - @Override - public void setCellValue(double value) { - this.value = value + ""; - } - - @Override - public void setCellValue(Date value) { - this.value = value.toString(); - - } - - @Override - public void setCellValue(LocalDateTime value) { - - } - - @Override - public void setCellValue(Calendar value) { - - } - - @Override - public void setCellValue(RichTextString value) { - - } - - @Override - public void setCellValue(String value) { - this.value = value; - } - - @Override - public void setCellFormula(String formula) throws FormulaParseException, IllegalStateException { - - } - - @Override - public void removeFormula() throws IllegalStateException { - - } - - @Override - public String getCellFormula() { - return null; - } - - @Override - public double getNumericCellValue() { - return 0; - } - - @Override - public Date getDateCellValue() { - return null; - } - - @Override - public LocalDateTime getLocalDateTimeCellValue() { - return null; - } - - @Override - public RichTextString getRichStringCellValue() { - return null; - } - - @Override - public String getStringCellValue() { - return value; - } - - @Override - public void setCellValue(boolean value) { - - } - - @Override - public void setCellErrorValue(byte value) { - - } - - @Override - public boolean getBooleanCellValue() { - return false; - } - - @Override - public byte getErrorCellValue() { - return 0; - } - - @Override - public void setCellStyle(CellStyle style) { - - } - - @Override - public CellStyle getCellStyle() { - return null; - } - - @Override - public void setAsActiveCell() { - - } - - @Override - public CellAddress getAddress() { - return null; - } - - @Override - public void setCellComment(Comment comment) { - - } - - @Override - public Comment getCellComment() { - return null; - } - - @Override - public void removeCellComment() { - - } - - @Override - public Hyperlink getHyperlink() { - return null; - } - - @Override - public void setHyperlink(Hyperlink link) { - - } - - @Override - public void removeHyperlink() { - - } - - @Override - public CellRangeAddress getArrayFormulaRange() { - return null; - } - - @Override - public boolean isPartOfArrayFormulaGroup() { - return false; - } - - - -} diff --git a/src/main/java/com/alibaba/excel/csv/CsvDataFormat.java b/src/main/java/com/alibaba/excel/csv/CsvDataFormat.java deleted file mode 100644 index 2961fbf1..00000000 --- a/src/main/java/com/alibaba/excel/csv/CsvDataFormat.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.alibaba.excel.csv; - -import org.apache.poi.ss.usermodel.DataFormat; - -public class CsvDataFormat implements DataFormat { - @Override - public short getFormat(String format) { - return 0; - } - - @Override - public String getFormat(short index) { - return null; - } -} diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java new file mode 100644 index 00000000..ef627392 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java @@ -0,0 +1,291 @@ +package com.alibaba.excel.metadata.csv; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Calendar; +import java.util.Date; + +import com.alibaba.excel.metadata.data.FormulaData; + +import org.apache.poi.ss.SpreadsheetVersion; +import org.apache.poi.ss.usermodel.CellBase; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Comment; +import org.apache.poi.ss.usermodel.Hyperlink; +import org.apache.poi.ss.usermodel.RichTextString; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.util.CellRangeAddress; + +/** + * csv cell + * + * @author Jiaju Zhuang + */ +public class CsvCell extends CellBase { + + /** + * column index + */ + private Integer columnIndex; + + /** + * cell type + */ + private CellType cellType; + /** + * row + */ + private final CsvRow csvRow; + + /** + * {@link CellType#NUMERIC} + */ + private BigDecimal numberValue; + /** + * {@link CellType#STRING} and {@link CellType#ERROR} {@link CellType#FORMULA} + */ + private String stringValue; + /** + * {@link CellType#BOOLEAN} + */ + private Boolean booleanValue; + + /** + * {@link CellType#NUMERIC} + */ + private LocalDateTime dateValue; + + /** + * formula + */ + private FormulaData formulaData; + + /** + * rich text string + */ + private RichTextString richTextString; + + /** + * style + */ + private CellStyle cellStyle; + + public CsvCell(CsvRow csvRow, Integer columnIndex, CellType cellType) { + this.csvRow = csvRow; + this.columnIndex = columnIndex; + this.cellType = cellType; + } + + @Override + protected void setCellTypeImpl(CellType cellType) { + this.cellType = cellType; + } + + @Override + protected void setCellFormulaImpl(String formula) { + FormulaData formulaData = new FormulaData(); + formulaData.setFormulaValue(formula); + this.formulaData = formulaData; + } + + @Override + protected void removeFormulaImpl() { + this.formulaData = null; + } + + @Override + protected void setCellValueImpl(double value) { + numberValue = BigDecimal.valueOf(value); + } + + @Override + protected void setCellValueImpl(Date value) { + if (value == null) { + return; + } + this.dateValue = LocalDateTime.ofInstant(value.toInstant(), ZoneId.systemDefault()); + } + + @Override + protected void setCellValueImpl(LocalDateTime value) { + this.dateValue = value; + } + + @Override + protected void setCellValueImpl(Calendar value) { + if (value == null) { + return; + } + this.dateValue = LocalDateTime.ofInstant(value.toInstant(), ZoneId.systemDefault()); + } + + @Override + protected void setCellValueImpl(String value) { + this.stringValue = value; + } + + @Override + protected void setCellValueImpl(RichTextString value) { + richTextString = value; + } + + @Override + protected SpreadsheetVersion getSpreadsheetVersion() { + return null; + } + + @Override + public int getColumnIndex() { + return columnIndex; + } + + @Override + public int getRowIndex() { + return csvRow.getRowNum(); + } + + @Override + public Sheet getSheet() { + return csvRow.getSheet(); + } + + @Override + public Row getRow() { + return csvRow; + } + + @Override + public CellType getCellType() { + return cellType; + } + + @Override + public CellType getCachedFormulaResultType() { + return getCellType(); + } + + @Override + public CellType getCachedFormulaResultTypeEnum() { + return getCellType(); + } + + @Override + public String getCellFormula() { + if (formulaData == null) { + return null; + } + return formulaData.getFormulaValue(); + } + + @Override + public double getNumericCellValue() { + if (numberValue == null) { + return 0; + } + return numberValue.doubleValue(); + } + + @Override + public Date getDateCellValue() { + if (dateValue == null) { + return null; + } + return Date.from(dateValue.atZone(ZoneId.systemDefault()).toInstant()); + } + + @Override + public LocalDateTime getLocalDateTimeCellValue() { + return dateValue; + } + + @Override + public RichTextString getRichStringCellValue() { + return richTextString; + } + + @Override + public String getStringCellValue() { + return stringValue; + } + + @Override + public void setCellValue(boolean value) { + this.booleanValue = value; + } + + @Override + public void setCellErrorValue(byte value) { + this.numberValue = BigDecimal.valueOf(value); + } + + @Override + public boolean getBooleanCellValue() { + return booleanValue; + } + + @Override + public byte getErrorCellValue() { + if (numberValue == null) { + return 0; + } + return numberValue.byteValue(); + } + + @Override + public void setCellStyle(CellStyle style) { + this.cellStyle = style; + } + + @Override + public CellStyle getCellStyle() { + return cellStyle; + } + + @Override + public void setAsActiveCell() { + + } + + @Override + public void setCellComment(Comment comment) { + + } + + @Override + public Comment getCellComment() { + return null; + } + + @Override + public void removeCellComment() { + + } + + @Override + public Hyperlink getHyperlink() { + return null; + } + + @Override + public void setHyperlink(Hyperlink link) { + + } + + @Override + public void removeHyperlink() { + + } + + @Override + public CellRangeAddress getArrayFormulaRange() { + return null; + } + + @Override + public boolean isPartOfArrayFormulaGroup() { + return false; + } +} diff --git a/src/main/java/com/alibaba/excel/csv/CsvCellStyle.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java similarity index 93% rename from src/main/java/com/alibaba/excel/csv/CsvCellStyle.java rename to src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java index 318b42a4..8c8fe981 100644 --- a/src/main/java/com/alibaba/excel/csv/CsvCellStyle.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java @@ -1,4 +1,6 @@ -package com.alibaba.excel.csv; +package com.alibaba.excel.metadata.csv; + +import com.alibaba.excel.metadata.data.DataFormatData; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.CellStyle; @@ -9,11 +11,26 @@ import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.VerticalAlignment; /** - * TODO + * csv cell style * * @author Jiaju Zhuang */ public class CsvCellStyle implements CellStyle { + + /** + * data format + */ + private DataFormatData dataFormatData; + + /** + * index + */ + private Short index; + + public CsvCellStyle(Short index) { + this.index = index; + } + @Override public short getIndex() { return 0; diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvDataFormat.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvDataFormat.java new file mode 100644 index 00000000..1dcc7c2e --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvDataFormat.java @@ -0,0 +1,65 @@ +package com.alibaba.excel.metadata.csv; + +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import com.alibaba.excel.constant.BuiltinFormats; +import com.alibaba.excel.util.ListUtils; +import com.alibaba.excel.util.MapUtils; + +import org.apache.poi.ss.usermodel.DataFormat; + +/** + * format data + * + * @author Jiaju Zhuang + */ +public class CsvDataFormat implements DataFormat { + /** + * It is stored in both map and list for easy retrieval + */ + private final Map formatMap; + private final List formatList; + + /** + * Excel's built-in format conversion. + */ + private final Map builtinFormatsMap; + private final String[] builtinFormats; + + public CsvDataFormat(Locale locale) { + formatMap = MapUtils.newHashMap(); + formatList = ListUtils.newArrayList(); + builtinFormatsMap = BuiltinFormats.switchBuiltinFormatsMap(locale); + builtinFormats = BuiltinFormats.switchBuiltinFormats(locale); + } + + @Override + public short getFormat(String format) { + Short index = builtinFormatsMap.get(format); + if (index != null) { + return index; + } + index = formatMap.get(format); + if (index != null) { + return index; + } + formatList.add(format); + index = (short)formatList.size(); + formatMap.put(format, index); + return index; + } + + @Override + public String getFormat(short index) { + if (index < BuiltinFormats.MIN_CUSTOM_DATA_FORMAT_INDEX) { + return builtinFormats[index]; + } + int actualIndex = index - BuiltinFormats.MIN_CUSTOM_DATA_FORMAT_INDEX; + if (actualIndex >= 0 && actualIndex < formatList.size()) { + return formatList.get(actualIndex); + } + return null; + } +} diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvRichTextString.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvRichTextString.java new file mode 100644 index 00000000..1c54b0c3 --- /dev/null +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvRichTextString.java @@ -0,0 +1,68 @@ +package com.alibaba.excel.metadata.csv; + +import org.apache.poi.ss.usermodel.Font; +import org.apache.poi.ss.usermodel.RichTextString; + +/** + * rich text string + * + * @author Jiaju Zhuang + */ +public class CsvRichTextString implements RichTextString { + /** + * string + */ + private final String string; + + public CsvRichTextString(String string) { + this.string = string; + } + + @Override + public void applyFont(int startIndex, int endIndex, short fontIndex) { + + } + + @Override + public void applyFont(int startIndex, int endIndex, Font font) { + + } + + @Override + public void applyFont(Font font) { + + } + + @Override + public void clearFormatting() { + + } + + @Override + public String getString() { + return string; + } + + @Override + public int length() { + if (string == null) { + return 0; + } + return string.length(); + } + + @Override + public int numFormattingRuns() { + return 0; + } + + @Override + public int getIndexOfFormattingRun(int index) { + return 0; + } + + @Override + public void applyFont(short fontIndex) { + + } +} diff --git a/src/main/java/com/alibaba/excel/csv/CsvRow.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java similarity index 59% rename from src/main/java/com/alibaba/excel/csv/CsvRow.java rename to src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java index 16129263..d7248313 100644 --- a/src/main/java/com/alibaba/excel/csv/CsvRow.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java @@ -1,9 +1,10 @@ -package com.alibaba.excel.csv; +package com.alibaba.excel.metadata.csv; -import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.compress.utils.Lists; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; @@ -11,64 +12,98 @@ import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; /** - * TODO + * csv row * * @author Jiaju Zhuang */ public class CsvRow implements Row { - public List list = new ArrayList<>(); + /** + * cell list + */ + private final List cellList; + + /** + * sheet + */ + private final CsvSheet csvSheet; + /** + * row index + */ + private Integer rowIndex; + + /** + * style + */ + private CellStyle cellStyle; + + public CsvRow(CsvSheet csvSheet, Integer rowIndex) { + cellList = Lists.newArrayList(); + this.csvSheet = csvSheet; + this.rowIndex = rowIndex; + } @Override public Cell createCell(int column) { - CsvCell cell = new CsvCell(); - list.add(cell); + CsvCell cell = new CsvCell(this, column, null); + cellList.add(cell); return cell; } @Override public Cell createCell(int column, CellType type) { - return null; + CsvCell cell = new CsvCell(this, column, type); + cellList.add(cell); + return cell; } @Override public void removeCell(Cell cell) { - + cellList.remove(cell); } @Override public void setRowNum(int rowNum) { - + this.rowIndex = rowNum; } @Override public int getRowNum() { - return 0; + return rowIndex; } @Override public Cell getCell(int cellnum) { - return list.get(cellnum); + if (cellnum >= cellList.size()) { + return null; + } + return cellList.get(cellnum - 1); } @Override public Cell getCell(int cellnum, MissingCellPolicy policy) { - return null; + return getCell(cellnum); } @Override public short getFirstCellNum() { + if (CollectionUtils.isEmpty(cellList)) { + return -1; + } return 0; } @Override public short getLastCellNum() { - return (short)list.size(); + if (CollectionUtils.isEmpty(cellList)) { + return -1; + } + return (short)cellList.size(); } @Override public int getPhysicalNumberOfCells() { - return 0; + return getRowNum(); } @Override @@ -108,22 +143,22 @@ public class CsvRow implements Row { @Override public CellStyle getRowStyle() { - return null; + return cellStyle; } @Override public void setRowStyle(CellStyle style) { - + this.cellStyle = style; } @Override public Iterator cellIterator() { - return null; + return (Iterator)(Iterator)cellList.iterator(); } @Override public Sheet getSheet() { - return null; + return csvSheet; } @Override @@ -143,6 +178,6 @@ public class CsvRow implements Row { @Override public Iterator iterator() { - return null; + return cellIterator(); } } diff --git a/src/main/java/com/alibaba/excel/csv/CsvSheet.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java similarity index 77% rename from src/main/java/com/alibaba/excel/csv/CsvSheet.java rename to src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java index db21787b..07f09e73 100644 --- a/src/main/java/com/alibaba/excel/csv/CsvSheet.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java @@ -1,6 +1,9 @@ -package com.alibaba.excel.csv; +package com.alibaba.excel.metadata.csv; +import java.io.Closeable; import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; @@ -9,10 +12,11 @@ import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; +import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.util.ListUtils; +import lombok.Data; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.poi.ss.usermodel.AutoFilter; @@ -36,62 +40,122 @@ import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.PaneInformation; /** - * TODO + * csv sheet * * @author Jiaju Zhuang */ -public class CsvSheet implements Sheet { - - public static int rowCacheCount = 500; - public static Charset defaultCharset = Charset.defaultCharset(); - - public CSVPrinter csvPrinter; - - private int lastRowNum = -1; - - private List rowCache = ListUtils.newArrayListWithExpectedSize(rowCacheCount); - - public CsvSheet(File file) throws IOException { - csvPrinter = CSVFormat.DEFAULT.print(file, defaultCharset); - } - - public CsvSheet(OutputStream outputStream) throws IOException { - csvPrinter = CSVFormat.DEFAULT.print(new OutputStreamWriter(outputStream)); +@Data +public class CsvSheet implements Sheet, Closeable { + + /** + * workbook + */ + private CsvWorkbook csvWorkbook; + /** + * output + */ + private Appendable out; + /** + * row cache + */ + private Integer rowCacheCount; + /** + * format + */ + public CSVFormat csvFormat; + + /** + * last row index + */ + private int lastRowIndex; + /** + * row cache + */ + private List rowCache; + /** + * csv printer + */ + private CSVPrinter csvPrinter; + + public CsvSheet(CsvWorkbook csvWorkbook, File file, Charset charset) throws FileNotFoundException { + this.csvWorkbook = csvWorkbook; + this.out = new OutputStreamWriter(new FileOutputStream(file), charset); + this.rowCacheCount = 500; + this.csvFormat = CSVFormat.DEFAULT; + this.lastRowIndex = -1; + } + + public CsvSheet(CsvWorkbook csvWorkbook, OutputStream outputStream) { + this.csvWorkbook = csvWorkbook; + this.out = new OutputStreamWriter(outputStream); + this.rowCacheCount = 500; + this.csvFormat = CSVFormat.DEFAULT; + this.lastRowIndex = -1; + } + + public CsvSheet(CsvWorkbook csvWorkbook, Appendable out) { + this.csvWorkbook = csvWorkbook; + this.out = out; + this.rowCacheCount = 500; + this.csvFormat = CSVFormat.DEFAULT; + this.lastRowIndex = -1; } @Override public Row createRow(int rownum) { - lastRowNum++; - assert rownum == lastRowNum : "csv create row must be in order."; + // Initialize the data when the row is first created + initSheet(); + + lastRowIndex++; + assert rownum == lastRowIndex : "csv create row must be in order."; printData(); - CsvRow csvRow = new CsvRow(); + CsvRow csvRow = new CsvRow(this, rownum); rowCache.add(csvRow); return csvRow; } + private void initSheet() { + if (csvPrinter != null) { + return; + } + rowCache = ListUtils.newArrayListWithExpectedSize(rowCacheCount); + try { + csvPrinter = csvFormat.print(out); + } catch (IOException e) { + throw new ExcelGenerateException(e); + } + } + @Override public void removeRow(Row row) { - + throw new UnsupportedOperationException("csv cannot move row."); } @Override public Row getRow(int rownum) { - return null; + int actualRowIndex = rownum - (lastRowIndex - rowCache.size()) - 1; + if (actualRowIndex < 0 || actualRowIndex > rowCache.size() - 1) { + throw new UnsupportedOperationException("The current data does not exist or has been flushed to disk\n."); + } + return rowCache.get(actualRowIndex); } @Override public int getPhysicalNumberOfRows() { - return 0; + return lastRowIndex - rowCache.size(); } @Override public int getFirstRowNum() { + if (lastRowIndex < 0) { + return -1; + } return 0; } @Override public int getLastRowNum() { - return 0; + return lastRowIndex; } @Override @@ -226,7 +290,7 @@ public class CsvSheet implements Sheet { @Override public Iterator rowIterator() { - return null; + return (Iterator)(Iterator)rowCache.iterator(); } @Override @@ -556,7 +620,7 @@ public class CsvSheet implements Sheet { @Override public Workbook getWorkbook() { - return null; + return csvWorkbook; } @Override @@ -657,23 +721,39 @@ public class CsvSheet implements Sheet { @Override public Iterator iterator() { - return null; + return rowIterator(); + } + + @Override + public void close() throws IOException { + // Avoid empty sheets + initSheet(); + + flushData(); + csvPrinter.flush(); + csvPrinter.close(); } public void printData() { if (rowCache.size() >= rowCacheCount) { flushData(); - rowCache.clear(); } } public void flushData() { try { for (CsvRow row : rowCache) { - csvPrinter.printRecord(row.list.stream().map(CsvCell::getStringCellValue).collect(Collectors.toList())); + Iterator cellIterator = row.cellIterator(); + while (cellIterator.hasNext()) { + CsvCell csvCell = (CsvCell)cellIterator.next(); + csvPrinter.print(csvCell.getStringCellValue()); + } + csvPrinter.println(); } + rowCache.clear(); } catch (IOException e) { - e.printStackTrace(); + throw new ExcelGenerateException(e); } } + } diff --git a/src/main/java/com/alibaba/excel/csv/CsvWorkbook.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java similarity index 80% rename from src/main/java/com/alibaba/excel/csv/CsvWorkbook.java rename to src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java index 082e770d..ae8a3e50 100644 --- a/src/main/java/com/alibaba/excel/csv/CsvWorkbook.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java @@ -1,13 +1,13 @@ -package com.alibaba.excel.csv; +package com.alibaba.excel.metadata.csv; -import java.io.File; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.List; +import java.util.Locale; import lombok.Data; +import org.apache.commons.compress.utils.Lists; import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.formula.udf.UDFFinder; import org.apache.poi.ss.usermodel.CellStyle; @@ -22,21 +22,37 @@ import org.apache.poi.ss.usermodel.SheetVisibility; import org.apache.poi.ss.usermodel.Workbook; /** - * TODO + * csv workbook * * @author Jiaju Zhuang */ @Data public class CsvWorkbook implements Workbook { - + /** + * output + */ + private Appendable out; + /** + * locale + */ + private Locale locale; + + /** + * data format + */ + private CsvDataFormat csvDataFormat; + /** + * sheet + */ private CsvSheet csvSheet; + /** + * cell style + */ + private List csvCellStyleList; - public CsvWorkbook(InputStream inputStream, File file) { - try { - this.csvSheet = new CsvSheet(file); - } catch (IOException e) { - e.printStackTrace(); - } + public CsvWorkbook(Appendable out, Locale locale) { + this.out = out; + this.locale = locale; } @Override @@ -91,11 +107,15 @@ public class CsvWorkbook implements Workbook { @Override public Sheet createSheet() { + assert csvSheet == null : "CSV repeat creation is not allowed."; + csvSheet = new CsvSheet(this, out); return csvSheet; } @Override public Sheet createSheet(String sheetname) { + assert csvSheet == null : "CSV repeat creation is not allowed."; + csvSheet = new CsvSheet(this, out); return csvSheet; } @@ -116,12 +136,13 @@ public class CsvWorkbook implements Workbook { @Override public Sheet getSheetAt(int index) { - return null; + assert index == 0 : "CSV exists only in one sheet."; + return csvSheet; } @Override public Sheet getSheet(String name) { - return null; + return csvSheet; } @Override @@ -162,24 +183,30 @@ public class CsvWorkbook implements Workbook { @Override public CellStyle createCellStyle() { - return new CsvCellStyle(); + if (csvCellStyleList == null) { + csvCellStyleList = Lists.newArrayList(); + } + CsvCellStyle csvCellStyle = new CsvCellStyle((short)csvCellStyleList.size()); + csvCellStyleList.add(csvCellStyle); + return csvCellStyle; } @Override public int getNumCellStyles() { - return 0; + return csvCellStyleList.size(); } @Override public CellStyle getCellStyleAt(int idx) { - return null; + if (idx < 0 || idx >= csvCellStyleList.size()) { + return null; + } + return csvCellStyleList.get(idx); } @Override public void write(OutputStream stream) throws IOException { - csvSheet.flushData(); - csvSheet.csvPrinter.flush(); - csvSheet.csvPrinter.close(); + csvSheet.close(); } @Override @@ -274,7 +301,11 @@ public class CsvWorkbook implements Workbook { @Override public DataFormat createDataFormat() { - return new CsvDataFormat(); + if (csvDataFormat != null) { + return csvDataFormat; + } + csvDataFormat = new CsvDataFormat(locale); + return csvDataFormat; } @Override diff --git a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java index 0760e895..3fb6575e 100644 --- a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java +++ b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java @@ -1,8 +1,10 @@ package com.alibaba.excel.util; +import java.io.FileOutputStream; import java.io.IOException; +import java.io.OutputStreamWriter; -import com.alibaba.excel.csv.CsvWorkbook; +import com.alibaba.excel.metadata.csv.CsvWorkbook; import com.alibaba.excel.metadata.data.DataFormatData; import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; @@ -67,12 +69,15 @@ public class WorkBookUtil { return; case CSV: CsvWorkbook csvWorkbook; - if (writeWorkbookHolder.getTempTemplateInputStream() != null) { - csvWorkbook = new CsvWorkbook(writeWorkbookHolder.getTempTemplateInputStream(), - writeWorkbookHolder.getFile()); + if (writeWorkbookHolder.getFile() != null) { + csvWorkbook = new CsvWorkbook( + new OutputStreamWriter(new FileOutputStream(writeWorkbookHolder.getFile()), + writeWorkbookHolder.getFileCharset()), + writeWorkbookHolder.getGlobalConfiguration().getLocale()); } else { - csvWorkbook = new CsvWorkbook(null, writeWorkbookHolder.getFile()); + csvWorkbook = new CsvWorkbook(null, writeWorkbookHolder.getGlobalConfiguration().getLocale()); } + CsvWorkbook csvWorkbook = new CsvWorkbook(writeWorkbookHolder); writeWorkbookHolder.setCachedWorkbook(csvWorkbook); writeWorkbookHolder.setWorkbook(csvWorkbook); return; diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java index a2a0d113..cb29ec22 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java @@ -7,6 +7,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; @@ -64,6 +65,10 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { * If 'outputStream' and 'file' all not empty,file first */ private File file; + /** + * charset of final output file + */ + private Charset fileCharset; /** * Final output stream */ @@ -152,11 +157,6 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { } else { this.autoCloseStream = writeWorkbook.getAutoCloseStream(); } - try { - copyTemplate(); - } catch (IOException e) { - throw new ExcelGenerateException("Copy template failure.", e); - } if (writeWorkbook.getExcelType() == null) { boolean isXls = (file != null && file.getName().endsWith(ExcelTypeEnum.XLS.getValue())) || (writeWorkbook.getTemplateFile() != null @@ -176,6 +176,11 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { } else { this.excelType = writeWorkbook.getExcelType(); } + try { + copyTemplate(); + } catch (IOException e) { + throw new ExcelGenerateException("Copy template failure.", e); + } if (writeWorkbook.getMandatoryUseInputStream() == null) { this.mandatoryUseInputStream = Boolean.FALSE; } else { @@ -203,6 +208,9 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { if (writeWorkbook.getTemplateFile() == null && writeWorkbook.getTemplateInputStream() == null) { return; } + if (this.excelType == ExcelTypeEnum.CSV) { + throw new ExcelGenerateException("csv cannot use template."); + } byte[] templateFileByte = null; if (writeWorkbook.getTemplateFile() != null) { templateFileByte = FileUtils.readFileToByteArray(writeWorkbook.getTemplateFile()); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java index 4489f1c1..54fa2700 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java @@ -4,26 +4,27 @@ import java.io.File; 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.util.DateUtils; +import org.junit.BeforeClass; +import org.junit.Test; + /** - * * @author Jiaju Zhuang */ public class AnnotationDataTest { private static File file07; private static File file03; + private static File fileCsv; @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("annotation07.xlsx"); file03 = TestFileUtil.createNewFile("annotation03.xls"); + fileCsv = TestFileUtil.createNewFile("annotation.csv"); } @Test @@ -36,6 +37,11 @@ public class AnnotationDataTest { readAndWrite(file03); } + @Test + public void t02ReadAndWriteCsv() throws Exception { + readAndWrite(fileCsv); + } + private void readAndWrite(File file) throws Exception { EasyExcel.write().file(file).head(AnnotationData.class).sheet().doWrite(data()); EasyExcel.read().file(file).head(AnnotationData.class).registerReadListener(new AnnotationDataListener()) @@ -43,7 +49,7 @@ public class AnnotationDataTest { } private List data() throws Exception { - List list = new ArrayList(); + List list = new ArrayList<>(); AnnotationData data = new AnnotationData(); data.setDate(DateUtils.parseDate("2020-01-01 01:01:01")); data.setNumber(99.99); From fd000d51ce0c5ac01cc37fd4fd65ad5797e0144d Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 10 Sep 2021 15:22:09 +0800 Subject: [PATCH 093/129] =?UTF-8?q?=E5=AE=8C=E6=88=90csv=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/excel/metadata/csv/CsvCell.java | 27 +++++++++++++++++++ .../excel/metadata/csv/CsvCellStyle.java | 17 +++++++++--- .../alibaba/excel/metadata/csv/CsvRow.java | 2 ++ .../alibaba/excel/metadata/csv/CsvSheet.java | 22 --------------- .../excel/metadata/data/DataFormatData.java | 4 +++ .../com/alibaba/excel/util/WorkBookUtil.java | 14 +++------- .../excel/write/metadata/WriteWorkbook.java | 5 ++++ .../metadata/holder/WriteWorkbookHolder.java | 15 ++++++++--- 8 files changed, 66 insertions(+), 40 deletions(-) diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java index ef627392..4898ff2c 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java @@ -8,6 +8,10 @@ import java.util.Date; import com.alibaba.excel.metadata.data.FormulaData; +import lombok.AccessLevel; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.usermodel.CellBase; import org.apache.poi.ss.usermodel.CellStyle; @@ -24,16 +28,21 @@ import org.apache.poi.ss.util.CellRangeAddress; * * @author Jiaju Zhuang */ +@Data public class CsvCell extends CellBase { /** * column index */ + @Getter(value = AccessLevel.NONE) + @Setter(value = AccessLevel.NONE) private Integer columnIndex; /** * cell type */ + @Getter(value = AccessLevel.NONE) + @Setter(value = AccessLevel.NONE) private CellType cellType; /** * row @@ -132,6 +141,24 @@ public class CsvCell extends CellBase { richTextString = value; } + @Override + public void setCellValue(String value) { + if (value == null) { + setBlank(); + return; + } + setCellValueImpl(value); + } + + @Override + public void setCellValue(RichTextString value) { + if (value == null || value.getString() == null) { + setBlank(); + return; + } + setCellValueImpl(value); + } + @Override protected SpreadsheetVersion getSpreadsheetVersion() { return null; diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java index 8c8fe981..ca153e45 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java @@ -2,6 +2,7 @@ package com.alibaba.excel.metadata.csv; import com.alibaba.excel.metadata.data.DataFormatData; +import lombok.Data; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Color; @@ -15,6 +16,7 @@ import org.apache.poi.ss.usermodel.VerticalAlignment; * * @author Jiaju Zhuang */ +@Data public class CsvCellStyle implements CellStyle { /** @@ -33,22 +35,31 @@ public class CsvCellStyle implements CellStyle { @Override public short getIndex() { - return 0; + return index; } @Override public void setDataFormat(short fmt) { + initDataFormatData(); + dataFormatData.setIndex(fmt); + } + private void initDataFormatData() { + if (dataFormatData == null) { + dataFormatData = new DataFormatData(); + } } @Override public short getDataFormat() { - return 0; + initDataFormatData(); + return dataFormatData.getIndex(); } @Override public String getDataFormatString() { - return null; + initDataFormatData(); + return dataFormatData.getFormat(); } @Override diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java index d7248313..0550e611 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java @@ -3,6 +3,7 @@ package com.alibaba.excel.metadata.csv; import java.util.Iterator; import java.util.List; +import lombok.Data; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.compress.utils.Lists; import org.apache.poi.ss.usermodel.Cell; @@ -16,6 +17,7 @@ import org.apache.poi.ss.usermodel.Sheet; * * @author Jiaju Zhuang */ +@Data public class CsvRow implements Row { /** diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java index 07f09e73..fa83fd47 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java @@ -1,13 +1,7 @@ package com.alibaba.excel.metadata.csv; import java.io.Closeable; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.nio.charset.Charset; import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -77,22 +71,6 @@ public class CsvSheet implements Sheet, Closeable { */ private CSVPrinter csvPrinter; - public CsvSheet(CsvWorkbook csvWorkbook, File file, Charset charset) throws FileNotFoundException { - this.csvWorkbook = csvWorkbook; - this.out = new OutputStreamWriter(new FileOutputStream(file), charset); - this.rowCacheCount = 500; - this.csvFormat = CSVFormat.DEFAULT; - this.lastRowIndex = -1; - } - - public CsvSheet(CsvWorkbook csvWorkbook, OutputStream outputStream) { - this.csvWorkbook = csvWorkbook; - this.out = new OutputStreamWriter(outputStream); - this.rowCacheCount = 500; - this.csvFormat = CSVFormat.DEFAULT; - this.lastRowIndex = -1; - } - public CsvSheet(CsvWorkbook csvWorkbook, Appendable out) { this.csvWorkbook = csvWorkbook; this.out = out; diff --git a/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java b/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java index 7f1a14c8..2cbcb42c 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java +++ b/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java @@ -19,6 +19,10 @@ public class DataFormatData { */ private String format; + public DataFormatData() { + this.index = 0; + } + @Override public DataFormatData clone() { DataFormatData dataFormatData = new DataFormatData(); diff --git a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java index 3fb6575e..5071709d 100644 --- a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java +++ b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java @@ -1,6 +1,5 @@ package com.alibaba.excel.util; -import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; @@ -68,16 +67,9 @@ public class WorkBookUtil { } return; case CSV: - CsvWorkbook csvWorkbook; - if (writeWorkbookHolder.getFile() != null) { - csvWorkbook = new CsvWorkbook( - new OutputStreamWriter(new FileOutputStream(writeWorkbookHolder.getFile()), - writeWorkbookHolder.getFileCharset()), - writeWorkbookHolder.getGlobalConfiguration().getLocale()); - } else { - csvWorkbook = new CsvWorkbook(null, writeWorkbookHolder.getGlobalConfiguration().getLocale()); - } - CsvWorkbook csvWorkbook = new CsvWorkbook(writeWorkbookHolder); + CsvWorkbook csvWorkbook = new CsvWorkbook( + new OutputStreamWriter(writeWorkbookHolder.getOutputStream(), writeWorkbookHolder.getCharset()), + writeWorkbookHolder.getGlobalConfiguration().getLocale()); writeWorkbookHolder.setCachedWorkbook(csvWorkbook); writeWorkbookHolder.setWorkbook(csvWorkbook); return; diff --git a/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java b/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java index 899e4ca1..9f4bea5c 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java +++ b/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java @@ -3,6 +3,7 @@ package com.alibaba.excel.write.metadata; import java.io.File; import java.io.InputStream; import java.io.OutputStream; +import java.nio.charset.Charset; import com.alibaba.excel.support.ExcelTypeEnum; @@ -31,6 +32,10 @@ public class WriteWorkbook extends WriteBasicParameter { * If 'outputStream' and 'file' all not empty,file first */ private OutputStream outputStream; + /** + * output charset + */ + private Charset charset; /** * Template input stream *

    diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java index cb29ec22..a7871ba7 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java @@ -65,14 +65,14 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { * If 'outputStream' and 'file' all not empty,file first */ private File file; - /** - * charset of final output file - */ - private Charset fileCharset; /** * Final output stream */ private OutputStream outputStream; + /** + * output charset + */ + private Charset charset; /** * Template input stream *

    @@ -152,6 +152,13 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { } else { this.outputStream = writeWorkbook.getOutputStream(); } + + if (writeWorkbook.getCharset() == null) { + this.charset = Charset.defaultCharset(); + } else { + this.charset = writeWorkbook.getCharset(); + } + if (writeWorkbook.getAutoCloseStream() == null) { this.autoCloseStream = Boolean.TRUE; } else { From 2682a041eb5820c8914759f8c29f2ef716c07ca2 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 10 Sep 2021 17:58:23 +0800 Subject: [PATCH 094/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=A0=BC=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/excel/converters/ConverterKeyBuild.java | 2 +- .../java/com/alibaba/excel/metadata/csv/CsvCell.java | 12 ++++++++++++ .../alibaba/excel/metadata/data/WriteCellData.java | 2 +- .../write/executor/AbstractExcelWriteExecutor.java | 4 ++++ 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/alibaba/excel/converters/ConverterKeyBuild.java b/src/main/java/com/alibaba/excel/converters/ConverterKeyBuild.java index a92f3033..f1068591 100644 --- a/src/main/java/com/alibaba/excel/converters/ConverterKeyBuild.java +++ b/src/main/java/com/alibaba/excel/converters/ConverterKeyBuild.java @@ -39,6 +39,6 @@ public class ConverterKeyBuild { if (cellDataTypeEnum == null) { return key; } - return key + "-" + cellDataTypeEnum.toString(); + return key + "-" + cellDataTypeEnum; } } diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java index 4898ff2c..6128ebd4 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java @@ -86,6 +86,9 @@ public class CsvCell extends CellBase { this.csvRow = csvRow; this.columnIndex = columnIndex; this.cellType = cellType; + if (this.cellType == null) { + this.cellType = CellType._NONE; + } } @Override @@ -98,6 +101,7 @@ public class CsvCell extends CellBase { FormulaData formulaData = new FormulaData(); formulaData.setFormulaValue(formula); this.formulaData = formulaData; + this.cellType = CellType.FORMULA; } @Override @@ -108,6 +112,7 @@ public class CsvCell extends CellBase { @Override protected void setCellValueImpl(double value) { numberValue = BigDecimal.valueOf(value); + this.cellType = CellType.NUMERIC; } @Override @@ -116,11 +121,13 @@ public class CsvCell extends CellBase { return; } this.dateValue = LocalDateTime.ofInstant(value.toInstant(), ZoneId.systemDefault()); + this.cellType = CellType.NUMERIC; } @Override protected void setCellValueImpl(LocalDateTime value) { this.dateValue = value; + this.cellType = CellType.NUMERIC; } @Override @@ -129,16 +136,19 @@ public class CsvCell extends CellBase { return; } this.dateValue = LocalDateTime.ofInstant(value.toInstant(), ZoneId.systemDefault()); + this.cellType = CellType.NUMERIC; } @Override protected void setCellValueImpl(String value) { this.stringValue = value; + this.cellType = CellType.STRING; } @Override protected void setCellValueImpl(RichTextString value) { richTextString = value; + this.cellType = CellType.STRING; } @Override @@ -241,11 +251,13 @@ public class CsvCell extends CellBase { @Override public void setCellValue(boolean value) { this.booleanValue = value; + this.cellType = CellType.BOOLEAN; } @Override public void setCellErrorValue(byte value) { this.numberValue = BigDecimal.valueOf(value); + this.cellType = CellType.ERROR; } @Override diff --git a/src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java b/src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java index 82231e5f..4c54b6fa 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java +++ b/src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java @@ -40,7 +40,7 @@ public class WriteCellData extends CellData { */ private HyperlinkData hyperlinkData; /** - * sytle + * style */ private WriteCellStyle writeCellStyle; diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index 9f32153e..44ba04ee 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -269,6 +269,10 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { converter = excelContentProperty.getConverter(); } if (converter == null) { + // csv is converted to string by default + if (writeContext.writeWorkbookHolder().getExcelType() == ExcelTypeEnum.CSV) { + targetType = CellDataTypeEnum.STRING; + } converter = currentWriteHolder.converterMap().get(ConverterKeyBuild.buildKey(clazz, targetType)); } if (converter == null) { From cfa62f2cc89fb9e9461d2ff7698fc9ab2ea0218f Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 10 Sep 2021 18:51:39 +0800 Subject: [PATCH 095/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=A0=BC=E5=A4=B4=E6=B2=A1=E6=9C=89=E6=A0=B7=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/excel/context/WriteContextImpl.java | 9 +++++++-- .../test/core/annotation/AnnotationDataTest.java | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java index da12189c..5766b4b3 100644 --- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java @@ -245,10 +245,15 @@ public class WriteContextImpl implements WriteContext { Head head = entry.getValue(); int columnIndex = entry.getKey(); WriteHandlerUtils.beforeCellCreate(this, row, head, columnIndex, relativeRowIndex, Boolean.TRUE); + Cell cell = row.createCell(columnIndex); + WriteHandlerUtils.afterCellCreate(this, cell, head, relativeRowIndex, Boolean.TRUE); - cell.setCellValue(head.getHeadNameList().get(relativeRowIndex)); - WriteHandlerUtils.afterCellDispose(this, (WriteCellData)null, cell, head, relativeRowIndex, + + WriteCellData writeCellData = new WriteCellData<>(head.getHeadNameList().get(relativeRowIndex)); + cell.setCellValue(writeCellData.getStringValue()); + + WriteHandlerUtils.afterCellDispose(this, writeCellData, cell, head, relativeRowIndex, Boolean.TRUE); } } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java index 54fa2700..da6848a3 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java @@ -39,7 +39,7 @@ public class AnnotationDataTest { @Test public void t02ReadAndWriteCsv() throws Exception { - readAndWrite(fileCsv); + //readAndWrite(fileCsv); } private void readAndWrite(File file) throws Exception { From d970854f6f8829560fa5818d49bc7b7787dc6133 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 10 Sep 2021 20:03:54 +0800 Subject: [PATCH 096/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=97=A5=E6=9C=9F?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/excel/metadata/csv/CsvCell.java | 52 +++++++++++-------- .../alibaba/excel/metadata/csv/CsvRow.java | 13 +++-- .../alibaba/excel/metadata/csv/CsvSheet.java | 48 +++++++++++++++-- .../excel/metadata/csv/CsvWorkbook.java | 11 +++- .../com/alibaba/excel/util/StyleUtil.java | 2 +- .../com/alibaba/excel/util/WorkBookUtil.java | 2 +- .../easyexcel/test/temp/csv/CsvReadTest.java | 2 +- 7 files changed, 98 insertions(+), 32 deletions(-) diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java index 6128ebd4..a434758e 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java @@ -6,6 +6,7 @@ import java.time.ZoneId; import java.util.Calendar; import java.util.Date; +import com.alibaba.excel.enums.NumericCellTypeEnum; import com.alibaba.excel.metadata.data.FormulaData; import lombok.AccessLevel; @@ -17,6 +18,7 @@ import org.apache.poi.ss.usermodel.CellBase; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Comment; +import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Hyperlink; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Row; @@ -44,6 +46,17 @@ public class CsvCell extends CellBase { @Getter(value = AccessLevel.NONE) @Setter(value = AccessLevel.NONE) private CellType cellType; + + /** + * workbook + */ + private final CsvWorkbook csvWorkbook; + + /** + * sheet + */ + private final CsvSheet csvSheet; + /** * row */ @@ -52,7 +65,7 @@ public class CsvCell extends CellBase { /** * {@link CellType#NUMERIC} */ - private BigDecimal numberValue; + private Double numberValue; /** * {@link CellType#STRING} and {@link CellType#ERROR} {@link CellType#FORMULA} */ @@ -62,11 +75,6 @@ public class CsvCell extends CellBase { */ private Boolean booleanValue; - /** - * {@link CellType#NUMERIC} - */ - private LocalDateTime dateValue; - /** * formula */ @@ -82,7 +90,9 @@ public class CsvCell extends CellBase { */ private CellStyle cellStyle; - public CsvCell(CsvRow csvRow, Integer columnIndex, CellType cellType) { + public CsvCell(CsvWorkbook csvWorkbook, CsvSheet csvSheet, CsvRow csvRow, Integer columnIndex, CellType cellType) { + this.csvWorkbook = csvWorkbook; + this.csvSheet = csvSheet; this.csvRow = csvRow; this.columnIndex = columnIndex; this.cellType = cellType; @@ -111,31 +121,25 @@ public class CsvCell extends CellBase { @Override protected void setCellValueImpl(double value) { - numberValue = BigDecimal.valueOf(value); + this.numberValue = value; this.cellType = CellType.NUMERIC; } @Override protected void setCellValueImpl(Date value) { - if (value == null) { - return; - } - this.dateValue = LocalDateTime.ofInstant(value.toInstant(), ZoneId.systemDefault()); + this.numberValue = DateUtil.getExcelDate(value, csvWorkbook.getUse1904windowing()); this.cellType = CellType.NUMERIC; } @Override protected void setCellValueImpl(LocalDateTime value) { - this.dateValue = value; + this.numberValue = DateUtil.getExcelDate(value, csvWorkbook.getUse1904windowing()); this.cellType = CellType.NUMERIC; } @Override protected void setCellValueImpl(Calendar value) { - if (value == null) { - return; - } - this.dateValue = LocalDateTime.ofInstant(value.toInstant(), ZoneId.systemDefault()); + this.numberValue = DateUtil.getExcelDate(value, csvWorkbook.getUse1904windowing()); this.cellType = CellType.NUMERIC; } @@ -227,15 +231,18 @@ public class CsvCell extends CellBase { @Override public Date getDateCellValue() { - if (dateValue == null) { + if (numberValue == null) { return null; } - return Date.from(dateValue.atZone(ZoneId.systemDefault()).toInstant()); + return DateUtil.getJavaDate(numberValue, csvWorkbook.getUse1904windowing()); } @Override public LocalDateTime getLocalDateTimeCellValue() { - return dateValue; + if (numberValue == null) { + return null; + } + return DateUtil.getLocalDateTime(numberValue, csvWorkbook.getUse1904windowing()); } @Override @@ -256,12 +263,15 @@ public class CsvCell extends CellBase { @Override public void setCellErrorValue(byte value) { - this.numberValue = BigDecimal.valueOf(value); + this.numberValue = value; this.cellType = CellType.ERROR; } @Override public boolean getBooleanCellValue() { + if (booleanValue == null) { + return false; + } return booleanValue; } diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java index 0550e611..24acd9d9 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java @@ -25,10 +25,16 @@ public class CsvRow implements Row { */ private final List cellList; + /** + * workbook + */ + private final CsvWorkbook csvWorkbook; + /** * sheet */ private final CsvSheet csvSheet; + /** * row index */ @@ -39,22 +45,23 @@ public class CsvRow implements Row { */ private CellStyle cellStyle; - public CsvRow(CsvSheet csvSheet, Integer rowIndex) { + public CsvRow(CsvWorkbook csvWorkbook, CsvSheet csvSheet, Integer rowIndex) { cellList = Lists.newArrayList(); + this.csvWorkbook = csvWorkbook; this.csvSheet = csvSheet; this.rowIndex = rowIndex; } @Override public Cell createCell(int column) { - CsvCell cell = new CsvCell(this, column, null); + CsvCell cell = new CsvCell(csvWorkbook, csvSheet, this, column, null); cellList.add(cell); return cell; } @Override public Cell createCell(int column, CellType type) { - CsvCell cell = new CsvCell(this, column, type); + CsvCell cell = new CsvCell(csvWorkbook, csvSheet, this, column, type); cellList.add(cell); return cell; } diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java index fa83fd47..0b203804 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java @@ -7,8 +7,13 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import com.alibaba.excel.enums.NumericCellTypeEnum; import com.alibaba.excel.exception.ExcelGenerateException; +import com.alibaba.excel.metadata.data.WriteCellData; +import com.alibaba.excel.util.DateUtils; import com.alibaba.excel.util.ListUtils; +import com.alibaba.excel.util.NumberDataFormatterUtils; +import com.alibaba.excel.util.StringUtils; import lombok.Data; import org.apache.commons.csv.CSVFormat; @@ -61,7 +66,8 @@ public class CsvSheet implements Sheet, Closeable { /** * last row index */ - private int lastRowIndex; + private Integer lastRowIndex; + /** * row cache */ @@ -74,7 +80,7 @@ public class CsvSheet implements Sheet, Closeable { public CsvSheet(CsvWorkbook csvWorkbook, Appendable out) { this.csvWorkbook = csvWorkbook; this.out = out; - this.rowCacheCount = 500; + this.rowCacheCount = 3000; this.csvFormat = CSVFormat.DEFAULT; this.lastRowIndex = -1; } @@ -87,7 +93,7 @@ public class CsvSheet implements Sheet, Closeable { lastRowIndex++; assert rownum == lastRowIndex : "csv create row must be in order."; printData(); - CsvRow csvRow = new CsvRow(this, rownum); + CsvRow csvRow = new CsvRow(csvWorkbook, this, rownum); rowCache.add(csvRow); return csvRow; } @@ -724,7 +730,7 @@ public class CsvSheet implements Sheet, Closeable { Iterator cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { CsvCell csvCell = (CsvCell)cellIterator.next(); - csvPrinter.print(csvCell.getStringCellValue()); + csvPrinter.print(buildCellValue(csvCell)); } csvPrinter.println(); } @@ -734,4 +740,38 @@ public class CsvSheet implements Sheet, Closeable { } } + private String buildCellValue(CsvCell csvCell) { + switch (csvCell.getCellType()) { + case STRING: + case ERROR: + case FORMULA: + return csvCell.getStringCellValue(); + case NUMERIC: + + NumberDataFormatterUtils.format() + + if (csvCell.getNumericCellType() == NumericCellTypeEnum.DATE) { + // date + if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { + return new WriteCellData<>(DateUtils.format(value, null)); + } else { + return new WriteCellData<>( + DateUtils.format(value, contentProperty.getDateTimeFormatProperty().getFormat())); + } + + } else { + //number + + } + case BOOLEAN: + return csvCell.getBooleanValue().toString(); + case BLANK: + return StringUtils.EMPTY; + default: + return null; + } + } + + private String + } diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java index ae8a3e50..ba55e01f 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java @@ -36,6 +36,14 @@ public class CsvWorkbook implements Workbook { * locale */ private Locale locale; + /** + * true if date uses 1904 windowing, or false if using 1900 date windowing. + * + * default is false + * + * @return + */ + private Boolean use1904windowing; /** * data format @@ -50,9 +58,10 @@ public class CsvWorkbook implements Workbook { */ private List csvCellStyleList; - public CsvWorkbook(Appendable out, Locale locale) { + public CsvWorkbook(Appendable out, Locale locale, Boolean use1904windowing) { this.out = out; this.locale = locale; + this.use1904windowing = use1904windowing; } @Override diff --git a/src/main/java/com/alibaba/excel/util/StyleUtil.java b/src/main/java/com/alibaba/excel/util/StyleUtil.java index 0b70cf9b..70c7ac7a 100644 --- a/src/main/java/com/alibaba/excel/util/StyleUtil.java +++ b/src/main/java/com/alibaba/excel/util/StyleUtil.java @@ -123,7 +123,7 @@ public class StyleUtil { public static Font buildFont(Workbook workbook, WriteFont writeFont) { Font font = workbook.createFont(); - if (writeFont == null) { + if (writeFont == null || font == null) { return font; } if (writeFont.getFontName() != null) { diff --git a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java index 5071709d..a7a3d74a 100644 --- a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java +++ b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java @@ -69,7 +69,7 @@ public class WorkBookUtil { case CSV: CsvWorkbook csvWorkbook = new CsvWorkbook( new OutputStreamWriter(writeWorkbookHolder.getOutputStream(), writeWorkbookHolder.getCharset()), - writeWorkbookHolder.getGlobalConfiguration().getLocale()); + writeWorkbookHolder.getGlobalConfiguration().getLocale(), writeWorkbookHolder.getGlobalConfiguration().getUse1904windowing()); writeWorkbookHolder.setCachedWorkbook(csvWorkbook); writeWorkbookHolder.setWorkbook(csvWorkbook); return; diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java index 653eafc6..d6f8fb2a 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java @@ -84,7 +84,7 @@ public class CsvReadTest { List list = new ArrayList<>(); for (int i = 0; i < 10; i++) { CsvData data = new CsvData(); - data.setString("字符串" + i); + data.setString("字符,串" + i); data.setDate(new Date()); data.setDoubleData(0.56); data.setIgnore("忽略" + i); From 7a2c5634d03befa0e1817251cec6873c7e83f1e1 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 10 Sep 2021 20:47:20 +0800 Subject: [PATCH 097/129] =?UTF-8?q?=E5=AE=8C=E6=88=90csv=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E4=B9=A6=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/enums/NumericCellTypeEnum.java | 22 ++++ .../alibaba/excel/metadata/csv/CsvCell.java | 40 +++++-- .../excel/metadata/csv/CsvCellStyle.java | 8 +- .../alibaba/excel/metadata/csv/CsvSheet.java | 45 ++++--- .../excel/metadata/csv/CsvWorkbook.java | 20 +++- .../excel/metadata/data/DataFormatData.java | 4 - .../excel/metadata/format/DataFormatter.java | 112 ++++++++++-------- .../excel/util/NumberDataFormatterUtils.java | 25 +++- .../com/alibaba/excel/util/WorkBookUtil.java | 4 +- 9 files changed, 190 insertions(+), 90 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/enums/NumericCellTypeEnum.java diff --git a/src/main/java/com/alibaba/excel/enums/NumericCellTypeEnum.java b/src/main/java/com/alibaba/excel/enums/NumericCellTypeEnum.java new file mode 100644 index 00000000..22001f13 --- /dev/null +++ b/src/main/java/com/alibaba/excel/enums/NumericCellTypeEnum.java @@ -0,0 +1,22 @@ +package com.alibaba.excel.enums; + +import org.apache.poi.ss.usermodel.CellType; + +/** + * Used to supplement {@link CellType}. + * + * Cannot distinguish between date and number in write case. + * + * @author Jiaju Zhuang + */ +public enum NumericCellTypeEnum { + /** + * number + */ + NUMBER, + /** + * date. Support only when writing. + */ + DATE, + ; +} diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java index a434758e..f0e925e6 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java @@ -18,7 +18,6 @@ import org.apache.poi.ss.usermodel.CellBase; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Hyperlink; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Row; @@ -47,6 +46,11 @@ public class CsvCell extends CellBase { @Setter(value = AccessLevel.NONE) private CellType cellType; + /** + * numeric cell type + */ + private NumericCellTypeEnum numericCellType; + /** * workbook */ @@ -65,7 +69,7 @@ public class CsvCell extends CellBase { /** * {@link CellType#NUMERIC} */ - private Double numberValue; + private BigDecimal numberValue; /** * {@link CellType#STRING} and {@link CellType#ERROR} {@link CellType#FORMULA} */ @@ -75,6 +79,11 @@ public class CsvCell extends CellBase { */ private Boolean booleanValue; + /** + * {@link CellType#NUMERIC} + */ + private LocalDateTime dateValue; + /** * formula */ @@ -121,25 +130,33 @@ public class CsvCell extends CellBase { @Override protected void setCellValueImpl(double value) { - this.numberValue = value; + numberValue = BigDecimal.valueOf(value); this.cellType = CellType.NUMERIC; } @Override protected void setCellValueImpl(Date value) { - this.numberValue = DateUtil.getExcelDate(value, csvWorkbook.getUse1904windowing()); + if (value == null) { + return; + } + this.dateValue = LocalDateTime.ofInstant(value.toInstant(), ZoneId.systemDefault()); this.cellType = CellType.NUMERIC; + this.numericCellType = NumericCellTypeEnum.DATE; } @Override protected void setCellValueImpl(LocalDateTime value) { - this.numberValue = DateUtil.getExcelDate(value, csvWorkbook.getUse1904windowing()); + this.dateValue = value; this.cellType = CellType.NUMERIC; + this.numericCellType = NumericCellTypeEnum.DATE; } @Override protected void setCellValueImpl(Calendar value) { - this.numberValue = DateUtil.getExcelDate(value, csvWorkbook.getUse1904windowing()); + if (value == null) { + return; + } + this.dateValue = LocalDateTime.ofInstant(value.toInstant(), ZoneId.systemDefault()); this.cellType = CellType.NUMERIC; } @@ -231,18 +248,15 @@ public class CsvCell extends CellBase { @Override public Date getDateCellValue() { - if (numberValue == null) { + if (dateValue == null) { return null; } - return DateUtil.getJavaDate(numberValue, csvWorkbook.getUse1904windowing()); + return Date.from(dateValue.atZone(ZoneId.systemDefault()).toInstant()); } @Override public LocalDateTime getLocalDateTimeCellValue() { - if (numberValue == null) { - return null; - } - return DateUtil.getLocalDateTime(numberValue, csvWorkbook.getUse1904windowing()); + return dateValue; } @Override @@ -263,7 +277,7 @@ public class CsvCell extends CellBase { @Override public void setCellErrorValue(byte value) { - this.numberValue = value; + this.numberValue = BigDecimal.valueOf(value); this.cellType = CellType.ERROR; } diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java index ca153e45..08b46e3a 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java @@ -52,13 +52,17 @@ public class CsvCellStyle implements CellStyle { @Override public short getDataFormat() { - initDataFormatData(); + if (dataFormatData == null) { + return 0; + } return dataFormatData.getIndex(); } @Override public String getDataFormatString() { - initDataFormatData(); + if (dataFormatData == null) { + return null; + } return dataFormatData.getFormat(); } diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java index 0b203804..14c6a207 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java @@ -7,9 +7,9 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import com.alibaba.excel.constant.BuiltinFormats; import com.alibaba.excel.enums.NumericCellTypeEnum; import com.alibaba.excel.exception.ExcelGenerateException; -import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.util.DateUtils; import com.alibaba.excel.util.ListUtils; import com.alibaba.excel.util.NumberDataFormatterUtils; @@ -25,6 +25,7 @@ import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Comment; import org.apache.poi.ss.usermodel.DataValidation; import org.apache.poi.ss.usermodel.DataValidationHelper; +import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Footer; import org.apache.poi.ss.usermodel.Header; @@ -45,7 +46,6 @@ import org.apache.poi.ss.util.PaneInformation; */ @Data public class CsvSheet implements Sheet, Closeable { - /** * workbook */ @@ -747,21 +747,40 @@ public class CsvSheet implements Sheet, Closeable { case FORMULA: return csvCell.getStringCellValue(); case NUMERIC: - - NumberDataFormatterUtils.format() - + Short dataFormat = null; + String dataFormatString = null; + if (csvCell.getCellStyle() != null) { + dataFormat = csvCell.getCellStyle().getDataFormat(); + dataFormatString = csvCell.getCellStyle().getDataFormatString(); + } if (csvCell.getNumericCellType() == NumericCellTypeEnum.DATE) { + if (csvCell.getDateValue() == null) { + return null; + } // date - if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { - return new WriteCellData<>(DateUtils.format(value, null)); - } else { - return new WriteCellData<>( - DateUtils.format(value, contentProperty.getDateTimeFormatProperty().getFormat())); + if (dataFormat == null) { + dataFormatString = DateUtils.defaultDateFormat; + dataFormat = csvWorkbook.createDataFormat().getFormat(dataFormatString); } - + if (dataFormatString == null) { + dataFormatString = csvWorkbook.createDataFormat().getFormat(dataFormat); + } + return NumberDataFormatterUtils.format( + DateUtil.getExcelDate(csvCell.getDateValue(), csvWorkbook.getUse1904windowing()), + dataFormat, dataFormatString, csvWorkbook.getUse1904windowing(), csvWorkbook.getLocale(), + csvWorkbook.getUseScientificFormat()); } else { + if (csvCell.getNumberValue() == null) { + return null; + } //number - + if (dataFormat == null) { + dataFormat = BuiltinFormats.GENERAL; + dataFormatString = csvWorkbook.createDataFormat().getFormat(dataFormat); + } + return NumberDataFormatterUtils.format(csvCell.getNumericCellValue(), dataFormat, dataFormatString, + csvWorkbook.getUse1904windowing(), csvWorkbook.getLocale(), + csvWorkbook.getUseScientificFormat()); } case BOOLEAN: return csvCell.getBooleanValue().toString(); @@ -772,6 +791,4 @@ public class CsvSheet implements Sheet, Closeable { } } - private String - } diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java index ba55e01f..e26a2b65 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java @@ -32,10 +32,7 @@ public class CsvWorkbook implements Workbook { * output */ private Appendable out; - /** - * locale - */ - private Locale locale; + /** * true if date uses 1904 windowing, or false if using 1900 date windowing. * @@ -45,6 +42,18 @@ public class CsvWorkbook implements Workbook { */ private Boolean use1904windowing; + /** + * locale + */ + private Locale locale; + + /** + * Whether to use scientific Format. + * + * default is false + */ + private Boolean useScientificFormat; + /** * data format */ @@ -58,10 +67,11 @@ public class CsvWorkbook implements Workbook { */ private List csvCellStyleList; - public CsvWorkbook(Appendable out, Locale locale, Boolean use1904windowing) { + public CsvWorkbook(Appendable out, Locale locale, Boolean use1904windowing, Boolean useScientificFormat) { this.out = out; this.locale = locale; this.use1904windowing = use1904windowing; + this.useScientificFormat = useScientificFormat; } @Override diff --git a/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java b/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java index 2cbcb42c..7f1a14c8 100644 --- a/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java +++ b/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java @@ -19,10 +19,6 @@ public class DataFormatData { */ private String format; - public DataFormatData() { - this.index = 0; - } - @Override public DataFormatData clone() { DataFormatData dataFormatData = new DataFormatData(); diff --git a/src/main/java/com/alibaba/excel/metadata/format/DataFormatter.java b/src/main/java/com/alibaba/excel/metadata/format/DataFormatter.java index e9266c71..aebbf4fc 100644 --- a/src/main/java/com/alibaba/excel/metadata/format/DataFormatter.java +++ b/src/main/java/com/alibaba/excel/metadata/format/DataFormatter.java @@ -34,6 +34,8 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import com.alibaba.excel.util.DateUtils; + import org.apache.poi.ss.format.CellFormat; import org.apache.poi.ss.format.CellFormatResult; import org.apache.poi.ss.usermodel.DateUtil; @@ -42,9 +44,6 @@ import org.apache.poi.ss.usermodel.FractionFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.alibaba.excel.metadata.GlobalConfiguration; -import com.alibaba.excel.util.DateUtils; - /** * Written with reference to {@link org.apache.poi.ss.usermodel.DataFormatter}.Made some optimizations for date * conversion. @@ -54,21 +53,31 @@ import com.alibaba.excel.util.DateUtils; * @author Jiaju Zhuang */ public class DataFormatter { - /** For logging any problems we find */ + /** + * For logging any problems we find + */ private static final Logger LOGGER = LoggerFactory.getLogger(DataFormatter.class); private static final String defaultFractionWholePartFormat = "#"; private static final String defaultFractionFractionPartFormat = "#/##"; - /** Pattern to find a number format: "0" or "#" */ + /** + * Pattern to find a number format: "0" or "#" + */ private static final Pattern numPattern = Pattern.compile("[0#]+"); - /** Pattern to find days of week as text "ddd...." */ + /** + * Pattern to find days of week as text "ddd...." + */ private static final Pattern daysAsText = Pattern.compile("([d]{3,})", Pattern.CASE_INSENSITIVE); - /** Pattern to find "AM/PM" marker */ + /** + * Pattern to find "AM/PM" marker + */ private static final Pattern amPmPattern = Pattern.compile("(([AP])[M/P]*)|(([上下])[午/下]*)", Pattern.CASE_INSENSITIVE); - /** Pattern to find formats with condition ranges e.g. [>=100] */ + /** + * Pattern to find formats with condition ranges e.g. [>=100] + */ private static final Pattern rangeConditionalPattern = Pattern.compile(".*\\[\\s*(>|>=|<|<=|=)\\s*[0-9]*\\.*[0-9].*"); @@ -107,10 +116,10 @@ public class DataFormatter { * ("#"). */ private static final String invalidDateTimeString; + static { StringBuilder buf = new StringBuilder(); - for (int i = 0; i < 255; i++) - buf.append('#'); + for (int i = 0; i < 255; i++) {buf.append('#');} invalidDateTimeString = buf.toString(); } @@ -123,14 +132,18 @@ public class DataFormatter { * The date symbols of the locale used for formatting values. */ private DateFormatSymbols dateSymbols; - /** A default format to use when a number pattern cannot be parsed. */ + /** + * A default format to use when a number pattern cannot be parsed. + */ private Format defaultNumFormat; /** * A map to cache formats. Map formats */ private final Map formats = new HashMap(); - /** stores the locale valid it the last formatting call */ + /** + * stores the locale valid it the last formatting call + */ private Locale locale; /** * true if date uses 1904 windowing, or false if using 1900 date windowing. @@ -149,28 +162,31 @@ public class DataFormatter { /** * Creates a formatter using the given locale. - * */ - public DataFormatter(GlobalConfiguration globalConfiguration) { - if (globalConfiguration == null) { + public DataFormatter(Boolean use1904windowing, Locale locale, Boolean useScientificFormat) { + if (use1904windowing == null) { this.use1904windowing = Boolean.FALSE; + } else { + this.use1904windowing = use1904windowing; + } + + if (locale == null) { this.locale = Locale.getDefault(); + } else { + this.locale = locale; + } + + if (use1904windowing == null) { this.useScientificFormat = Boolean.FALSE; } else { - this.use1904windowing = - globalConfiguration.getUse1904windowing() != null ? globalConfiguration.getUse1904windowing() - : Boolean.FALSE; - this.locale = - globalConfiguration.getLocale() != null ? globalConfiguration.getLocale() : Locale.getDefault(); - this.useScientificFormat = - globalConfiguration.getUseScientificFormat() != null ? globalConfiguration.getUseScientificFormat() - : Boolean.FALSE; + this.useScientificFormat = useScientificFormat; } + this.dateSymbols = DateFormatSymbols.getInstance(this.locale); this.decimalSymbols = DecimalFormatSymbols.getInstance(this.locale); } - private Format getFormat(Double data,Short dataFormat, String dataFormatString) { + private Format getFormat(Double data, Short dataFormat, String dataFormatString) { // Might be better to separate out the n p and z formats, falling back to p when n and z are not set. // That however would require other code to be re factored. @@ -188,7 +204,7 @@ public class DataFormatter { if (formatStr.contains(";") && (formatStr.indexOf(';') != formatStr.lastIndexOf(';') || rangeConditionalPattern.matcher(formatStr).matches() - ) ) { + )) { try { // Ask CellFormat to get a formatter for it CellFormat cfmt = CellFormat.getInstance(locale, formatStr); @@ -200,9 +216,9 @@ public class DataFormatter { cellValueO = DateUtil.getJavaDate(data, use1904windowing); } // Wrap and return (non-cachable - CellFormat does that) - return new CellFormatResultWrapper( cfmt.apply(cellValueO) ); + return new CellFormatResultWrapper(cfmt.apply(cellValueO)); } catch (Exception e) { - LOGGER.warn("Formatting failed for format {}, falling back",formatStr, e); + LOGGER.warn("Formatting failed for format {}, falling back", formatStr, e); } } @@ -240,11 +256,9 @@ public class DataFormatter { // Paranoid replacement... int at = formatStr.indexOf(colour); - if (at == -1) - break; + if (at == -1) {break;} String nFormatStr = formatStr.substring(0, at) + formatStr.substring(at + colour.length()); - if (nFormatStr.equals(formatStr)) - break; + if (nFormatStr.equals(formatStr)) {break;} // Try again in case there's multiple formatStr = nFormatStr; @@ -601,8 +615,7 @@ public class DataFormatter { * number format, or no rules apply, the cell's style format is used. If the style does not have a format, the * default date format is applied. * - * @param data - * to format + * @param data to format * @param dataFormat * @param dataFormatString * @return Formatted value @@ -624,8 +637,7 @@ public class DataFormatter { * Format comes from either the highest priority conditional format rule with a specified format, or from the cell * style. * - * @param data - * to format + * @param data to format * @param dataFormat * @param dataFormatString * @return a formatted number string @@ -663,8 +675,7 @@ public class DataFormatter { * Number value. *

    * - * @param format - * A Format instance to be used as a default + * @param format A Format instance to be used as a default * @see Format#format */ public void setDefaultNumberFormat(Format format) { @@ -684,10 +695,8 @@ public class DataFormatter { * Number value. *

    * - * @param excelFormatStr - * The data format string - * @param format - * A Format instance + * @param excelFormatStr The data format string + * @param format A Format instance */ public void addFormat(String excelFormatStr, Format format) { formats.put(excelFormatStr, format); @@ -715,10 +724,8 @@ public class DataFormatter { /** * Enables custom rounding mode on the given Decimal Format. * - * @param format - * DecimalFormat - * @param roundingMode - * RoundingMode + * @param format DecimalFormat + * @param roundingMode RoundingMode */ public static void setExcelStyleRoundingMode(DecimalFormat format, RoundingMode roundingMode) { format.setRoundingMode(roundingMode); @@ -737,7 +744,9 @@ public class DataFormatter { // enforce singleton } - /** Format a number as an SSN */ + /** + * Format a number as an SSN + */ public static String format(Number num) { String result = df.format(num); return result.substring(0, 3) + '-' + result.substring(3, 5) + '-' + result.substring(5, 9); @@ -767,7 +776,9 @@ public class DataFormatter { // enforce singleton } - /** Format a number as Zip + 4 */ + /** + * Format a number as Zip + 4 + */ public static String format(Number num) { String result = df.format(num); return result.substring(0, 5) + '-' + result.substring(5, 9); @@ -797,7 +808,9 @@ public class DataFormatter { // enforce singleton } - /** Format a number as a phone number */ + /** + * Format a number as a phone number + */ public static String format(Number num) { String result = df.format(num); StringBuilder sb = new StringBuilder(); @@ -833,7 +846,8 @@ public class DataFormatter { } /** - * Workaround until we merge {@link org.apache.poi.ss.usermodel.DataFormatter} with {@link CellFormat}. Constant, non-cachable wrapper around a + * Workaround until we merge {@link org.apache.poi.ss.usermodel.DataFormatter} with {@link CellFormat}. Constant, + * non-cachable wrapper around a * {@link CellFormatResult} */ private final class CellFormatResultWrapper extends Format { diff --git a/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java b/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java index de01ad54..f9a8ee23 100644 --- a/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java +++ b/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java @@ -1,5 +1,7 @@ package com.alibaba.excel.util; +import java.util.Locale; + import com.alibaba.excel.metadata.format.DataFormatter; import com.alibaba.excel.metadata.GlobalConfiguration; @@ -26,13 +28,32 @@ public class NumberDataFormatterUtils { */ public static String format(Double data, Short dataFormat, String dataFormatString, GlobalConfiguration globalConfiguration) { + if (globalConfiguration == null) { + return format(data, dataFormat, dataFormatString, null, null, null); + } + return format(data, dataFormat, dataFormatString, globalConfiguration.getUse1904windowing(), + globalConfiguration.getLocale(), globalConfiguration.getUseScientificFormat()); + } + + /** + * Format number data. + * + * @param data + * @param dataFormat Not null. + * @param dataFormatString + * @param use1904windowing + * @param locale + * @param useScientificFormat + * @return + */ + public static String format(Double data, Short dataFormat, String dataFormatString, Boolean use1904windowing, + Locale locale, Boolean useScientificFormat) { DataFormatter dataFormatter = DATA_FORMATTER_THREAD_LOCAL.get(); if (dataFormatter == null) { - dataFormatter = new DataFormatter(globalConfiguration); + dataFormatter = new DataFormatter(use1904windowing, locale, useScientificFormat); DATA_FORMATTER_THREAD_LOCAL.set(dataFormatter); } return dataFormatter.format(data, dataFormat, dataFormatString); - } public static void removeThreadLocalCache() { diff --git a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java index a7a3d74a..3e9732a9 100644 --- a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java +++ b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java @@ -69,7 +69,9 @@ public class WorkBookUtil { case CSV: CsvWorkbook csvWorkbook = new CsvWorkbook( new OutputStreamWriter(writeWorkbookHolder.getOutputStream(), writeWorkbookHolder.getCharset()), - writeWorkbookHolder.getGlobalConfiguration().getLocale(), writeWorkbookHolder.getGlobalConfiguration().getUse1904windowing()); + writeWorkbookHolder.getGlobalConfiguration().getLocale(), + writeWorkbookHolder.getGlobalConfiguration().getUse1904windowing(), + writeWorkbookHolder.getGlobalConfiguration().getUseScientificFormat()); writeWorkbookHolder.setCachedWorkbook(csvWorkbook); writeWorkbookHolder.setWorkbook(csvWorkbook); return; From 316db1f256c21ca21045b54944ce8d4d71fcbd64 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Fri, 10 Sep 2021 21:02:39 +0800 Subject: [PATCH 098/129] =?UTF-8?q?=E5=AE=8C=E6=88=902=E4=B8=AA=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E6=A1=88=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/excel/metadata/csv/CsvSheet.java | 4 ++++ .../test/core/annotation/AnnotationDataTest.java | 6 +++--- .../annotation/AnnotationIndexAndNameDataTest.java | 13 ++++++++++--- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java index 14c6a207..a54d0681 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java @@ -728,8 +728,12 @@ public class CsvSheet implements Sheet, Closeable { try { for (CsvRow row : rowCache) { Iterator cellIterator = row.cellIterator(); + int columnIndex = 0; while (cellIterator.hasNext()) { CsvCell csvCell = (CsvCell)cellIterator.next(); + while (csvCell.getColumnIndex() > columnIndex++) { + csvPrinter.print(null); + } csvPrinter.print(buildCellValue(csvCell)); } csvPrinter.println(); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java index da6848a3..7a4dfe21 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java @@ -24,7 +24,7 @@ public class AnnotationDataTest { public static void init() { file07 = TestFileUtil.createNewFile("annotation07.xlsx"); file03 = TestFileUtil.createNewFile("annotation03.xls"); - fileCsv = TestFileUtil.createNewFile("annotation.csv"); + fileCsv = TestFileUtil.createNewFile("annotationCsv.csv"); } @Test @@ -38,8 +38,8 @@ public class AnnotationDataTest { } @Test - public void t02ReadAndWriteCsv() throws Exception { - //readAndWrite(fileCsv); + public void t03ReadAndWriteCsv() throws Exception { + readAndWrite(fileCsv); } private void readAndWrite(File file) throws Exception { diff --git a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataTest.java index cd069c81..5f12bb33 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataTest.java @@ -4,12 +4,12 @@ import java.io.File; 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 org.junit.BeforeClass; +import org.junit.Test; + /** * Annotation data test * @@ -19,11 +19,13 @@ public class AnnotationIndexAndNameDataTest { private static File file07; private static File file03; + private static File fileCsv; @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("annotationIndexAndName07.xlsx"); file03 = TestFileUtil.createNewFile("annotationIndexAndName03.xls"); + fileCsv = TestFileUtil.createNewFile("annotationIndexAndNameCsv.csv"); } @Test @@ -36,6 +38,11 @@ public class AnnotationIndexAndNameDataTest { readAndWrite(file03); } + @Test + public void t03ReadAndWrite03() { + readAndWrite(fileCsv); + } + private void readAndWrite(File file) { EasyExcel.write(file, AnnotationIndexAndNameData.class).sheet().doWrite(data()); EasyExcel.read(file, AnnotationIndexAndNameData.class, new AnnotationIndexAndNameDataListener()).sheet() From 06d3b4bba469caeb2e3cdd068d1ea2e45d7643fa Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 13 Sep 2021 12:14:47 +0800 Subject: [PATCH 099/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/metadata/AbstractHolder.java | 10 ++--- .../excel/metadata/GlobalConfiguration.java | 38 ++++--------------- .../metadata/holder/AbstractReadHolder.java | 18 ++++----- .../metadata/holder/AbstractWriteHolder.java | 11 ++---- .../AnnotationIndexAndNameDataTest.java | 2 +- .../test/core/celldata/CellDataDataTest.java | 9 +++++ 6 files changed, 34 insertions(+), 54 deletions(-) diff --git a/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java b/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java index ffb54559..90a1bbbe 100644 --- a/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java +++ b/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java @@ -1,7 +1,6 @@ package com.alibaba.excel.metadata; import java.util.List; -import java.util.Locale; import java.util.Map; import com.alibaba.excel.converters.Converter; @@ -55,19 +54,16 @@ public abstract class AbstractHolder implements ConfigurationHolder { } this.globalConfiguration = new GlobalConfiguration(); if (basicParameter.getAutoTrim() == null) { - if (prentAbstractHolder == null) { - globalConfiguration.setAutoTrim(Boolean.TRUE); - } else { + if (prentAbstractHolder != null) { globalConfiguration.setAutoTrim(prentAbstractHolder.getGlobalConfiguration().getAutoTrim()); } } else { globalConfiguration.setAutoTrim(basicParameter.getAutoTrim()); } + if (basicParameter.getLocale() == null) { - if (prentAbstractHolder == null) { - globalConfiguration.setLocale(Locale.getDefault()); - } else { + if (prentAbstractHolder != null) { globalConfiguration.setLocale(prentAbstractHolder.getGlobalConfiguration().getLocale()); } } else { diff --git a/src/main/java/com/alibaba/excel/metadata/GlobalConfiguration.java b/src/main/java/com/alibaba/excel/metadata/GlobalConfiguration.java index 26f3720f..987e553b 100644 --- a/src/main/java/com/alibaba/excel/metadata/GlobalConfiguration.java +++ b/src/main/java/com/alibaba/excel/metadata/GlobalConfiguration.java @@ -2,11 +2,14 @@ package com.alibaba.excel.metadata; import java.util.Locale; +import lombok.Data; + /** * Global configuration * * @author Jiaju Zhuang */ +@Data public class GlobalConfiguration { /** * Automatic trim includes sheet name and content @@ -32,35 +35,10 @@ public class GlobalConfiguration { */ private Boolean useScientificFormat; - public Boolean getUse1904windowing() { - return use1904windowing; - } - - public void setUse1904windowing(Boolean use1904windowing) { - this.use1904windowing = use1904windowing; - } - - public Boolean getAutoTrim() { - return autoTrim; - } - - public void setAutoTrim(Boolean autoTrim) { - this.autoTrim = autoTrim; - } - - public Locale getLocale() { - return locale; - } - - public void setLocale(Locale locale) { - this.locale = locale; - } - - public Boolean getUseScientificFormat() { - return useScientificFormat; - } - - public void setUseScientificFormat(Boolean useScientificFormat) { - this.useScientificFormat = useScientificFormat; + public GlobalConfiguration() { + this.autoTrim = Boolean.TRUE; + this.use1904windowing = Boolean.FALSE; + this.locale = Locale.getDefault(); + this.useScientificFormat = Boolean.FALSE; } } diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java index ab6dfb72..14a708b6 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java @@ -49,19 +49,20 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH public AbstractReadHolder(ReadBasicParameter readBasicParameter, AbstractReadHolder parentAbstractReadHolder, Boolean convertAllFiled) { super(readBasicParameter, parentAbstractReadHolder); - if (readBasicParameter.getUse1904windowing() == null && parentAbstractReadHolder != null) { - getGlobalConfiguration() - .setUse1904windowing(parentAbstractReadHolder.getGlobalConfiguration().getUse1904windowing()); + + if (readBasicParameter.getUse1904windowing() == null) { + if (parentAbstractReadHolder != null) { + getGlobalConfiguration() + .setUse1904windowing(parentAbstractReadHolder.getGlobalConfiguration().getUse1904windowing()); + } } else { getGlobalConfiguration().setUse1904windowing(readBasicParameter.getUse1904windowing()); } if (readBasicParameter.getUseScientificFormat() == null) { - if (parentAbstractReadHolder == null) { - getGlobalConfiguration().setUseScientificFormat(Boolean.FALSE); - } else { - getGlobalConfiguration() - .setUseScientificFormat(parentAbstractReadHolder.getGlobalConfiguration().getUseScientificFormat()); + if (parentAbstractReadHolder != null) { + getGlobalConfiguration().setUseScientificFormat( + parentAbstractReadHolder.getGlobalConfiguration().getUseScientificFormat()); } } else { getGlobalConfiguration().setUseScientificFormat(readBasicParameter.getUseScientificFormat()); @@ -114,7 +115,6 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH } } - @Override public List> readListenerList() { return getReadListenerList(); diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java index d667b1b3..4be4907b 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java @@ -96,10 +96,9 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ public AbstractWriteHolder(WriteBasicParameter writeBasicParameter, AbstractWriteHolder parentAbstractWriteHolder, Boolean convertAllField) { super(writeBasicParameter, parentAbstractWriteHolder); + if (writeBasicParameter.getUse1904windowing() == null) { - if (parentAbstractWriteHolder == null) { - getGlobalConfiguration().setUse1904windowing(Boolean.FALSE); - } else { + if (parentAbstractWriteHolder != null) { getGlobalConfiguration() .setUse1904windowing(parentAbstractWriteHolder.getGlobalConfiguration().getUse1904windowing()); } @@ -210,7 +209,6 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ } } - protected void initAnnotationConfig(List handlerList, WriteBasicParameter writeBasicParameter) { if (!HeadKindEnum.CLASS.equals(getExcelWriteHeadProperty().getHeadKind())) { return; @@ -310,7 +308,6 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ handlerList.add(columnWidthStyleStrategy); } - protected Map, List> sortAndClearUpAllHandler( List handlerList, Map, List> parentHandlerMap) { // add @@ -330,7 +327,7 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ for (WriteHandler handler : handlerList) { int order = Integer.MIN_VALUE; if (handler instanceof Order) { - order = ((Order) handler).order(); + order = ((Order)handler).order(); } if (orderExcelWriteHandlerMap.containsKey(order)) { orderExcelWriteHandlerMap.get(order).add(handler); @@ -346,7 +343,7 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ for (Map.Entry> entry : orderExcelWriteHandlerMap.entrySet()) { for (WriteHandler handler : entry.getValue()) { if (handler instanceof NotRepeatExecutor) { - String uniqueValue = ((NotRepeatExecutor) handler).uniqueValue(); + String uniqueValue = ((NotRepeatExecutor)handler).uniqueValue(); if (alreadyExistedHandlerSet.contains(uniqueValue)) { continue; } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataTest.java index 5f12bb33..937cf665 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataTest.java @@ -39,7 +39,7 @@ public class AnnotationIndexAndNameDataTest { } @Test - public void t03ReadAndWrite03() { + public void t03ReadAndWriteCsv() { readAndWrite(fileCsv); } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java index db4bf80b..0fd2f225 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataTest.java @@ -25,11 +25,14 @@ public class CellDataDataTest { private static File file07; private static File file03; + private static File fileCsv; + @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("cellData07.xlsx"); file03 = TestFileUtil.createNewFile("cellData03.xls"); + fileCsv = TestFileUtil.createNewFile("cellDataCsv.csv"); } @Test @@ -42,6 +45,12 @@ public class CellDataDataTest { readAndWrite(file03); } + @Test + public void t03ReadAndWriteCsv() throws Exception { + readAndWrite(fileCsv); + } + + private void readAndWrite(File file) throws Exception { EasyExcel.write(file, CellDataWriteData.class).sheet().doWrite(data()); EasyExcel.read(file, CellDataReadData.class, new CellDataDataListener()).sheet().doRead(); From 2fb54ca91e86a6474024f51180c4cf05a6f2a01d Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 13 Sep 2021 15:17:48 +0800 Subject: [PATCH 100/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=A9=BA=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E7=9A=84=E6=97=B6=E5=80=99=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../analysis/csv/CsvExcelReadExecutor.java | 16 +++++++++--- .../excel/metadata/AbstractHolder.java | 8 ++++++ .../excel/metadata/csv/CsvDataFormat.java | 4 +-- .../alibaba/excel/metadata/csv/CsvSheet.java | 4 ++- .../metadata/holder/AbstractReadHolder.java | 9 ------- .../holder/csv/CsvReadWorkbookHolder.java | 2 +- .../com/alibaba/excel/util/DateUtils.java | 2 +- .../executor/AbstractExcelWriteExecutor.java | 26 +++++++++++++++++++ .../metadata/holder/AbstractWriteHolder.java | 8 ------ .../core/celldata/CellDataDataListener.java | 9 +++++-- .../test/temp/csv/CsvDataListeer.java | 20 ++++++++++++++ .../easyexcel/test/temp/csv/CsvReadTest.java | 9 ++++--- 12 files changed, 85 insertions(+), 32 deletions(-) create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvDataListeer.java diff --git a/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java b/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java index 6f1353ca..e98b3580 100644 --- a/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java +++ b/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java @@ -20,6 +20,7 @@ import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.read.metadata.holder.ReadRowHolder; import com.alibaba.excel.read.metadata.holder.csv.CsvReadWorkbookHolder; import com.alibaba.excel.util.SheetUtils; +import com.alibaba.excel.util.StringUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.MapUtils; @@ -27,7 +28,7 @@ import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVRecord; /** - * azz + * read executor * * @author zhuangjiaju */ @@ -66,10 +67,11 @@ public class CsvExcelReadExecutor implements ExcelReadExecutor { csvReadContext.currentSheet(readSheet); int rowIndex = 0; - for (CSVRecord record : parseRecords) { + for (CSVRecord record : parseRecords) { dealRecord(record, rowIndex++); } + // The last sheet is read csvReadContext.analysisEventProcessor().endSheet(csvReadContext); } @@ -95,8 +97,14 @@ public class CsvExcelReadExecutor implements ExcelReadExecutor { while (cellIterator.hasNext()) { String cellString = cellIterator.next(); ReadCellData readCellData = new ReadCellData<>(); - readCellData.setType(CellDataTypeEnum.STRING); - readCellData.setStringValue(cellString); + + // csv is an empty string of whether ,, is read or ,"", + if (StringUtils.isNotBlank(cellString)) { + readCellData.setType(CellDataTypeEnum.STRING); + readCellData.setStringValue(cellString); + } else { + readCellData.setType(CellDataTypeEnum.EMPTY); + } cellMap.put(cellIndex++, readCellData); } diff --git a/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java b/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java index 90a1bbbe..735a0623 100644 --- a/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java +++ b/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java @@ -61,6 +61,14 @@ public abstract class AbstractHolder implements ConfigurationHolder { globalConfiguration.setAutoTrim(basicParameter.getAutoTrim()); } + if (basicParameter.getUse1904windowing() == null) { + if (prentAbstractHolder != null) { + globalConfiguration.setUse1904windowing( + prentAbstractHolder.getGlobalConfiguration().getUse1904windowing()); + } + } else { + globalConfiguration.setUse1904windowing(basicParameter.getUse1904windowing()); + } if (basicParameter.getLocale() == null) { if (prentAbstractHolder != null) { diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvDataFormat.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvDataFormat.java index 1dcc7c2e..42d3f043 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvDataFormat.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvDataFormat.java @@ -45,8 +45,8 @@ public class CsvDataFormat implements DataFormat { if (index != null) { return index; } + index = (short)(formatList.size() + BuiltinFormats.MIN_CUSTOM_DATA_FORMAT_INDEX); formatList.add(format); - index = (short)formatList.size(); formatMap.put(format, index); return index; } @@ -57,7 +57,7 @@ public class CsvDataFormat implements DataFormat { return builtinFormats[index]; } int actualIndex = index - BuiltinFormats.MIN_CUSTOM_DATA_FORMAT_INDEX; - if (actualIndex >= 0 && actualIndex < formatList.size()) { + if (actualIndex < formatList.size()) { return formatList.get(actualIndex); } return null; diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java index a54d0681..fe35ab82 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java @@ -748,7 +748,6 @@ public class CsvSheet implements Sheet, Closeable { switch (csvCell.getCellType()) { case STRING: case ERROR: - case FORMULA: return csvCell.getStringCellValue(); case NUMERIC: Short dataFormat = null; @@ -782,6 +781,9 @@ public class CsvSheet implements Sheet, Closeable { dataFormat = BuiltinFormats.GENERAL; dataFormatString = csvWorkbook.createDataFormat().getFormat(dataFormat); } + if (dataFormatString == null) { + dataFormatString = csvWorkbook.createDataFormat().getFormat(dataFormat); + } return NumberDataFormatterUtils.format(csvCell.getNumericCellValue(), dataFormat, dataFormatString, csvWorkbook.getUse1904windowing(), csvWorkbook.getLocale(), csvWorkbook.getUseScientificFormat()); diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java index 14a708b6..1b313939 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java @@ -50,15 +50,6 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH Boolean convertAllFiled) { super(readBasicParameter, parentAbstractReadHolder); - if (readBasicParameter.getUse1904windowing() == null) { - if (parentAbstractReadHolder != null) { - getGlobalConfiguration() - .setUse1904windowing(parentAbstractReadHolder.getGlobalConfiguration().getUse1904windowing()); - } - } else { - getGlobalConfiguration().setUse1904windowing(readBasicParameter.getUse1904windowing()); - } - if (readBasicParameter.getUseScientificFormat() == null) { if (parentAbstractReadHolder != null) { getGlobalConfiguration().setUseScientificFormat( diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/csv/CsvReadWorkbookHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/csv/CsvReadWorkbookHolder.java index 4e8de41f..8066fab6 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/csv/CsvReadWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/csv/CsvReadWorkbookHolder.java @@ -20,6 +20,6 @@ public class CsvReadWorkbookHolder extends ReadWorkbookHolder { public CsvReadWorkbookHolder(ReadWorkbook readWorkbook) { super(readWorkbook); setExcelType(ExcelTypeEnum.CSV); - csvFormat = CSVFormat.DEFAULT; + this.csvFormat = CSVFormat.DEFAULT; } } diff --git a/src/main/java/com/alibaba/excel/util/DateUtils.java b/src/main/java/com/alibaba/excel/util/DateUtils.java index bc85adf6..68eb01c0 100644 --- a/src/main/java/com/alibaba/excel/util/DateUtils.java +++ b/src/main/java/com/alibaba/excel/util/DateUtils.java @@ -133,7 +133,7 @@ public class DateUtils { */ public static String format(Date date, String dateFormat) { if (date == null) { - return ""; + return null; } if (StringUtils.isEmpty(dateFormat)) { dateFormat = defaultDateFormat; diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index 44ba04ee..0c632b6e 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -17,8 +17,10 @@ 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.DateUtils; import com.alibaba.excel.util.FileTypeUtils; import com.alibaba.excel.util.StyleUtil; +import com.alibaba.excel.util.WorkBookUtil; import com.alibaba.excel.util.WriteHandlerUtils; import com.alibaba.excel.write.metadata.holder.WriteHolder; import com.alibaba.excel.write.metadata.style.WriteCellStyle; @@ -231,6 +233,9 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { } WriteCellData cellDataValue = (WriteCellData)value; if (cellDataValue.getType() != null) { + // Configuration information may not be read here + fillProperty(cellDataValue, excelContentProperty); + return cellDataValue; } else { if (cellDataValue.getData() == null) { @@ -262,6 +267,27 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { return doConvert(currentWriteHolder, clazz, targetType, cell, value, excelContentProperty); } + private void fillProperty(WriteCellData cellDataValue, ExcelContentProperty excelContentProperty) { + switch (cellDataValue.getType()) { + case DATE: + String dateFormat = null; + if (excelContentProperty != null && excelContentProperty.getDateTimeFormatProperty() != null) { + dateFormat = excelContentProperty.getDateTimeFormatProperty().getFormat(); + } + WorkBookUtil.fillDataFormat(cellDataValue, dateFormat, DateUtils.defaultDateFormat); + return; + case NUMBER: + String numberFormat = null; + if (excelContentProperty != null && excelContentProperty.getNumberFormatProperty() != null) { + numberFormat = excelContentProperty.getNumberFormatProperty().getFormat(); + } + WorkBookUtil.fillDataFormat(cellDataValue, numberFormat, null); + return; + default: + return; + } + } + private WriteCellData doConvert(WriteHolder currentWriteHolder, Class clazz, CellDataTypeEnum targetType, Cell cell, Object value, ExcelContentProperty excelContentProperty) { Converter converter = null; diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java index 4be4907b..96d55396 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java @@ -97,14 +97,6 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ Boolean convertAllField) { super(writeBasicParameter, parentAbstractWriteHolder); - if (writeBasicParameter.getUse1904windowing() == null) { - if (parentAbstractWriteHolder != null) { - getGlobalConfiguration() - .setUse1904windowing(parentAbstractWriteHolder.getGlobalConfiguration().getUse1904windowing()); - } - } else { - getGlobalConfiguration().setUse1904windowing(writeBasicParameter.getUse1904windowing()); - } if (writeBasicParameter.getUseScientificFormat() != null) { throw new UnsupportedOperationException("Currently does not support setting useScientificFormat."); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java index cb6a1105..626f801e 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java @@ -5,6 +5,7 @@ import java.util.List; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; +import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.fastjson.JSON; import org.junit.Assert; @@ -28,10 +29,14 @@ public class CellDataDataListener extends AnalysisEventListener { + @Override + public void invoke(CsvData data, AnalysisContext context) { + log.info("data:{}", JSON.toJSONString(data)); + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java index d6f8fb2a..ebc910d1 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java @@ -5,7 +5,6 @@ import java.io.FileInputStream; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; -import java.util.Date; import java.util.List; import com.alibaba.easyexcel.test.util.TestFileUtil; @@ -38,8 +37,8 @@ public class CsvReadTest { @Test public void read1() throws Exception { - Iterable records = CSVFormat.DEFAULT.parse( - new FileReader("/Users/zhuangjiaju/IdeaProjects/easyexcel/target/test-classes/csvWrite1.csv")); + Iterable records = CSVFormat.DEFAULT.withNullString("").parse( + new FileReader("/Users/zhuangjiaju/IdeaProjects/easyexcel/target/test-classes/t1.csv")); for (CSVRecord record : records) { String lastName = record.get(0); String firstName = record.get(1); @@ -71,6 +70,8 @@ public class CsvReadTest { // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 // 如果这里想使用03 则 传入excelType参数即可 EasyExcel.write(fileName, CsvData.class).sheet().doWrite(data()); + + EasyExcel.read(fileName, CsvData.class, new CsvDataListeer()).sheet().doRead(); } @Test @@ -85,7 +86,7 @@ public class CsvReadTest { for (int i = 0; i < 10; i++) { CsvData data = new CsvData(); data.setString("字符,串" + i); - data.setDate(new Date()); + //data.setDate(new Date()); data.setDoubleData(0.56); data.setIgnore("忽略" + i); list.add(data); From 729bda5d0ecd39aebb9524b3251b89c6a1baf4ff Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 13 Sep 2021 17:29:56 +0800 Subject: [PATCH 101/129] =?UTF-8?q?=E5=AE=8C=E6=88=90=E9=83=A8=E5=88=86csv?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E6=A1=88=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../analysis/csv/CsvExcelReadExecutor.java | 6 ++- .../listener/ModelBuildEventListener.java | 11 ---- .../alibaba/excel/util/ConverterUtils.java | 9 ++++ .../alibaba/excel/write/ExcelBuilderImpl.java | 14 +++-- .../executor/AbstractExcelWriteExecutor.java | 6 +-- .../core/celldata/CellDataDataListener.java | 2 +- .../core/converter/ConverterDataTest.java | 23 ++++++--- .../ReadAllConverterDataListener.java | 17 ++++--- .../test/core/dataformat/DateFormatTest.java | 13 +++-- .../core/exception/ExceptionDataTest.java | 14 +++-- .../ExcludeOrIncludeDataTest.java | 51 ++++++++++++++----- .../test/core/handler/WriteHandlerTest.java | 39 +++++++++----- src/test/resources/converter/converterCsv.csv | 2 + 13 files changed, 132 insertions(+), 75 deletions(-) create mode 100644 src/test/resources/converter/converterCsv.csv diff --git a/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java b/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java index e98b3580..d411ef0d 100644 --- a/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java +++ b/src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java @@ -93,10 +93,12 @@ public class CsvExcelReadExecutor implements ExcelReadExecutor { private void dealRecord(CSVRecord record, int rowIndex) { Map cellMap = new LinkedHashMap<>(); Iterator cellIterator = record.iterator(); - int cellIndex = 0; + int columnIndex = 0; while (cellIterator.hasNext()) { String cellString = cellIterator.next(); ReadCellData readCellData = new ReadCellData<>(); + readCellData.setRowIndex(rowIndex); + readCellData.setColumnIndex(columnIndex); // csv is an empty string of whether ,, is read or ,"", if (StringUtils.isNotBlank(cellString)) { @@ -105,7 +107,7 @@ public class CsvExcelReadExecutor implements ExcelReadExecutor { } else { readCellData.setType(CellDataTypeEnum.EMPTY); } - cellMap.put(cellIndex++, readCellData); + cellMap.put(columnIndex++, readCellData); } RowTypeEnum rowType = MapUtils.isEmpty(cellMap) ? RowTypeEnum.EMPTY : RowTypeEnum.DATA; diff --git a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java index 9feb1515..adfa6589 100644 --- a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java +++ b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java @@ -53,10 +53,6 @@ public class ModelBuildEventListener implements ReadListener cellData = cellDataMap.get(index); - if (cellData.getType() == CellDataTypeEnum.EMPTY) { - continue; - } ExcelContentProperty excelContentProperty = contentPropertyMap.get(index); Object value = ConverterUtils.convertToJavaObject(cellData, excelContentProperty.getField(), excelContentProperty, readSheetHolder.converterMap(), context, diff --git a/src/main/java/com/alibaba/excel/util/ConverterUtils.java b/src/main/java/com/alibaba/excel/util/ConverterUtils.java index e0e139f7..b666be6e 100644 --- a/src/main/java/com/alibaba/excel/util/ConverterUtils.java +++ b/src/main/java/com/alibaba/excel/util/ConverterUtils.java @@ -8,6 +8,7 @@ import java.util.Map; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.ConverterKeyBuild; +import com.alibaba.excel.converters.NullableObjectConverter; import com.alibaba.excel.converters.ReadConverterContext; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.exception.ExcelDataConvertException; @@ -131,6 +132,13 @@ public class ConverterUtils { if (contentProperty != null) { converter = contentProperty.getConverter(); } + + boolean canNotConverterEmpty = cellData.getType() == CellDataTypeEnum.EMPTY + && !(converter instanceof NullableObjectConverter); + if (canNotConverterEmpty) { + return null; + } + if (converter == null) { converter = converterMap.get(ConverterKeyBuild.buildKey(clazz, cellData.getType())); } @@ -138,6 +146,7 @@ public class ConverterUtils { throw new ExcelDataConvertException(rowIndex, columnIndex, cellData, contentProperty, "Converter not found, convert " + cellData.getType() + " to " + clazz.getName()); } + try { return converter.convertToJavaData(new ReadConverterContext<>(cellData, contentProperty, context)); } catch (Exception e) { diff --git a/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java b/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java index e172140d..d6503c6c 100644 --- a/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java +++ b/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java @@ -1,19 +1,12 @@ package com.alibaba.excel.write; -import java.lang.reflect.Field; import java.util.Collection; -import java.util.List; - -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFSheet; import com.alibaba.excel.context.WriteContext; import com.alibaba.excel.context.WriteContextImpl; import com.alibaba.excel.enums.WriteTypeEnum; import com.alibaba.excel.exception.ExcelGenerateException; -import com.alibaba.excel.util.FieldUtils; +import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.write.executor.ExcelWriteAddExecutor; import com.alibaba.excel.write.executor.ExcelWriteFillExecutor; @@ -22,6 +15,8 @@ import com.alibaba.excel.write.metadata.WriteTable; import com.alibaba.excel.write.metadata.WriteWorkbook; import com.alibaba.excel.write.metadata.fill.FillConfig; +import org.apache.poi.ss.util.CellRangeAddress; + /** * @author jipengfei */ @@ -77,6 +72,9 @@ public class ExcelBuilderImpl implements ExcelBuilder { if (context.writeWorkbookHolder().getTempTemplateInputStream() == null) { throw new ExcelGenerateException("Calling the 'fill' method must use a template."); } + if (context.writeWorkbookHolder().getExcelType() == ExcelTypeEnum.CSV) { + throw new ExcelGenerateException("csv does not support filling data."); + } context.currentSheet(writeSheet, WriteTypeEnum.FILL); if (excelWriteFillExecutor == null) { excelWriteFillExecutor = new ExcelWriteFillExecutor(context); diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index 0c632b6e..dfd327c1 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -301,14 +301,14 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { } converter = currentWriteHolder.converterMap().get(ConverterKeyBuild.buildKey(clazz, targetType)); } + if (value == null && !(converter instanceof NullableObjectConverter)) { + return new WriteCellData<>(CellDataTypeEnum.EMPTY); + } if (converter == null) { throw new ExcelDataConvertException(cell.getRow().getRowNum(), cell.getColumnIndex(), new WriteCellData<>(CellDataTypeEnum.EMPTY), excelContentProperty, "Can not find 'Converter' support class " + clazz.getSimpleName() + "."); } - if (value == null && !(converter instanceof NullableObjectConverter)) { - return new WriteCellData<>(CellDataTypeEnum.EMPTY); - } WriteCellData cellData; try { cellData = ((Converter)converter).convertToExcelData( diff --git a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java index 626f801e..35829e0e 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/celldata/CellDataDataListener.java @@ -35,7 +35,7 @@ public class CellDataDataListener extends AnalysisEventListener list = new ArrayList(); + List list = new ArrayList<>(); ImageData imageData = new ImageData(); list.add(imageData); String imagePath = TestFileUtil.getPath() + "converter" + File.separator + "img.jpg"; diff --git a/src/test/java/com/alibaba/easyexcel/test/core/converter/ReadAllConverterDataListener.java b/src/test/java/com/alibaba/easyexcel/test/core/converter/ReadAllConverterDataListener.java index d5da81ad..4a11f8b8 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/converter/ReadAllConverterDataListener.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/converter/ReadAllConverterDataListener.java @@ -5,16 +5,17 @@ import java.text.ParseException; 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.excel.exception.ExcelCommonException; +import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.util.DateUtils; import com.alibaba.fastjson.JSON; +import org.junit.Assert; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * @author Jiaju Zhuang */ @@ -61,10 +62,14 @@ public class ReadAllConverterDataListener extends AnalysisEventListener excludeColumnIndexes = new HashSet(); @@ -147,7 +171,6 @@ public class ExcludeOrIncludeDataTest { Assert.assertEquals("column3", record.get(1)); } - private List data() { List list = new ArrayList(); ExcludeOrIncludeData excludeOrIncludeData = new ExcludeOrIncludeData(); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandlerTest.java b/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandlerTest.java index a96d133e..a3354f35 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandlerTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/handler/WriteHandlerTest.java @@ -1,22 +1,17 @@ package com.alibaba.easyexcel.test.core.handler; import java.io.File; -import java.text.ParseException; import java.util.ArrayList; import java.util.List; +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; + import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; -import com.alibaba.easyexcel.test.core.head.ListHeadDataListener; -import com.alibaba.easyexcel.test.core.simple.SimpleData; -import com.alibaba.easyexcel.test.util.TestFileUtil; -import com.alibaba.excel.EasyExcel; -import com.alibaba.excel.util.DateUtils; -import com.alibaba.excel.write.handler.WorkbookWriteHandler; - /** * * @author Jiaju Zhuang @@ -26,11 +21,14 @@ public class WriteHandlerTest { private static File file07; private static File file03; + private static File fileCsv; + @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("writeHandler07.xlsx"); file03 = TestFileUtil.createNewFile("writeHandler03.xls"); + fileCsv = TestFileUtil.createNewFile("writeHandlerCsv.csv"); } @Test @@ -44,27 +42,42 @@ public class WriteHandlerTest { } @Test - public void t03SheetWrite07() throws Exception { + public void t03WorkbookWriteCsv() throws Exception { + workbookWrite(fileCsv); + } + + + @Test + public void t11SheetWrite07() throws Exception { sheetWrite(file07); } @Test - public void t04SheetWrite03() throws Exception { + public void t12SheetWrite03() throws Exception { sheetWrite(file03); } @Test - public void t05TableWrite07() throws Exception { - workbookWrite(file07); + public void t13SheetWriteCsv() throws Exception { + sheetWrite(fileCsv); + } + + @Test + public void t21TableWrite07() throws Exception { tableWrite(file07); } @Test - public void t06TableWrite03() throws Exception { + public void t22TableWrite03() throws Exception { tableWrite(file03); } + @Test + public void t23TableWriteCsv() throws Exception { + tableWrite(fileCsv); + } + private void workbookWrite(File file) { WriteHandler writeHandler = new WriteHandler(); EasyExcel.write(file).head(WriteHandlerData.class).registerWriteHandler(writeHandler).sheet().doWrite(data()); diff --git a/src/test/resources/converter/converterCsv.csv b/src/test/resources/converter/converterCsv.csv new file mode 100644 index 00000000..c61f06ca --- /dev/null +++ b/src/test/resources/converter/converterCsv.csv @@ -0,0 +1,2 @@ +大数的布尔(不支持),大数的数字,大数的字符串,布尔的布尔,布尔的数字(不支持),布尔的字符串,字节的布尔(不支持),字节的数字,字节的字符串,日期的数字,日期的字符串,双精度浮点的布尔(不支持),双精度浮点的数字,双精度浮点的字符串,浮点的布尔(不支持),浮点的数字,浮点的字符串,整型的布尔(不支持),整型的数字,整型的字符串,长整型的布尔(不支持),长整型的数字,长整型的字符串,短整型的布尔(不支持),短整型的数字,短整型的字符串,字符串的布尔,字符串的数字,字符串的字符串,字符串的错误,字符串的数字公式,字符串的字符串公式,字符串的数字日期 +1,1,1,TRUE,TRUE,TRUE,1,1,1,2020-01-01 01:01:01,2020-01-01 01:01:01,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,TRUE,1,测试,#VALUE!,2,1测试,2020-01-01 01:01:01 \ No newline at end of file From c1396b278aae7db933f1210aa78a1a82eb38b60e Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 13 Sep 2021 18:55:23 +0800 Subject: [PATCH 102/129] =?UTF-8?q?=E5=AE=8C=E6=88=90large=E6=B5=8B?= =?UTF-8?q?=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test/core/head/ComplexHeadDataTest.java | 34 ++++++++++++----- .../test/core/head/ListHeadDataTest.java | 17 +++++++-- .../test/core/head/NoHeadDataTest.java | 17 +++++++-- .../test/core/large/LargeDataListener.java | 17 ++++++--- .../test/core/large/LargeDataTest.java | 38 +++++++++++++++---- 5 files changed, 93 insertions(+), 30 deletions(-) diff --git a/src/test/java/com/alibaba/easyexcel/test/core/head/ComplexHeadDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/head/ComplexHeadDataTest.java index 25f7fed5..07340c3b 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/head/ComplexHeadDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/head/ComplexHeadDataTest.java @@ -4,29 +4,35 @@ import java.io.File; 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 org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + /** - * * @author Jiaju Zhuang */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ComplexHeadDataTest { private static File file07; private static File file03; + private static File fileCsv; private static File file07AutomaticMergeHead; private static File file03AutomaticMergeHead; + private static File fileCsvAutomaticMergeHead; @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("complexHead07.xlsx"); file03 = TestFileUtil.createNewFile("complexHead03.xls"); + fileCsv = TestFileUtil.createNewFile("complexHeadCsv.csv"); file07AutomaticMergeHead = TestFileUtil.createNewFile("complexHeadAutomaticMergeHead07.xlsx"); file03AutomaticMergeHead = TestFileUtil.createNewFile("complexHeadAutomaticMergeHead03.xls"); + fileCsvAutomaticMergeHead = TestFileUtil.createNewFile("complexHeadAutomaticMergeHeadCsv.csv"); } @Test @@ -39,6 +45,11 @@ public class ComplexHeadDataTest { readAndWrite(file03); } + @Test + public void t03ReadAndWriteCsv() { + readAndWrite(fileCsv); + } + private void readAndWrite(File file) { EasyExcel.write(file, ComplexHeadData.class).sheet().doWrite(data()); EasyExcel.read(file, ComplexHeadData.class, new ComplexDataListener()) @@ -46,16 +57,21 @@ public class ComplexHeadDataTest { } @Test - public void t03ReadAndWriteAutomaticMergeHead07() { - readAndWriteAutomaticMergeHead07(file07AutomaticMergeHead); + public void t11ReadAndWriteAutomaticMergeHead07() { + readAndWriteAutomaticMergeHead(file07AutomaticMergeHead); + } + + @Test + public void t12ReadAndWriteAutomaticMergeHead03() { + readAndWriteAutomaticMergeHead(file03AutomaticMergeHead); } @Test - public void t04ReadAndWriteAutomaticMergeHead0703() { - readAndWriteAutomaticMergeHead07(file03AutomaticMergeHead); + public void t13ReadAndWriteAutomaticMergeHeadCsv() { + readAndWriteAutomaticMergeHead(fileCsvAutomaticMergeHead); } - private void readAndWriteAutomaticMergeHead07(File file) { + private void readAndWriteAutomaticMergeHead(File file) { EasyExcel.write(file, ComplexHeadData.class).automaticMergeHead(Boolean.FALSE).sheet().doWrite(data()); EasyExcel.read(file, ComplexHeadData.class, new ComplexDataListener()).sheet().doRead(); } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/head/ListHeadDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/head/ListHeadDataTest.java index 6e63a0b3..073c0e9c 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/head/ListHeadDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/head/ListHeadDataTest.java @@ -5,26 +5,32 @@ import java.text.ParseException; 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.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) public class ListHeadDataTest { private static File file07; private static File file03; + private static File fileCsv; + @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("listHead07.xlsx"); file03 = TestFileUtil.createNewFile("listHead03.xls"); + fileCsv = TestFileUtil.createNewFile("listHeadCsv.csv"); } @Test @@ -37,6 +43,11 @@ public class ListHeadDataTest { readAndWrite(file03); } + @Test + public void t03ReadAndWriteCsv() throws Exception { + readAndWrite(fileCsv); + } + private void readAndWrite(File file) throws Exception { EasyExcel.write(file).head(head()).sheet().doWrite(data()); EasyExcel.read(file).registerReadListener(new ListHeadDataListener()).sheet().doRead(); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/head/NoHeadDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/head/NoHeadDataTest.java index a62adbb8..b08e4630 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/head/NoHeadDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/head/NoHeadDataTest.java @@ -4,25 +4,29 @@ import java.io.File; 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 org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + /** - * * @author Jiaju Zhuang */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) public class NoHeadDataTest { private static File file07; private static File file03; + private static File fileCsv; @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("noHead07.xlsx"); file03 = TestFileUtil.createNewFile("noHead03.xls"); + fileCsv = TestFileUtil.createNewFile("noHeadCsv.csv"); } @Test @@ -35,6 +39,11 @@ public class NoHeadDataTest { readAndWrite(file03); } + @Test + public void t03ReadAndWriteCsv() { + readAndWrite(fileCsv); + } + private void readAndWrite(File file) { EasyExcel.write(file, NoHeadData.class).needHead(Boolean.FALSE).sheet().doWrite(data()); EasyExcel.read(file, NoHeadData.class, new NoHeadDataListener()).headRowNumber(0).sheet().doRead(); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/large/LargeDataListener.java b/src/test/java/com/alibaba/easyexcel/test/core/large/LargeDataListener.java index 23a8843c..dafe25fa 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/large/LargeDataListener.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/large/LargeDataListener.java @@ -1,13 +1,14 @@ package com.alibaba.easyexcel.test.core.large; -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.excel.support.ExcelTypeEnum; import com.alibaba.fastjson.JSON; +import org.junit.Assert; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * @author Jiaju Zhuang */ @@ -22,13 +23,17 @@ public class LargeDataListener extends AnalysisEventListener { } count++; if (count % 100000 == 0) { - LOGGER.info("Already read:{}", count); + LOGGER.info("Already read:{},{}", count, JSON.toJSONString(data)); } } @Override public void doAfterAllAnalysed(AnalysisContext context) { LOGGER.info("Large row count:{}", count); - Assert.assertEquals(count, 464509); + if (context.readWorkbookHolder().getExcelType() != ExcelTypeEnum.CSV) { + Assert.assertEquals(count, 464509); + } else { + Assert.assertEquals(count, 499999); + } } } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/large/LargeDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/large/LargeDataTest.java index fa32433a..957894e2 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/large/LargeDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/large/LargeDataTest.java @@ -4,31 +4,34 @@ import java.io.File; import java.util.ArrayList; import java.util.List; -import org.junit.BeforeClass; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.alibaba.easyexcel.test.demo.write.DemoData; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.write.metadata.WriteSheet; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** - * * @author Jiaju Zhuang */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) public class LargeDataTest { private static final Logger LOGGER = LoggerFactory.getLogger(LargeDataTest.class); private static File fileFill07; private static File template07; + private static File fileCsv; private int i = 0; @BeforeClass public static void init() { fileFill07 = TestFileUtil.createNewFile("largefill07.xlsx"); template07 = TestFileUtil.readFile("large" + File.separator + "fill.xlsx"); + fileCsv = TestFileUtil.createNewFile("largefileCsv.csv"); } @Test @@ -50,8 +53,27 @@ public class LargeDataTest { excelWriter.finish(); } + @Test + public void t03ReadAndWriteCsv() { + // write + long start = System.currentTimeMillis(); + ExcelWriter excelWriter = EasyExcel.write(fileCsv).build(); + WriteSheet writeSheet = EasyExcel.writerSheet().build(); + for (int j = 0; j < 100; j++) { + excelWriter.write(data(), writeSheet); + LOGGER.info("{} write success.", j); + } + excelWriter.finish(); + LOGGER.info("CSV large data total time spent:{}", System.currentTimeMillis() - start); + + // read + start = System.currentTimeMillis(); + EasyExcel.read(fileCsv, LargeData.class, new LargeDataListener()).sheet().doRead(); + LOGGER.info("CSV large data total time spent:{}", System.currentTimeMillis() - start); + } + private List data() { - List list = new ArrayList(); + List list = new ArrayList<>(); int size = i + 5000; for (; i < size; i++) { LargeData largeData = new LargeData(); From fce94542a47bc891b0305e3d2b8d89a136e02df3 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 13 Sep 2021 19:58:57 +0800 Subject: [PATCH 103/129] =?UTF-8?q?=E5=AE=8C=E6=88=90csv=20=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E6=A1=88=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/excel/util/WorkBookUtil.java | 5 +- .../MultipleSheetsDataTest.java | 12 ++-- .../test/core/nomodel/NoModelDataTest.java | 10 +++ .../test/core/noncamel/UnCamelDataTest.java | 8 +++ .../core/parameter/ParameterDataTest.java | 70 ++++++++++++------- .../core/repetition/RepetitionDataTest.java | 29 +++++--- .../test/core/simple/SimpleDataTest.java | 23 ++++-- .../test/core/skip/SkipDataTest.java | 27 ++++--- .../test/core/sort/SortDataTest.java | 24 +++++-- .../test/core/style/StyleDataTest.java | 2 +- .../test/core/template/TemplateDataTest.java | 7 +- .../easyexcel/test/temp/csv/CsvReadTest.java | 5 +- 12 files changed, 151 insertions(+), 71 deletions(-) diff --git a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java index 3e9732a9..71e1fd54 100644 --- a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java +++ b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java @@ -2,6 +2,7 @@ package com.alibaba.excel.util; import java.io.IOException; import java.io.OutputStreamWriter; +import java.io.PrintWriter; import com.alibaba.excel.metadata.csv.CsvWorkbook; import com.alibaba.excel.metadata.data.DataFormatData; @@ -67,8 +68,8 @@ public class WorkBookUtil { } return; case CSV: - CsvWorkbook csvWorkbook = new CsvWorkbook( - new OutputStreamWriter(writeWorkbookHolder.getOutputStream(), writeWorkbookHolder.getCharset()), + CsvWorkbook csvWorkbook = new CsvWorkbook(new PrintWriter( + new OutputStreamWriter(writeWorkbookHolder.getOutputStream(), writeWorkbookHolder.getCharset())), writeWorkbookHolder.getGlobalConfiguration().getLocale(), writeWorkbookHolder.getGlobalConfiguration().getUse1904windowing(), writeWorkbookHolder.getGlobalConfiguration().getUseScientificFormat()); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/multiplesheets/MultipleSheetsDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/multiplesheets/MultipleSheetsDataTest.java index 44e2f55b..c69e3ae4 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/multiplesheets/MultipleSheetsDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/multiplesheets/MultipleSheetsDataTest.java @@ -3,17 +3,17 @@ package com.alibaba.easyexcel.test.core.multiplesheets; import java.io.File; import java.util.List; +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.ExcelReader; +import com.alibaba.excel.read.metadata.ReadSheet; + import org.junit.Assert; 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.ExcelReader; -import com.alibaba.excel.read.metadata.ReadSheet; - /** * * @author Jiaju Zhuang @@ -57,7 +57,7 @@ public class MultipleSheetsDataTest { int count = 1; for (ReadSheet readSheet : sheets) { excelReader.read(readSheet); - Assert.assertEquals((long)multipleSheetsListener.getList().size(), (long)count); + Assert.assertEquals(multipleSheetsListener.getList().size(), count); count++; } excelReader.finish(); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java index 1a0cf088..262ae35d 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/nomodel/NoModelDataTest.java @@ -23,15 +23,20 @@ public class NoModelDataTest { private static File file07; private static File file03; + private static File fileCsv; private static File fileRepeat07; private static File fileRepeat03; + private static File fileRepeatCsv; + @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("noModel07.xlsx"); file03 = TestFileUtil.createNewFile("noModel03.xls"); + fileCsv = TestFileUtil.createNewFile("noModelCsv.csv"); fileRepeat07 = TestFileUtil.createNewFile("noModelRepeat07.xlsx"); fileRepeat03 = TestFileUtil.createNewFile("noModelRepeat03.xls"); + fileRepeatCsv = TestFileUtil.createNewFile("noModelRepeatCsv.csv"); } @Test @@ -44,6 +49,11 @@ public class NoModelDataTest { readAndWrite(file03, fileRepeat03); } + @Test + public void t03ReadAndWriteCsv() throws Exception { + readAndWrite(fileCsv, fileRepeatCsv); + } + private void readAndWrite(File file, File fileRepeat) throws Exception { EasyExcel.write(file).sheet().doWrite(data()); List> result = EasyExcel.read(file).headRowNumber(0).sheet().doReadSync(); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataTest.java index 689c9f8a..e8696c5a 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/noncamel/UnCamelDataTest.java @@ -20,11 +20,14 @@ public class UnCamelDataTest { private static File file07; private static File file03; + private static File fileCsv; + @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("unCame07.xlsx"); file03 = TestFileUtil.createNewFile("unCame03.xls"); + fileCsv = TestFileUtil.createNewFile("unCameCsv.csv"); } @Test @@ -37,6 +40,11 @@ public class UnCamelDataTest { readAndWrite(file03); } + @Test + public void t03ReadAndWriteCsv() { + readAndWrite(fileCsv); + } + private void readAndWrite(File file) { EasyExcel.write(file, UnCamelData.class).sheet().doWrite(data()); EasyExcel.read(file, UnCamelData.class, new UnCamelDataListener()).sheet().doRead(); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterDataTest.java index c7c305de..4e0f2a09 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterDataTest.java @@ -5,11 +5,6 @@ import java.io.FileOutputStream; 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.ExcelReader; @@ -17,59 +12,79 @@ import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.cache.MapCache; import com.alibaba.excel.converters.string.StringStringConverter; import com.alibaba.excel.read.metadata.ReadSheet; +import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.metadata.WriteTable; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + /** - * * @author Jiaju Zhuang */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ParameterDataTest { - private static File file; + private static File file07; + private static File fileCsv; @BeforeClass public static void init() { - file = TestFileUtil.createNewFile("parameter07.xlsx"); + file07 = TestFileUtil.createNewFile("parameter07.xlsx"); + fileCsv = TestFileUtil.createNewFile("parameterCsv.csv"); } @Test public void t01ReadAndWrite() throws Exception { - readAndWrite1(); - readAndWrite2(); - readAndWrite3(); - readAndWrite4(); - readAndWrite5(); - readAndWrite6(); - readAndWrite7(); + readAndWrite1(file07, ExcelTypeEnum.XLSX); + readAndWrite2(file07, ExcelTypeEnum.XLSX); + readAndWrite3(file07, ExcelTypeEnum.XLSX); + readAndWrite4(file07, ExcelTypeEnum.XLSX); + readAndWrite5(file07, ExcelTypeEnum.XLSX); + readAndWrite6(file07, ExcelTypeEnum.XLSX); + readAndWrite7(file07, ExcelTypeEnum.XLSX); } - private void readAndWrite1() { + @Test + public void t02ReadAndWrite() throws Exception { + readAndWrite1(fileCsv, ExcelTypeEnum.CSV); + readAndWrite2(fileCsv, ExcelTypeEnum.CSV); + readAndWrite3(fileCsv, ExcelTypeEnum.CSV); + readAndWrite4(fileCsv, ExcelTypeEnum.CSV); + readAndWrite5(fileCsv, ExcelTypeEnum.CSV); + readAndWrite6(fileCsv, ExcelTypeEnum.CSV); + readAndWrite7(fileCsv, ExcelTypeEnum.CSV); + } + + private void readAndWrite1(File file, ExcelTypeEnum type) { EasyExcel.write(file.getPath()).head(ParameterData.class).sheet().doWrite(data()); EasyExcel.read(file.getPath()).head(ParameterData.class).registerReadListener(new ParameterDataListener()) .sheet().doRead(); } - private void readAndWrite2() { + private void readAndWrite2(File file, ExcelTypeEnum type) { EasyExcel.write(file.getPath(), ParameterData.class).sheet().doWrite(data()); EasyExcel.read(file.getPath(), ParameterData.class, new ParameterDataListener()).sheet().doRead(); } - private void readAndWrite3() throws Exception { - EasyExcel.write(new FileOutputStream(file)).head(ParameterData.class).sheet().doWrite(data()); + private void readAndWrite3(File file, ExcelTypeEnum type) throws Exception { + EasyExcel.write(new FileOutputStream(file)).excelType(type).head(ParameterData.class).sheet() + .doWrite(data()); EasyExcel.read(file.getPath()).head(ParameterData.class).registerReadListener(new ParameterDataListener()) .sheet().doRead(); } - private void readAndWrite4() throws Exception { - EasyExcel.write(new FileOutputStream(file), ParameterData.class).sheet().doWrite(data()); + private void readAndWrite4(File file, ExcelTypeEnum type) throws Exception { + EasyExcel.write(new FileOutputStream(file), ParameterData.class).excelType(type).sheet().doWrite(data()); EasyExcel.read(file.getPath(), new ParameterDataListener()).head(ParameterData.class).sheet().doRead(); } - private void readAndWrite5() throws Exception { + private void readAndWrite5(File file, ExcelTypeEnum type) throws Exception { ExcelWriter excelWriter = - EasyExcel.write(new FileOutputStream(file)).head(ParameterData.class).relativeHeadRowIndex(0).build(); + EasyExcel.write(new FileOutputStream(file)).excelType(type).head(ParameterData.class).relativeHeadRowIndex( + 0).build(); WriteSheet writeSheet = EasyExcel.writerSheet(0).relativeHeadRowIndex(0).needHead(Boolean.FALSE).build(); WriteTable writeTable = EasyExcel.writerTable(0).relativeHeadRowIndex(0).needHead(Boolean.TRUE).build(); excelWriter.write(data(), writeSheet, writeTable); @@ -88,9 +103,10 @@ public class ParameterDataTest { excelReader.finish(); } - private void readAndWrite6() throws Exception { + private void readAndWrite6(File file, ExcelTypeEnum type) throws Exception { ExcelWriter excelWriter = - EasyExcel.write(new FileOutputStream(file)).head(ParameterData.class).relativeHeadRowIndex(0).build(); + EasyExcel.write(new FileOutputStream(file)).excelType(type).head(ParameterData.class).relativeHeadRowIndex( + 0).build(); WriteSheet writeSheet = EasyExcel.writerSheet(0).relativeHeadRowIndex(0).needHead(Boolean.FALSE).build(); WriteTable writeTable = EasyExcel.writerTable(0).registerConverter(new StringStringConverter()) .relativeHeadRowIndex(0).needHead(Boolean.TRUE).build(); @@ -110,7 +126,7 @@ public class ParameterDataTest { excelReader.finish(); } - private void readAndWrite7() { + private void readAndWrite7(File file, ExcelTypeEnum type) { EasyExcel.write(file, ParameterData.class).registerConverter(new StringStringConverter()).sheet() .registerConverter(new StringStringConverter()).needHead(Boolean.FALSE).table(0).needHead(Boolean.TRUE) .doWrite(data()); @@ -119,7 +135,7 @@ public class ParameterDataTest { } private List data() { - List list = new ArrayList(); + List list = new ArrayList<>(); for (int i = 0; i < 10; i++) { ParameterData simpleData = new ParameterData(); simpleData.setName("姓名" + i); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataTest.java index 4c0d8aad..70acf19f 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataTest.java @@ -4,11 +4,6 @@ import java.io.File; 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.ExcelReader; @@ -17,8 +12,12 @@ import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.metadata.WriteTable; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + /** - * * @author Jiaju Zhuang */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @@ -26,15 +25,19 @@ public class RepetitionDataTest { private static File file07; private static File file03; + private static File fileCsv; private static File fileTable07; private static File fileTable03; + private static File fileTableCsv; @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("repetition07.xlsx"); file03 = TestFileUtil.createNewFile("repetition03.xls"); + fileCsv = TestFileUtil.createNewFile("repetitionCsv.csv"); fileTable07 = TestFileUtil.createNewFile("repetitionTable07.xlsx"); fileTable03 = TestFileUtil.createNewFile("repetitionTable03.xls"); + fileTableCsv = TestFileUtil.createNewFile("repetitionTableCsv.csv"); } @Test @@ -47,6 +50,11 @@ public class RepetitionDataTest { readAndWrite(file03); } + @Test + public void t03ReadAndWriteCsv() { + readAndWrite(fileCsv); + } + private void readAndWrite(File file) { ExcelWriter excelWriter = EasyExcel.write(file, RepetitionData.class).build(); WriteSheet writeSheet = EasyExcel.writerSheet(0).build(); @@ -57,15 +65,20 @@ public class RepetitionDataTest { } @Test - public void t03ReadAndWriteTable07() { + public void t11ReadAndWriteTable07() { readAndWriteTable(fileTable07); } @Test - public void t04ReadAndWriteTable03() { + public void t12ReadAndWriteTable03() { readAndWriteTable(fileTable03); } + @Test + public void t13ReadAndWriteTableCsv() { + readAndWriteTable(fileTableCsv); + } + private void readAndWriteTable(File file) { ExcelWriter excelWriter = EasyExcel.write(file, RepetitionData.class).build(); WriteSheet writeSheet = EasyExcel.writerSheet(0).build(); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java index 2d3c75b6..a381ec43 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java @@ -4,17 +4,16 @@ import java.io.File; import java.util.ArrayList; import java.util.List; +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; + import org.junit.Assert; 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; - /** - * * @author Jiaju Zhuang */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @@ -22,11 +21,13 @@ public class SimpleDataTest { private static File file07; private static File file03; + private static File fileCsv; @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("simple07.xlsx"); file03 = TestFileUtil.createNewFile("simple03.xls"); + fileCsv = TestFileUtil.createNewFile("simpleCsv.csv"); } @Test @@ -39,21 +40,31 @@ public class SimpleDataTest { readAndWrite(file03); } + @Test + public void t03ReadAndWriteCsv() { + readAndWrite(fileCsv); + } + private void readAndWrite(File file) { EasyExcel.write(file, SimpleData.class).sheet().doWrite(data()); EasyExcel.read(file, SimpleData.class, new SimpleDataListener()).sheet().doRead(); } @Test - public void t03SynchronousRead07() { + public void t11SynchronousRead07() { synchronousRead(file07); } @Test - public void t04SynchronousRead03() { + public void t12SynchronousRead03() { synchronousRead(file03); } + @Test + public void t13SynchronousReadCsv() { + synchronousRead(fileCsv); + } + @Test public void t05SheetNameRead07() { EasyExcel.read(TestFileUtil.readFile("simple" + File.separator + "simple07.xlsx"), SimpleData.class, diff --git a/src/test/java/com/alibaba/easyexcel/test/core/skip/SkipDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/skip/SkipDataTest.java index 3f62994e..ed9e84df 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/skip/SkipDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/skip/SkipDataTest.java @@ -4,23 +4,22 @@ import java.io.File; import java.util.ArrayList; import java.util.List; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; - import com.alibaba.easyexcel.test.core.simple.SimpleData; -import com.alibaba.easyexcel.test.core.simple.SimpleDataListener; -import com.alibaba.easyexcel.test.core.simple.SimpleDataSheetNameListener; 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.event.SyncReadListener; +import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.write.metadata.WriteSheet; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + /** * @author Jiaju Zhuang */ @@ -29,11 +28,13 @@ public class SkipDataTest { private static File file07; private static File file03; + private static File fileCsv; @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("skip.xlsx"); file03 = TestFileUtil.createNewFile("skip.xls"); + fileCsv = TestFileUtil.createNewFile("skip.csv"); } @Test @@ -46,6 +47,11 @@ public class SkipDataTest { readAndWrite(file03); } + @Test + public void t03ReadAndWriteCsv() { + Assert.assertThrows(ExcelGenerateException.class, () -> readAndWrite(fileCsv)); + } + private void readAndWrite(File file) { ExcelWriter excelWriter = EasyExcel.write(file, SimpleData.class).build(); WriteSheet writeSheet0 = EasyExcel.writerSheet(0, "第一个").build(); @@ -70,12 +76,11 @@ public class SkipDataTest { excelReader.read(readSheet1, readSheet3); List syncList = syncReadListener.getList(); Assert.assertEquals(2, syncList.size()); - Assert.assertEquals("name2", ((SkipData) syncList.get(0)).getName()); - Assert.assertEquals("name4", ((SkipData) syncList.get(1)).getName()); + Assert.assertEquals("name2", ((SkipData)syncList.get(0)).getName()); + Assert.assertEquals("name4", ((SkipData)syncList.get(1)).getName()); excelReader.finish(); } - private List data(String name) { List list = new ArrayList(); SkipData data = new SkipData(); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/sort/SortDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/sort/SortDataTest.java index 698078a1..f1a2b618 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/sort/SortDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/sort/SortDataTest.java @@ -6,15 +6,15 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; + import org.junit.Assert; 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; - /** * @author Jiaju Zhuang */ @@ -23,15 +23,19 @@ public class SortDataTest { private static File file07; private static File file03; + private static File fileCsv; private static File sortNoHead07; private static File sortNoHead03; + private static File sortNoHeadCsv; @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("sort.xlsx"); file03 = TestFileUtil.createNewFile("sort.xls"); + fileCsv = TestFileUtil.createNewFile("sort.csv"); sortNoHead07 = TestFileUtil.createNewFile("sortNoHead.xlsx"); sortNoHead03 = TestFileUtil.createNewFile("sortNoHead.xls"); + sortNoHeadCsv = TestFileUtil.createNewFile("sortNoHead.csv"); } @Test @@ -45,15 +49,24 @@ public class SortDataTest { } @Test - public void t03ReadAndWriteNoHead07() { + public void t03ReadAndWriteCsv() { + readAndWrite(fileCsv); + } + + @Test + public void t11ReadAndWriteNoHead07() { readAndWriteNoHead(sortNoHead07); } @Test - public void t04ReadAndWriteNoHead03() { + public void t12ReadAndWriteNoHead03() { readAndWriteNoHead(sortNoHead03); } + @Test + public void t13ReadAndWriteNoHeadCsv() { + readAndWriteNoHead(sortNoHeadCsv); + } private void readAndWrite(File file) { EasyExcel.write(file, SortData.class).sheet().doWrite(data()); @@ -95,7 +108,6 @@ public class SortDataTest { return head; } - private List data() { List list = new ArrayList(); SortData sortData = new SortData(); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java index 843ac964..fec79796 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java @@ -40,7 +40,7 @@ public class StyleDataTest { @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("style07.xlsx"); - file03 = TestFileUtil.createNewFile("style03.xls"); + file03 = TestFileUtil.createNewFile("style03.csv"); } @Test diff --git a/src/test/java/com/alibaba/easyexcel/test/core/template/TemplateDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/template/TemplateDataTest.java index adf63137..d6ebd0aa 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/template/TemplateDataTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/template/TemplateDataTest.java @@ -4,14 +4,14 @@ import java.io.File; import java.util.ArrayList; import java.util.List; +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; + 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; - /** * * @author Jiaju Zhuang @@ -22,6 +22,7 @@ public class TemplateDataTest { private static File file07; private static File file03; + @BeforeClass public static void init() { file07 = TestFileUtil.createNewFile("template07.xlsx"); diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java index ebc910d1..91293019 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/csv/CsvReadTest.java @@ -2,7 +2,9 @@ package com.alibaba.easyexcel.test.temp.csv; import java.io.File; import java.io.FileInputStream; +import java.io.FileOutputStream; import java.io.FileReader; +import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; @@ -25,7 +27,8 @@ public class CsvReadTest { @Test public void write() throws Exception { - Appendable out = new PrintWriter(TestFileUtil.createNewFile("csvWrite1.csv")); + Appendable out = new PrintWriter( + new OutputStreamWriter(new FileOutputStream(TestFileUtil.createNewFile("csvWrite1.csv")))); CSVPrinter printer = CSVFormat.DEFAULT.withHeader("userId", "userName") .print(out); for (int i = 0; i < 10; i++) { From bd3a98fc0b84f27148f969d113ceef05a38f9237 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 13 Sep 2021 20:06:09 +0800 Subject: [PATCH 104/129] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- update.md | 1 + 1 file changed, 1 insertion(+) diff --git a/update.md b/update.md index 95fed3b3..993c2762 100644 --- a/update.md +++ b/update.md @@ -4,6 +4,7 @@ * 升级cglib 到 3.3.0 * 升级ehcache 到 3.8.1 * 支持非驼峰的字段读写 +* 支持csv的读&写 * 修复`CellData`可能不返回行列号 [Issue #1832](https://github.com/alibaba/easyexcel/issues/1832) * 优化读取性能 * 修复部分情况下不抛出异常 From 859220169863fa64cf494c2c7235841bab1545d3 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 13 Sep 2021 20:08:09 +0800 Subject: [PATCH 105/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test/core/dataformat/DateFormatTest.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/test/java/com/alibaba/easyexcel/test/core/dataformat/DateFormatTest.java b/src/test/java/com/alibaba/easyexcel/test/core/dataformat/DateFormatTest.java index ec256213..27494f29 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/dataformat/DateFormatTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/core/dataformat/DateFormatTest.java @@ -7,19 +7,18 @@ import java.util.Locale; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; +import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * @author Jiaju Zhuang */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) +@Slf4j public class DateFormatTest { private static File file07; @@ -48,10 +47,10 @@ public class DateFormatTest { EasyExcel.read(file, DateFormatData.class, null).locale(Locale.CHINA).sheet().doReadSync(); for (DateFormatData data : list) { if (data.getDateStringCn() != null && !data.getDateStringCn().equals(data.getDate())) { - LOGGER.info("date:cn:{},{}", data.getDateStringCn(), data.getDate()); + log.info("date:cn:{},{}", data.getDateStringCn(), data.getDate()); } if (data.getNumberStringCn() != null && !data.getNumberStringCn().equals(data.getNumber())) { - LOGGER.info("number:cn{},{}", data.getNumberStringCn(), data.getNumber()); + log.info("number:cn{},{}", data.getNumberStringCn(), data.getNumber()); } } for (DateFormatData data : list) { @@ -65,10 +64,10 @@ public class DateFormatTest { EasyExcel.read(file, DateFormatData.class, null).locale(Locale.US).sheet().doReadSync(); for (DateFormatData data : list) { if (data.getDateStringUs() != null && !data.getDateStringUs().equals(data.getDate())) { - LOGGER.info("date:us:{},{}", data.getDateStringUs(), data.getDate()); + log.info("date:us:{},{}", data.getDateStringUs(), data.getDate()); } if (data.getNumberStringUs() != null && !data.getNumberStringUs().equals(data.getNumber())) { - LOGGER.info("number:us{},{}", data.getNumberStringUs(), data.getNumber()); + log.info("number:us{},{}", data.getNumberStringUs(), data.getNumber()); } } for (DateFormatData data : list) { From 16f7f53eb3253a1c199df5fbc37b61959a3e0626 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 13 Sep 2021 20:10:14 +0800 Subject: [PATCH 106/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java | 7 ++++--- .../com/alibaba/excel/util/NumberDataFormatterUtils.java | 7 +++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java index fe35ab82..b002b6b4 100644 --- a/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java +++ b/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java @@ -2,6 +2,7 @@ package com.alibaba.excel.metadata.csv; import java.io.Closeable; import java.io.IOException; +import java.math.BigDecimal; import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -768,8 +769,8 @@ public class CsvSheet implements Sheet, Closeable { if (dataFormatString == null) { dataFormatString = csvWorkbook.createDataFormat().getFormat(dataFormat); } - return NumberDataFormatterUtils.format( - DateUtil.getExcelDate(csvCell.getDateValue(), csvWorkbook.getUse1904windowing()), + return NumberDataFormatterUtils.format(BigDecimal.valueOf( + DateUtil.getExcelDate(csvCell.getDateValue(), csvWorkbook.getUse1904windowing())), dataFormat, dataFormatString, csvWorkbook.getUse1904windowing(), csvWorkbook.getLocale(), csvWorkbook.getUseScientificFormat()); } else { @@ -784,7 +785,7 @@ public class CsvSheet implements Sheet, Closeable { if (dataFormatString == null) { dataFormatString = csvWorkbook.createDataFormat().getFormat(dataFormat); } - return NumberDataFormatterUtils.format(csvCell.getNumericCellValue(), dataFormat, dataFormatString, + return NumberDataFormatterUtils.format(csvCell.getNumberValue(), dataFormat, dataFormatString, csvWorkbook.getUse1904windowing(), csvWorkbook.getLocale(), csvWorkbook.getUseScientificFormat()); } diff --git a/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java b/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java index 640fd07f..83d7a23f 100644 --- a/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java +++ b/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java @@ -1,11 +1,10 @@ package com.alibaba.excel.util; -import java.util.Locale; - import java.math.BigDecimal; +import java.util.Locale; -import com.alibaba.excel.metadata.format.DataFormatter; import com.alibaba.excel.metadata.GlobalConfiguration; +import com.alibaba.excel.metadata.format.DataFormatter; /** * Convert number data, including date. @@ -48,7 +47,7 @@ public class NumberDataFormatterUtils { * @param useScientificFormat * @return */ - public static String format(Double data, Short dataFormat, String dataFormatString, Boolean use1904windowing, + public static String format(BigDecimal data, Short dataFormat, String dataFormatString, Boolean use1904windowing, Locale locale, Boolean useScientificFormat) { DataFormatter dataFormatter = DATA_FORMATTER_THREAD_LOCAL.get(); if (dataFormatter == null) { From 35dd6f1aa3494ec67a9cd8ac9d5e4f5973a47d0f Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Mon, 13 Sep 2021 21:12:14 +0800 Subject: [PATCH 107/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9cglib=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../listener/ModelBuildEventListener.java | 5 +-- .../com/alibaba/excel/util/BeanMapUtils.java | 40 +++++++++++++++++++ .../com/alibaba/excel/util/ClassUtils.java | 2 +- .../write/executor/ExcelWriteAddExecutor.java | 3 +- .../executor/ExcelWriteFillExecutor.java | 4 +- .../easyexcel/test/temp/Xls03Test.java | 5 ++- .../easyexcel/test/temp/simple/Wirte.java | 4 +- 7 files changed, 52 insertions(+), 11 deletions(-) create mode 100644 src/main/java/com/alibaba/excel/util/BeanMapUtils.java diff --git a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java index adfa6589..bba3e487 100644 --- a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java +++ b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java @@ -13,12 +13,11 @@ import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; import com.alibaba.excel.read.metadata.property.ExcelReadHeadProperty; +import com.alibaba.excel.util.BeanMapUtils; import com.alibaba.excel.util.ConverterUtils; import com.alibaba.excel.util.FieldUtils; import com.alibaba.excel.util.MapUtils; -import net.sf.cglib.beans.BeanMap; - /** * Convert to the object the user needs * @@ -115,7 +114,7 @@ public class ModelBuildEventListener implements ReadListenerBeanMap. For finer + * control over the generated instance, use a new instance of + * BeanMap.Generator instead of this static method. + * + * Custom naming policy to prevent null pointer exceptions. + * https://github.com/alibaba/easyexcel/issues/2064 + * + * @param bean the JavaBean underlying the map + * @return a new BeanMap instance + */ + public static BeanMap create(Object bean) { + Generator gen = new Generator(); + gen.setBean(bean); + gen.setNamingPolicy(EasyExcelNamingPolicy.INSTANCE); + return gen.create(); + } + + public static class EasyExcelNamingPolicy extends DefaultNamingPolicy { + public static final EasyExcelNamingPolicy INSTANCE = new EasyExcelNamingPolicy(); + + @Override + protected String getTag() { + return "ByEasyExcelCGLIB"; + } + } +} diff --git a/src/main/java/com/alibaba/excel/util/ClassUtils.java b/src/main/java/com/alibaba/excel/util/ClassUtils.java index 2f628780..96cc11f8 100644 --- a/src/main/java/com/alibaba/excel/util/ClassUtils.java +++ b/src/main/java/com/alibaba/excel/util/ClassUtils.java @@ -27,7 +27,7 @@ import com.alibaba.excel.write.metadata.holder.WriteHolder; **/ public class ClassUtils { - private static final Map, SoftReference> FIELD_CACHE = new ConcurrentHashMap<>(); + public static final Map, SoftReference> FIELD_CACHE = new ConcurrentHashMap<>(); public static void declaredFields(Class clazz, Map sortedAllFiledMap, Map indexFiledMap, Map ignoreMap, Boolean convertAllFiled, diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index d2677d3d..01f9b53d 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -13,6 +13,7 @@ import com.alibaba.excel.enums.HeadKindEnum; 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.BeanMapUtils; import com.alibaba.excel.util.ClassUtils; import com.alibaba.excel.util.FieldUtils; import com.alibaba.excel.util.WorkBookUtil; @@ -120,7 +121,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { private void addJavaObjectToExcel(Object oneRowData, Row row, int relativeRowIndex, Map sortedAllFiledMap) { WriteHolder currentWriteHolder = writeContext.currentWriteHolder(); - BeanMap beanMap = BeanMap.create(oneRowData); + BeanMap beanMap = BeanMapUtils.create(oneRowData); Set beanMapHandledSet = new HashSet(); int cellIndex; // If it's a class it needs to be cast by type diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index fd3802c0..c3b66472 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -16,6 +16,7 @@ import com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum; import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; +import com.alibaba.excel.util.BeanMapUtils; import com.alibaba.excel.util.FieldUtils; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.util.WriteHandlerUtils; @@ -24,7 +25,6 @@ import com.alibaba.excel.write.metadata.fill.FillConfig; import com.alibaba.excel.write.metadata.fill.FillWrapper; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; -import net.sf.cglib.beans.BeanMap; import org.apache.commons.collections4.CollectionUtils; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; @@ -186,7 +186,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { if (oneRowData instanceof Map) { dataMap = (Map)oneRowData; } else { - dataMap = BeanMap.create(oneRowData); + dataMap = BeanMapUtils.create(oneRowData); } WriteSheetHolder writeSheetHolder = writeContext.writeSheetHolder(); Map fieldNameContentPropertyMap = diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/Xls03Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/Xls03Test.java index e5d7dfc3..906c092e 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/Xls03Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/Xls03Test.java @@ -3,14 +3,15 @@ package com.alibaba.easyexcel.test.temp; import java.util.List; import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.util.BeanMapUtils; import com.alibaba.fastjson.JSON; +import net.sf.cglib.beans.BeanMap; import net.sf.cglib.core.DebuggingClassWriter; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.cglib.beans.BeanMap; /** * 临时测试 @@ -40,7 +41,7 @@ public class Xls03Test { //camlData.setAEst("test3"); //camlData.setTEST("test4"); - BeanMap beanMap = BeanMap.create(camlData); + BeanMap beanMap = BeanMapUtils.create(camlData); LOGGER.info("test:{}", beanMap.get("test")); LOGGER.info("test:{}", beanMap.get("Test")); diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/simple/Wirte.java b/src/test/java/com/alibaba/easyexcel/test/temp/simple/Wirte.java index 98e77527..3cc54749 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/simple/Wirte.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/simple/Wirte.java @@ -10,12 +10,12 @@ import com.alibaba.easyexcel.test.demo.write.DemoData; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; +import com.alibaba.excel.util.BeanMapUtils; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.metadata.WriteTable; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; -import net.sf.cglib.beans.BeanMap; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; @@ -35,7 +35,7 @@ public class Wirte { public void simpleWrite1() { LargeData ss = new LargeData(); ss.setStr23("ttt"); - Map map = BeanMap.create(ss); + Map map = BeanMapUtils.create(ss); System.out.println(map.containsKey("str23")); System.out.println(map.containsKey("str22")); System.out.println(map.get("str23")); From 25b132a852872ab5a0f33fb36d5c1da8ff984ff5 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Tue, 14 Sep 2021 20:39:40 +0800 Subject: [PATCH 108/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9url=E8=B6=85=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 14 ++++++++++++++ .../excel/converters/url/UrlImageConverter.java | 13 ++++++++----- .../easyexcel/test/demo/write/WriteTest.java | 1 + update.md | 15 ++++++++------- 4 files changed, 31 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 604823f9..f0e070c3 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,20 @@ Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都 当然还有极速模式能更快,但是内存占用会在100M多一点 ![img](img/readme/large.png) +## 版本支持 +* 2+ 版本支持 Java7和Java6 +* 3+ 版本至少 Java8 + +## 人员招募 +由于工作较忙,有意愿做开源的同学可以报名,主要负责群里回答&issue处理,当然也可以做一些PR. +由于开源没有任何物质回报,然后现在的维护同学也是课余时间维护的,所以想加入的同学需要持之以恒,而不是一时兴起. +要求如下: +* 有一定java编码能力 & 良好的编码习惯 +* 了解easyexcel 读&写的原理 +* 热爱开源项目 +* 能长期坚持的去做 +* 相对工作没那么忙 + ## 相关文档 * [快速开始](https://www.yuque.com/easyexcel/doc/easyexcel) * [关于软件](/abouteasyexcel.md) diff --git a/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java b/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java index 65f9035f..7daa7cab 100644 --- a/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java +++ b/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java @@ -18,6 +18,9 @@ import com.alibaba.excel.util.IoUtils; * @since 2.1.1 */ public class UrlImageConverter implements Converter { + public static int urlConnectTimeout = 1000; + public static int urlReadTimeout = 5000; + @Override public Class supportJavaTypeKey() { return URL.class; @@ -28,11 +31,11 @@ public class UrlImageConverter implements Converter { GlobalConfiguration globalConfiguration) throws IOException { InputStream inputStream = null; try { - URLConnection conn = value.openConnection(); - conn.setConnectTimeout(1000); - conn.setReadTimeout(5000); - inputStream = con.getInputStream(); - byte[] bytes = IoUtils.toByteArray(inputStream); + URLConnection urlConnection = value.openConnection(); + urlConnection.setConnectTimeout(urlConnectTimeout); + urlConnection.setReadTimeout(urlReadTimeout); + inputStream = urlConnection.getInputStream(); + byte[] bytes = IoUtils.toByteArray(inputStream); return new WriteCellData<>(bytes); } finally { if (inputStream != null) { diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java index 00d1b059..1bf11fe4 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java @@ -95,6 +95,7 @@ public class WriteTest { @Test public void excludeOrIncludeWrite() { String fileName = TestFileUtil.getPath() + "excludeOrIncludeWrite" + System.currentTimeMillis() + ".xlsx"; + // 这里需要注意 在使用ExcelProperty注解的使用,如果想不空列则需要加入order字段,而不是index,order会忽略空列,然后继续往后,而index,不会忽略空列,在第几列就是第几列。 // 根据用户传入字段 假设我们要忽略 date Set excludeColumnFiledNames = new HashSet(); diff --git a/update.md b/update.md index b777133f..a6a8208d 100644 --- a/update.md +++ b/update.md @@ -1,11 +1,5 @@ -# 2.2.10 -* 修复读取的时候用string接收数字 可能四舍五入不一致的bug - -# 2.2.9 -* 修复读取的时候用string接收数字 可能四舍五入不一致的bug - # 3.0.0-beta1 -* 升级jdk8 不再支持jdk6 jdk7 +* 升级jdk8 不再支持jdk6 jdk7 * 升级poi 到 4.1.2 * 升级cglib 到 3.3.0 * 升级ehcache 到 3.8.1 @@ -21,6 +15,13 @@ * 修改读的关闭流无效 [Issue #1840](https://github.com/alibaba/easyexcel/issues/1840) * 写入支持Collection [Issue #1834](https://github.com/alibaba/easyexcel/issues/1834) * `Converter`支持null转换 [Issue #1776](https://github.com/alibaba/easyexcel/issues/1776) +* cglib 新增命名策略,防止和`spring`的冲突 [Issue #2064](https://github.com/alibaba/easyexcel/issues/2064) + +# 2.2.10 +* 修复读取的时候用string接收数字 可能四舍五入不一致的bug + +# 2.2.9 +* 修复读取的时候用string接收数字 可能四舍五入不一致的bug # 2.2.8 * 兼容07在特殊的excel的情况下,读取数据异常 From 4cff5214c05199bfcbf1b1764c0ffdc854ffc1d7 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Tue, 14 Sep 2021 21:17:51 +0800 Subject: [PATCH 109/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9lomok?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../write/metadata/fill/AnalysisCell.java | 67 +---- .../test/temp/fill/FillTempTest.java | 228 ++++++++++++++++++ 2 files changed, 231 insertions(+), 64 deletions(-) create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/fill/FillTempTest.java diff --git a/src/main/java/com/alibaba/excel/write/metadata/fill/AnalysisCell.java b/src/main/java/com/alibaba/excel/write/metadata/fill/AnalysisCell.java index 41b2cfc1..b9b377ed 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/fill/AnalysisCell.java +++ b/src/main/java/com/alibaba/excel/write/metadata/fill/AnalysisCell.java @@ -4,11 +4,14 @@ import java.util.List; import com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum; +import lombok.Data; + /** * Read the cells of the template while populating the data. * * @author Jiaju Zhuang **/ +@Data public class AnalysisCell { private int columnIndex; private int rowIndex; @@ -19,70 +22,6 @@ public class AnalysisCell { private String prefix; private Boolean firstRow; - public int getColumnIndex() { - return columnIndex; - } - - public void setColumnIndex(int columnIndex) { - this.columnIndex = columnIndex; - } - - public int getRowIndex() { - return rowIndex; - } - - public void setRowIndex(int rowIndex) { - this.rowIndex = rowIndex; - } - - public List getVariableList() { - return variableList; - } - - public void setVariableList(List variableList) { - this.variableList = variableList; - } - - public List getPrepareDataList() { - return prepareDataList; - } - - public void setPrepareDataList(List prepareDataList) { - this.prepareDataList = prepareDataList; - } - - public Boolean getOnlyOneVariable() { - return onlyOneVariable; - } - - public void setOnlyOneVariable(Boolean onlyOneVariable) { - this.onlyOneVariable = onlyOneVariable; - } - - public String getPrefix() { - return prefix; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - public WriteTemplateAnalysisCellTypeEnum getCellType() { - return cellType; - } - - public void setCellType(WriteTemplateAnalysisCellTypeEnum cellType) { - this.cellType = cellType; - } - - public Boolean getFirstRow() { - return firstRow; - } - - public void setFirstRow(Boolean firstRow) { - this.firstRow = firstRow; - } - @Override public boolean equals(Object o) { if (this == o) { diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/fill/FillTempTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/fill/FillTempTest.java new file mode 100644 index 00000000..2c201863 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/fill/FillTempTest.java @@ -0,0 +1,228 @@ +package com.alibaba.easyexcel.test.temp.fill; + +import java.io.File; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alibaba.easyexcel.test.demo.fill.FillData; +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; +import com.alibaba.excel.ExcelWriter; +import com.alibaba.excel.enums.WriteDirectionEnum; +import com.alibaba.excel.write.metadata.WriteSheet; +import com.alibaba.excel.write.metadata.fill.FillConfig; +import com.alibaba.excel.write.metadata.fill.FillWrapper; + +import org.junit.Ignore; +import org.junit.Test; + +/** + * 写的填充写法 + * + * @since 2.1.1 + * @author Jiaju Zhuang + */ +@Ignore +public class FillTempTest { + /** + * 最简单的填充 + * + * @since 2.1.1 + */ + @Test + public void simpleFill() { + // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替 + String templateFileName ="/Users/zhuangjiaju/Downloads/simple.xlsx"; + + // 方案1 根据对象填充 + String fileName = TestFileUtil.getPath() + "simpleFill" + System.currentTimeMillis() + ".xlsx"; + // 这里 会填充到第一个sheet, 然后文件流会自动关闭 + FillData fillData = new FillData(); + fillData.setName("张三"); + fillData.setNumber(5.2); + EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(fillData); + + //// 方案2 根据Map填充 + //fileName = TestFileUtil.getPath() + "simpleFill" + System.currentTimeMillis() + ".xlsx"; + //// 这里 会填充到第一个sheet, 然后文件流会自动关闭 + //Map map = new HashMap(); + //map.put("name", "张三"); + //map.put("number", 5.2); + //EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(map); + } + + /** + * 填充列表 + * + * @since 2.1.1 + */ + @Test + public void listFill() { + // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替 + // 填充list 的时候还要注意 模板中{.} 多了个点 表示list + String templateFileName = + TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "list.xlsx"; + + // 方案1 一下子全部放到内存里面 并填充 + String fileName = TestFileUtil.getPath() + "listFill" + System.currentTimeMillis() + ".xlsx"; + // 这里 会填充到第一个sheet, 然后文件流会自动关闭 + EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(data()); + + // 方案2 分多次 填充 会使用文件缓存(省内存) + fileName = TestFileUtil.getPath() + "listFill" + System.currentTimeMillis() + ".xlsx"; + ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build(); + WriteSheet writeSheet = EasyExcel.writerSheet().build(); + excelWriter.fill(data(), writeSheet); + excelWriter.fill(data(), writeSheet); + // 千万别忘记关闭流 + excelWriter.finish(); + } + + /** + * 复杂的填充 + * + * @since 2.1.1 + */ + @Test + public void complexFill() { + // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替 + // {} 代表普通变量 {.} 代表是list的变量 + String templateFileName = + TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "complex.xlsx"; + + String fileName = TestFileUtil.getPath() + "complexFill" + System.currentTimeMillis() + ".xlsx"; + ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build(); + WriteSheet writeSheet = EasyExcel.writerSheet().build(); + // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行,然后下面的数据往后移动。默认 是false,会直接使用下一行,如果没有则创建。 + // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了,所以慎用 + // 简单的说 如果你的模板有list,且list不是最后一行,下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存 + // 如果数据量大 list不是最后一行 参照下一个 + FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build(); + excelWriter.fill(data(), fillConfig, writeSheet); + excelWriter.fill(data(), fillConfig, writeSheet); + Map map = new HashMap(); + map.put("date", "2019年10月9日13:28:28"); + map.put("total", 1000); + excelWriter.fill(map, writeSheet); + excelWriter.finish(); + } + + /** + * 数据量大的复杂填充 + *

    + * 这里的解决方案是 确保模板list为最后一行,然后再拼接table.还有03版没救,只能刚正面加内存。 + * + * @since 2.1.1 + */ + @Test + public void complexFillWithTable() { + // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替 + // {} 代表普通变量 {.} 代表是list的变量 + // 这里模板 删除了list以后的数据,也就是统计的这一行 + String templateFileName = + TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "complexFillWithTable.xlsx"; + + String fileName = TestFileUtil.getPath() + "complexFillWithTable" + System.currentTimeMillis() + ".xlsx"; + ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build(); + WriteSheet writeSheet = EasyExcel.writerSheet().build(); + // 直接写入数据 + excelWriter.fill(data(), writeSheet); + excelWriter.fill(data(), writeSheet); + + // 写入list之前的数据 + Map map = new HashMap(); + map.put("date", "2019年10月9日13:28:28"); + excelWriter.fill(map, writeSheet); + + // list 后面还有个统计 想办法手动写入 + // 这里偷懒直接用list 也可以用对象 + List> totalListList = new ArrayList>(); + List totalList = new ArrayList(); + totalListList.add(totalList); + totalList.add(null); + totalList.add(null); + totalList.add(null); + // 第四列 + totalList.add("统计:1000"); + // 这里是write 别和fill 搞错了 + excelWriter.write(totalListList, writeSheet); + excelWriter.finish(); + // 总体上写法比较复杂 但是也没有想到好的版本 异步的去写入excel 不支持行的删除和移动,也不支持备注这种的写入,所以也排除了可以 + // 新建一个 然后一点点复制过来的方案,最后导致list需要新增行的时候,后面的列的数据没法后移,后续会继续想想解决方案 + } + + /** + * 横向的填充 + * + * @since 2.1.1 + */ + @Test + public void horizontalFill() { + // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替 + // {} 代表普通变量 {.} 代表是list的变量 + String templateFileName = + TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "horizontal.xlsx"; + + String fileName = TestFileUtil.getPath() + "horizontalFill" + System.currentTimeMillis() + ".xlsx"; + ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build(); + WriteSheet writeSheet = EasyExcel.writerSheet().build(); + FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build(); + excelWriter.fill(data(), fillConfig, writeSheet); + excelWriter.fill(data(), fillConfig, writeSheet); + + Map map = new HashMap(); + map.put("date", "2019年10月9日13:28:28"); + excelWriter.fill(map, writeSheet); + + // 别忘记关闭流 + excelWriter.finish(); + } + + /** + * 多列表组合填充填充 + * + * @since 2.2.0-beta1 + */ + @Test + public void compositeFill() { + // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替 + // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list + String templateFileName = + TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "composite.xlsx"; + + String fileName = TestFileUtil.getPath() + "compositeFill" + System.currentTimeMillis() + ".xlsx"; + ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build(); + WriteSheet writeSheet = EasyExcel.writerSheet().build(); + FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build(); + // 如果有多个list 模板上必须有{前缀.} 这里的前缀就是 data1,然后多个list必须用 FillWrapper包裹 + excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet); + excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet); + excelWriter.fill(new FillWrapper("data2", data()), writeSheet); + excelWriter.fill(new FillWrapper("data2", data()), writeSheet); + excelWriter.fill(new FillWrapper("data3", data()), writeSheet); + excelWriter.fill(new FillWrapper("data3", data()), writeSheet); + + Map map = new HashMap(); + //map.put("date", "2019年10月9日13:28:28"); + map.put("date", new Date()); + + excelWriter.fill(map, writeSheet); + + // 别忘记关闭流 + excelWriter.finish(); + } + + private List data() { + List list = new ArrayList(); + for (int i = 0; i < 10; i++) { + FillData fillData = new FillData(); + list.add(fillData); + fillData.setName("张三"); + fillData.setNumber(5.2); + } + return list; + } +} From 6407a8abcaa50c16bb9b9306590523a08a2c0cf7 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Tue, 14 Sep 2021 21:22:47 +0800 Subject: [PATCH 110/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=A1=AB=E5=85=85?= =?UTF-8?q?=E5=8F=AF=E8=83=BD=E5=A1=AB=E5=85=85=E9=94=99=E8=AF=AF=E7=9A=84?= =?UTF-8?q?bug=20#2035?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../write/executor/ExcelWriteFillExecutor.java | 16 +++++++--------- update.md | 1 + 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index e15a96c9..5e6139f6 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -199,7 +199,8 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { continue; } Object value = dataMap.get(variable); - WriteCellData cellData = converterAndSet(writeSheetHolder, FieldUtils.getFieldClass(dataMap, variable), + WriteCellData cellData = converterAndSet(writeSheetHolder, + FieldUtils.getFieldClass(dataMap, variable), null, cell, value, fieldNameContentPropertyMap.get(variable), null, relativeRowIndex); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, relativeRowIndex, Boolean.FALSE); } else { @@ -416,7 +417,6 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { int startIndex = 0; int length = value.length(); int lastPrepareDataIndex = 0; - int variableCount = 0; out: while (startIndex < length) { int prefixIndex = value.indexOf(FILL_PREFIX, startIndex); @@ -448,10 +448,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { String variable = value.substring(prefixIndex + 1, suffixIndex); if (StringUtils.isEmpty(variable)) { continue; - } else { - ++variableCount; } - int collectPrefixIndex = variable.indexOf(COLLECTION_PREFIX); if (collectPrefixIndex > -1) { if (collectPrefixIndex != 0) { @@ -466,18 +463,19 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { analysisCell.getVariableList().add(variable); if (lastPrepareDataIndex == prefixIndex) { analysisCell.getPrepareDataList().add(StringUtils.EMPTY); + // fix https://github.com/alibaba/easyexcel/issues/2035 + if (lastPrepareDataIndex != 0) { + analysisCell.setOnlyOneVariable(Boolean.FALSE); + } } else { String data = convertPrepareData(value.substring(lastPrepareDataIndex, prefixIndex)); preparedData.append(data); analysisCell.getPrepareDataList().add(data); + analysisCell.setOnlyOneVariable(Boolean.FALSE); } lastPrepareDataIndex = suffixIndex + 1; } - if (variableCount > 1) { - analysisCell.setOnlyOneVariable(Boolean.FALSE); - } - return dealAnalysisCell(analysisCell, value, rowIndex, lastPrepareDataIndex, length, firstRowCache, preparedData); } diff --git a/update.md b/update.md index a6a8208d..23aef9c6 100644 --- a/update.md +++ b/update.md @@ -16,6 +16,7 @@ * 写入支持Collection [Issue #1834](https://github.com/alibaba/easyexcel/issues/1834) * `Converter`支持null转换 [Issue #1776](https://github.com/alibaba/easyexcel/issues/1776) * cglib 新增命名策略,防止和`spring`的冲突 [Issue #2064](https://github.com/alibaba/easyexcel/issues/2064) +* 修改填充可能填充错误的bug [Issue #2035](https://github.com/alibaba/easyexcel/issues/2035) # 2.2.10 * 修复读取的时候用string接收数字 可能四舍五入不一致的bug From bdba8a41d42affa3fe42b79d3bdf552847cd98e0 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 14:13:21 +0800 Subject: [PATCH 111/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E4=B8=BAjdk8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../executor/ExcelWriteFillExecutor.java | 91 ++++++++----------- .../test/temp/dataformat/DataFormatter1.java | 2 +- 2 files changed, 40 insertions(+), 53 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 5e6139f6..1c45c49d 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -18,6 +18,8 @@ import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.util.BeanMapUtils; import com.alibaba.excel.util.FieldUtils; +import com.alibaba.excel.util.ListUtils; +import com.alibaba.excel.util.MapUtils; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.util.WriteHandlerUtils; import com.alibaba.excel.write.metadata.fill.AnalysisCell; @@ -48,32 +50,25 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { /** * Fields to replace in the template */ - private final Map> templateAnalysisCache = new HashMap>(8); + private final Map> templateAnalysisCache = MapUtils.newHashMap(); /** * Collection fields to replace in the template */ - private final Map> templateCollectionAnalysisCache = - new HashMap>(8); + private final Map> templateCollectionAnalysisCache = MapUtils.newHashMap(); /** * Style cache for collection fields */ - private final Map> collectionFieldStyleCache = - new HashMap>(8); + private final Map> collectionFieldStyleCache = MapUtils.newHashMap(); /** * Row height cache for collection */ - private final Map collectionRowHeightCache = new HashMap(8); + private final Map collectionRowHeightCache = MapUtils.newHashMap(); /** * Last index cache for collection fields */ - private final Map> collectionLastIndexCache = - new HashMap>(8); + private final Map> collectionLastIndexCache = MapUtils.newHashMap(); - private final Map relativeRowIndexMap = new HashMap(8); - /** - * The data prefix that is populated this time - */ - private String currentDataPrefix; + private final Map relativeRowIndexMap = MapUtils.newHashMap(); /** * The unique data encoding for this fill */ @@ -93,6 +88,9 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { fillConfig.init(); Object realData; + // The data prefix that is populated this time + String currentDataPrefix; + if (data instanceof FillWrapper) { FillWrapper fillWrapper = (FillWrapper)data; currentDataPrefix = fillWrapper.getName(); @@ -106,11 +104,11 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { // processing data if (realData instanceof Collection) { List analysisCellList = readTemplateData(templateCollectionAnalysisCache); - Collection collectionData = (Collection)realData; + Collection collectionData = (Collection)realData; if (CollectionUtils.isEmpty(collectionData)) { return; } - Iterator iterator = collectionData.iterator(); + Iterator iterator = collectionData.iterator(); if (WriteDirectionEnum.VERTICAL.equals(fillConfig.getDirection()) && fillConfig.getForceNewRow()) { shiftRows(collectionData.size(), analysisCellList); } @@ -182,9 +180,9 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { if (CollectionUtils.isEmpty(analysisCellList)) { return; } - Map dataMap; + Map dataMap; if (oneRowData instanceof Map) { - dataMap = (Map)oneRowData; + dataMap = (Map)oneRowData; } else { dataMap = BeanMapUtils.create(oneRowData); } @@ -259,11 +257,9 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { } Sheet sheet = writeContext.writeSheetHolder().getSheet(); - Map collectionLastIndexMap = collectionLastIndexCache.get(currentUniqueDataFlag); - if (collectionLastIndexMap == null) { - collectionLastIndexMap = new HashMap(16); - collectionLastIndexCache.put(currentUniqueDataFlag, collectionLastIndexMap); - } + Map collectionLastIndexMap = collectionLastIndexCache + .computeIfAbsent(currentUniqueDataFlag, key -> MapUtils.newHashMap()); + boolean isOriginalCell = false; Integer lastRowIndex; Integer lastColumnIndex; @@ -297,11 +293,9 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { Row row = createRowIfNecessary(sheet, cachedSheet, lastRowIndex, fillConfig, analysisCell, isOriginalCell); Cell cell = createCellIfNecessary(row, lastColumnIndex); - Map collectionFieldStyleMap = collectionFieldStyleCache.get(currentUniqueDataFlag); - if (collectionFieldStyleMap == null) { - collectionFieldStyleMap = new HashMap(16); - collectionFieldStyleCache.put(currentUniqueDataFlag, collectionFieldStyleMap); - } + Map collectionFieldStyleMap = collectionFieldStyleCache.computeIfAbsent( + currentUniqueDataFlag, key -> MapUtils.newHashMap()); + if (isOriginalCell) { collectionFieldStyleMap.put(analysisCell, cell.getCellStyle()); } else { @@ -373,7 +367,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { return analysisCellList; } Sheet sheet = writeContext.writeSheetHolder().getCachedSheet(); - Map> firstRowCache = new HashMap>(8); + Map> firstRowCache = MapUtils.newHashMapWithExpectedSize(8); for (int i = 0; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); if (row == null) { @@ -397,14 +391,14 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { /** * To prepare data * - * @param cell - * @param rowIndex - * @param columnIndex - * @param firstRowCache + * @param cell cell + * @param rowIndex row index + * @param columnIndex column index + * @param firstRowCache first row cache * @return Returns the data that the cell needs to replace */ private String prepareData(Cell cell, int rowIndex, int columnIndex, Map> firstRowCache) { - if (!CellType.STRING.equals(cell.getCellTypeEnum())) { + if (!CellType.STRING.equals(cell.getCellType())) { return null; } String value = cell.getStringCellValue(); @@ -421,7 +415,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { while (startIndex < length) { int prefixIndex = value.indexOf(FILL_PREFIX, startIndex); if (prefixIndex < 0) { - break out; + break; } if (prefixIndex != 0) { char prefixPrefixChar = value.charAt(prefixIndex - 1); @@ -491,28 +485,21 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { } String uniqueDataFlag = uniqueDataFlag(writeContext.writeSheetHolder(), analysisCell.getPrefix()); if (WriteTemplateAnalysisCellTypeEnum.COMMON.equals(analysisCell.getCellType())) { - List analysisCellList = templateAnalysisCache.get(uniqueDataFlag); - if (analysisCellList == null) { - analysisCellList = new ArrayList(); - templateAnalysisCache.put(uniqueDataFlag, analysisCellList); - } + List analysisCellList = templateAnalysisCache.computeIfAbsent(uniqueDataFlag, + key -> ListUtils.newArrayList()); analysisCellList.add(analysisCell); } else { - Set uniqueFirstRowCache = firstRowCache.get(uniqueDataFlag); - if (uniqueFirstRowCache == null) { - uniqueFirstRowCache = new HashSet(); - firstRowCache.put(uniqueDataFlag, uniqueFirstRowCache); - } + Set uniqueFirstRowCache = firstRowCache.computeIfAbsent(uniqueDataFlag, + key -> new HashSet<>()); + if (!uniqueFirstRowCache.contains(rowIndex)) { analysisCell.setFirstRow(Boolean.TRUE); uniqueFirstRowCache.add(rowIndex); } - List collectionAnalysisCellList = templateCollectionAnalysisCache.get(uniqueDataFlag); - if (collectionAnalysisCellList == null) { - collectionAnalysisCellList = new ArrayList(); - templateCollectionAnalysisCache.put(uniqueDataFlag, collectionAnalysisCellList); - } + List collectionAnalysisCellList = templateCollectionAnalysisCache.computeIfAbsent( + uniqueDataFlag, key -> ListUtils.newArrayList()); + collectionAnalysisCellList.add(analysisCell); } return preparedData.toString(); @@ -525,9 +512,9 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { analysisCell.setRowIndex(rowIndex); analysisCell.setColumnIndex(columnIndex); analysisCell.setOnlyOneVariable(Boolean.TRUE); - List variableList = new ArrayList(); + List variableList = ListUtils.newArrayList(); analysisCell.setVariableList(variableList); - List prepareDataList = new ArrayList(); + List prepareDataList = ListUtils.newArrayList(); analysisCell.setPrepareDataList(prepareDataList); analysisCell.setCellType(WriteTemplateAnalysisCellTypeEnum.COMMON); analysisCell.setFirstRow(Boolean.FALSE); @@ -545,7 +532,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { if (writeSheetHolder.getSheetNo() != null) { prefix = writeSheetHolder.getSheetNo().toString(); } else { - prefix = writeSheetHolder.getSheetName().toString(); + prefix = writeSheetHolder.getSheetName(); } if (StringUtils.isEmpty(wrapperName)) { return prefix + "-"; diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatter1.java b/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatter1.java index 0239ed5b..18e8049d 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatter1.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/dataformat/DataFormatter1.java @@ -968,7 +968,7 @@ public class DataFormatter1 implements Observer { return ""; } - CellType cellType = cell.getCellTypeEnum(); + CellType cellType = cell.getCellType(); if (cellType == CellType.FORMULA) { if (evaluator == null) { return cell.getCellFormula(); From 153d4c6e2047b013e12b2cbb57e321d2817a7960 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 16:14:15 +0800 Subject: [PATCH 112/129] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E5=BC=83=E7=94=A8?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../excel/context/WriteContextImpl.java | 2 +- .../metadata/property/ExcelHeadProperty.java | 29 ++-- .../listener/ModelBuildEventListener.java | 55 ++----- .../excel/read/metadata/ReadWorkbook.java | 140 +----------------- .../metadata/holder/AbstractReadHolder.java | 5 +- .../read/metadata/holder/ReadSheetHolder.java | 2 +- .../metadata/holder/ReadWorkbookHolder.java | 22 +-- .../property/ExcelReadHeadProperty.java | 4 +- .../com/alibaba/excel/util/ClassUtils.java | 27 ++-- .../write/builder/ExcelWriterBuilder.java | 15 -- .../write/executor/ExcelWriteAddExecutor.java | 3 +- .../excel/write/metadata/WriteWorkbook.java | 11 -- .../metadata/holder/AbstractWriteHolder.java | 6 +- .../metadata/holder/WriteSheetHolder.java | 2 +- .../metadata/holder/WriteTableHolder.java | 32 +--- .../metadata/holder/WriteWorkbookHolder.java | 2 +- .../property/ExcelWriteHeadProperty.java | 24 ++- 17 files changed, 72 insertions(+), 309 deletions(-) diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java index 5766b4b3..8e50eb74 100644 --- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java @@ -291,7 +291,7 @@ public class WriteContextImpl implements WriteContext { } private void initCurrentTableHolder(WriteTable writeTable) { - writeTableHolder = new WriteTableHolder(writeTable, writeSheetHolder, writeWorkbookHolder); + writeTableHolder = new WriteTableHolder(writeTable, writeSheetHolder); writeSheetHolder.getHasBeenInitializedTable().put(writeTable.getTableNo(), writeTableHolder); currentWriteHolder = writeTableHolder; if (LOGGER.isDebugEnabled()) { diff --git a/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java b/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java index 34c9d4d0..4b52e213 100644 --- a/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java +++ b/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java @@ -3,7 +3,6 @@ package com.alibaba.excel.metadata.property; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; @@ -18,6 +17,7 @@ import com.alibaba.excel.exception.ExcelCommonException; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Holder; import com.alibaba.excel.util.ClassUtils; +import com.alibaba.excel.util.MapUtils; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.write.metadata.holder.AbstractWriteHolder; @@ -64,19 +64,19 @@ public class ExcelHeadProperty { */ private Map ignoreMap; - public ExcelHeadProperty(Holder holder, Class headClazz, List> head, Boolean convertAllFiled) { + public ExcelHeadProperty(Holder holder, Class headClazz, List> head) { this.headClazz = headClazz; - headMap = new TreeMap(); - contentPropertyMap = new TreeMap(); - fieldNameContentPropertyMap = new HashMap(); - ignoreMap = new HashMap(16); + headMap = new TreeMap<>(); + contentPropertyMap = new TreeMap<>(); + fieldNameContentPropertyMap = MapUtils.newHashMap(); + ignoreMap = MapUtils.newHashMap(); headKind = HeadKindEnum.NONE; headRowNumber = 0; if (head != null && !head.isEmpty()) { int headIndex = 0; for (int i = 0; i < head.size(); i++) { if (holder instanceof AbstractWriteHolder) { - if (((AbstractWriteHolder) holder).ignore(null, i)) { + if (((AbstractWriteHolder)holder).ignore(null, i)) { continue; } } @@ -87,7 +87,7 @@ public class ExcelHeadProperty { headKind = HeadKindEnum.STRING; } // convert headClazz to head - initColumnProperties(holder, convertAllFiled); + initColumnProperties(holder); initHeadRowNumber(); if (LOGGER.isDebugEnabled()) { @@ -115,7 +115,7 @@ public class ExcelHeadProperty { } } - private void initColumnProperties(Holder holder, Boolean convertAllFiled) { + private void initColumnProperties(Holder holder) { if (headClazz == null) { return; } @@ -124,12 +124,11 @@ public class ExcelHeadProperty { Map indexFiledMap = new TreeMap(); boolean needIgnore = (holder instanceof AbstractWriteHolder) && ( - !CollectionUtils.isEmpty(((AbstractWriteHolder) holder).getExcludeColumnFieldNames()) || !CollectionUtils - .isEmpty(((AbstractWriteHolder) holder).getExcludeColumnIndexes()) || !CollectionUtils - .isEmpty(((AbstractWriteHolder) holder).getIncludeColumnFieldNames()) || !CollectionUtils - .isEmpty(((AbstractWriteHolder) holder).getIncludeColumnIndexes())); - ClassUtils.declaredFields(headClazz, sortedAllFiledMap, indexFiledMap, ignoreMap, convertAllFiled, needIgnore, - holder); + !CollectionUtils.isEmpty(((AbstractWriteHolder)holder).getExcludeColumnFieldNames()) || !CollectionUtils + .isEmpty(((AbstractWriteHolder)holder).getExcludeColumnIndexes()) || !CollectionUtils + .isEmpty(((AbstractWriteHolder)holder).getIncludeColumnFieldNames()) || !CollectionUtils + .isEmpty(((AbstractWriteHolder)holder).getIncludeColumnIndexes())); + ClassUtils.declaredFields(headClazz, sortedAllFiledMap, indexFiledMap, ignoreMap, needIgnore, holder); for (Map.Entry entry : sortedAllFiledMap.entrySet()) { initOneColumnProperty(entry.getKey(), entry.getValue(), indexFiledMap.containsKey(entry.getKey())); diff --git a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java index bba3e487..508a8a4b 100644 --- a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java +++ b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java @@ -1,7 +1,5 @@ package com.alibaba.excel.read.listener; -import java.util.ArrayList; -import java.util.List; import java.util.Map; import com.alibaba.excel.context.AnalysisContext; @@ -42,48 +40,25 @@ public class ModelBuildEventListener implements ReadListener> cellDataMap, ReadSheetHolder readSheetHolder, AnalysisContext context) { int index = 0; - if (context.readWorkbookHolder().getDefaultReturnMap()) { - Map map = MapUtils.newLinkedHashMapWithExpectedSize(cellDataMap.size()); - for (Map.Entry> entry : cellDataMap.entrySet()) { - Integer key = entry.getKey(); - ReadCellData cellData = entry.getValue(); - while (index < key) { - map.put(index, null); - index++; - } - index++; - map.put(key, - (String)ConverterUtils.convertToJavaObject(cellData, null, null, readSheetHolder.converterMap(), - context, context.readRowHolder().getRowIndex(), key)); - } - int headSize = readSheetHolder.excelReadHeadProperty().getHeadMap().size(); - while (index < headSize) { + Map map = MapUtils.newLinkedHashMapWithExpectedSize(cellDataMap.size()); + for (Map.Entry> entry : cellDataMap.entrySet()) { + Integer key = entry.getKey(); + ReadCellData cellData = entry.getValue(); + while (index < key) { map.put(index, null); index++; } - return map; - } else { - // Compatible with the old code the old code returns a list - List list = new ArrayList<>(); - for (Map.Entry> entry : cellDataMap.entrySet()) { - Integer key = entry.getKey(); - ReadCellData cellData = entry.getValue(); - while (index < key) { - list.add(null); - index++; - } - index++; - list.add( - (String)ConverterUtils.convertToJavaObject(cellData, null, null, readSheetHolder.converterMap(), - context, context.readRowHolder().getRowIndex(), key)); - } - int headSize = readSheetHolder.excelReadHeadProperty().getHeadMap().size(); - while (index < headSize) { - list.add(null); - index++; - } - return list; + index++; + map.put(key, + (String)ConverterUtils.convertToJavaObject(cellData, null, null, readSheetHolder.converterMap(), + context, context.readRowHolder().getRowIndex(), key)); + } + int headSize = readSheetHolder.excelReadHeadProperty().getHeadMap().size(); + while (index < headSize) { + map.put(index, null); + index++; } + return map; } private Object buildUserModel(Map> cellDataMap, ReadSheetHolder readSheetHolder, diff --git a/src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java b/src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java index c9e4db93..6db9be9f 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java +++ b/src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java @@ -14,11 +14,14 @@ import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.read.listener.ModelBuildEventListener; import com.alibaba.excel.support.ExcelTypeEnum; +import lombok.Data; + /** * Workbook * * @author Jiaju Zhuang **/ +@Data public class ReadWorkbook extends ReadBasicParameter { /** * Excel type @@ -91,141 +94,4 @@ public class ReadWorkbook extends ReadBasicParameter { * @see CellExtraTypeEnum */ private Set extraReadSet; - /** - * The default is all excel objects.Default is true. - *

    - * if true , you can use {@link com.alibaba.excel.annotation.ExcelIgnore} ignore a field. - *

    - * if false , you must use {@link com.alibaba.excel.annotation.ExcelProperty} to use a filed. - * - * @deprecated Just to be compatible with historical data, The default is always going to be convert all filed. - */ - @Deprecated - private Boolean convertAllFiled; - - /** - * List is returned by default, now map is returned by default - */ - @Deprecated - private Boolean defaultReturnMap; - - public ExcelTypeEnum getExcelType() { - return excelType; - } - - public void setExcelType(ExcelTypeEnum excelType) { - this.excelType = excelType; - } - - public InputStream getInputStream() { - return inputStream; - } - - public void setInputStream(InputStream inputStream) { - this.inputStream = inputStream; - } - - public File getFile() { - return file; - } - - public void setFile(File file) { - this.file = file; - } - - public Boolean getAutoCloseStream() { - return autoCloseStream; - } - - public void setAutoCloseStream(Boolean autoCloseStream) { - this.autoCloseStream = autoCloseStream; - } - - public Object getCustomObject() { - return customObject; - } - - public void setCustomObject(Object customObject) { - this.customObject = customObject; - } - - public Boolean getMandatoryUseInputStream() { - return mandatoryUseInputStream; - } - - public void setMandatoryUseInputStream(Boolean mandatoryUseInputStream) { - this.mandatoryUseInputStream = mandatoryUseInputStream; - } - - public ReadCache getReadCache() { - return readCache; - } - - public void setReadCache(ReadCache readCache) { - this.readCache = readCache; - } - - public Boolean getConvertAllFiled() { - return convertAllFiled; - } - - public void setConvertAllFiled(Boolean convertAllFiled) { - this.convertAllFiled = convertAllFiled; - } - - public Boolean getDefaultReturnMap() { - return defaultReturnMap; - } - - public void setDefaultReturnMap(Boolean defaultReturnMap) { - this.defaultReturnMap = defaultReturnMap; - } - - public Boolean getIgnoreEmptyRow() { - return ignoreEmptyRow; - } - - public void setIgnoreEmptyRow(Boolean ignoreEmptyRow) { - this.ignoreEmptyRow = ignoreEmptyRow; - } - - public ReadCacheSelector getReadCacheSelector() { - return readCacheSelector; - } - - public void setReadCacheSelector(ReadCacheSelector readCacheSelector) { - this.readCacheSelector = readCacheSelector; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getXlsxSAXParserFactoryName() { - return xlsxSAXParserFactoryName; - } - - public void setXlsxSAXParserFactoryName(String xlsxSAXParserFactoryName) { - this.xlsxSAXParserFactoryName = xlsxSAXParserFactoryName; - } - - public Boolean getUseDefaultListener() { - return useDefaultListener; - } - - public void setUseDefaultListener(Boolean useDefaultListener) { - this.useDefaultListener = useDefaultListener; - } - - public Set getExtraReadSet() { - return extraReadSet; - } - - public void setExtraReadSet(Set extraReadSet) { - this.extraReadSet = extraReadSet; - } } diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java index 1b313939..6561d377 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java @@ -46,8 +46,7 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH */ private List> readListenerList; - public AbstractReadHolder(ReadBasicParameter readBasicParameter, AbstractReadHolder parentAbstractReadHolder, - Boolean convertAllFiled) { + public AbstractReadHolder(ReadBasicParameter readBasicParameter, AbstractReadHolder parentAbstractReadHolder) { super(readBasicParameter, parentAbstractReadHolder); if (readBasicParameter.getUseScientificFormat() == null) { @@ -60,7 +59,7 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH } // Initialization property - this.excelReadHeadProperty = new ExcelReadHeadProperty(this, getClazz(), getHead(), convertAllFiled); + this.excelReadHeadProperty = new ExcelReadHeadProperty(this, getClazz(), getHead()); if (readBasicParameter.getHeadRowNumber() == null) { if (parentAbstractReadHolder == null) { if (excelReadHeadProperty.hasHead()) { diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java index 73b00e71..12eb5dc4 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java @@ -59,7 +59,7 @@ public class ReadSheetHolder extends AbstractReadHolder { private ReadCellData tempCellData; public ReadSheetHolder(ReadSheet readSheet, ReadWorkbookHolder readWorkbookHolder) { - super(readSheet, readWorkbookHolder, readWorkbookHolder.getReadWorkbook().getConvertAllFiled()); + super(readSheet, readWorkbookHolder); this.readSheet = readSheet; this.parentReadWorkbookHolder = readWorkbookHolder; this.sheetNo = readSheet.getSheetNo(); diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java index 6693467f..36577471 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java @@ -106,28 +106,13 @@ public class ReadWorkbookHolder extends AbstractReadHolder { */ private Boolean readAll; - /** - * The default is all excel objects.if true , you can use {@link com.alibaba.excel.annotation.ExcelIgnore} ignore a - * field. if false , you must use {@link com.alibaba.excel.annotation.ExcelProperty} to use a filed. - * - * @deprecated Just to be compatible with historical data, The default is always going to be convert all filed. - */ - @Deprecated - private Boolean convertAllFiled; - - /** - * List is returned by default, now map is returned by default - */ - @Deprecated - private Boolean defaultReturnMap; - /** * Prevent repeating sheet */ private Set hasReadSheet; public ReadWorkbookHolder(ReadWorkbook readWorkbook) { - super(readWorkbook, null, readWorkbook.getConvertAllFiled()); + super(readWorkbook, null); this.readWorkbook = readWorkbook; if (readWorkbook.getInputStream() != null) { this.inputStream = readWorkbook.getInputStream(); @@ -162,11 +147,6 @@ public class ReadWorkbookHolder extends AbstractReadHolder { this.readCacheSelector = readWorkbook.getReadCacheSelector(); } } - if (readWorkbook.getDefaultReturnMap() == null) { - this.defaultReturnMap = Boolean.TRUE; - } else { - this.defaultReturnMap = readWorkbook.getDefaultReturnMap(); - } if (readWorkbook.getExtraReadSet() == null) { this.extraReadSet = new HashSet(); } else { diff --git a/src/main/java/com/alibaba/excel/read/metadata/property/ExcelReadHeadProperty.java b/src/main/java/com/alibaba/excel/read/metadata/property/ExcelReadHeadProperty.java index 1b7ae17c..9c332ceb 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/property/ExcelReadHeadProperty.java +++ b/src/main/java/com/alibaba/excel/read/metadata/property/ExcelReadHeadProperty.java @@ -12,7 +12,7 @@ import com.alibaba.excel.metadata.property.ExcelHeadProperty; */ public class ExcelReadHeadProperty extends ExcelHeadProperty { - public ExcelReadHeadProperty(Holder holder, Class headClazz, List> head, Boolean convertAllFiled) { - super(holder, headClazz, head, convertAllFiled); + public ExcelReadHeadProperty(Holder holder, Class headClazz, List> head) { + super(holder, headClazz, head); } } diff --git a/src/main/java/com/alibaba/excel/util/ClassUtils.java b/src/main/java/com/alibaba/excel/util/ClassUtils.java index 96cc11f8..4f14ac2c 100644 --- a/src/main/java/com/alibaba/excel/util/ClassUtils.java +++ b/src/main/java/com/alibaba/excel/util/ClassUtils.java @@ -30,9 +30,8 @@ public class ClassUtils { public static final Map, SoftReference> FIELD_CACHE = new ConcurrentHashMap<>(); public static void declaredFields(Class clazz, Map sortedAllFiledMap, - Map indexFiledMap, Map ignoreMap, Boolean convertAllFiled, - Boolean needIgnore, Holder holder) { - FieldCache fieldCache = getFieldCache(clazz, convertAllFiled); + Map indexFiledMap, Map ignoreMap, Boolean needIgnore, Holder holder) { + FieldCache fieldCache = getFieldCache(clazz); if (fieldCache == null) { return; } @@ -68,12 +67,12 @@ public class ClassUtils { } } - public static void declaredFields(Class clazz, Map sortedAllFiledMap, Boolean convertAllFiled, - Boolean needIgnore, WriteHolder writeHolder) { - declaredFields(clazz, sortedAllFiledMap, null, null, convertAllFiled, needIgnore, writeHolder); + public static void declaredFields(Class clazz, Map sortedAllFiledMap, Boolean needIgnore, + WriteHolder writeHolder) { + declaredFields(clazz, sortedAllFiledMap, null, null, needIgnore, writeHolder); } - private static FieldCache getFieldCache(Class clazz, Boolean convertAllFiled) { + private static FieldCache getFieldCache(Class clazz) { if (clazz == null) { return null; } @@ -86,12 +85,12 @@ public class ClassUtils { if (fieldCacheSoftReference != null && fieldCacheSoftReference.get() != null) { return fieldCacheSoftReference.get(); } - declaredFields(clazz, convertAllFiled); + declaredFields(clazz); } return FIELD_CACHE.get(clazz).get(); } - private static void declaredFields(Class clazz, Boolean convertAllFiled) { + private static void declaredFields(Class clazz) { List tempFieldList = new ArrayList<>(); Class tempClass = clazz; // When the parent class is null, it indicates that the parent class (Object class) has reached the top @@ -108,7 +107,7 @@ public class ClassUtils { ExcelIgnoreUnannotated excelIgnoreUnannotated = clazz.getAnnotation(ExcelIgnoreUnannotated.class); for (Field field : tempFieldList) { - declaredOneField(field, orderFiledMap, indexFiledMap, ignoreMap, excelIgnoreUnannotated, convertAllFiled); + declaredOneField(field, orderFiledMap, indexFiledMap, ignoreMap, excelIgnoreUnannotated); } FIELD_CACHE.put(clazz, new SoftReference( new FieldCache(buildSortedAllFiledMap(orderFiledMap, indexFiledMap), indexFiledMap, ignoreMap))); @@ -138,16 +137,16 @@ public class ClassUtils { } private static void declaredOneField(Field field, Map> orderFiledMap, - Map indexFiledMap, Map ignoreMap, ExcelIgnoreUnannotated excelIgnoreUnannotated, - Boolean convertAllFiled) { + Map indexFiledMap, Map ignoreMap, + ExcelIgnoreUnannotated excelIgnoreUnannotated) { + ExcelIgnore excelIgnore = field.getAnnotation(ExcelIgnore.class); if (excelIgnore != null) { ignoreMap.put(field.getName(), field); return; } ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class); - boolean noExcelProperty = excelProperty == null - && ((convertAllFiled != null && !convertAllFiled) || excelIgnoreUnannotated != null); + boolean noExcelProperty = excelProperty == null && excelIgnoreUnannotated != null; if (noExcelProperty) { ignoreMap.put(field.getName(), field); return; diff --git a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java index 22196555..1bbdd950 100644 --- a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java +++ b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java @@ -65,21 +65,6 @@ public class ExcelWriterBuilder extends AbstractExcelWriterParameterBuilder - * Default true - * - * @param convertAllFiled - * @return - * @deprecated Just to be compatible with historical data, The default is always going to be convert all filed. - */ - @Deprecated - public ExcelWriterBuilder convertAllFiled(Boolean convertAllFiled) { - writeWorkbook.setConvertAllFiled(convertAllFiled); - return this; - } public ExcelWriterBuilder excelType(ExcelTypeEnum excelType) { writeWorkbook.setExcelType(excelType); diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 01f9b53d..1b5e12a5 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -183,8 +183,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { .isEmpty(writeWorkbookHolder.getExcludeColumnIndexes()) || !CollectionUtils .isEmpty(writeWorkbookHolder.getIncludeColumnFieldNames()) || !CollectionUtils .isEmpty(writeWorkbookHolder.getIncludeColumnIndexes()); - ClassUtils.declaredFields(clazz, sortedAllFiledMap, - writeWorkbookHolder.getWriteWorkbook().getConvertAllFiled(), needIgnore, writeWorkbookHolder); + ClassUtils.declaredFields(clazz, sortedAllFiledMap, needIgnore, writeWorkbookHolder); } } diff --git a/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java b/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java index 9f4bea5c..a3d99d2b 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java +++ b/src/main/java/com/alibaba/excel/write/metadata/WriteWorkbook.java @@ -74,15 +74,4 @@ public class WriteWorkbook extends WriteBasicParameter { * Excel is also written in the event of an exception being thrown.The default false. */ private Boolean writeExcelOnException; - /** - * The default is all excel objects.Default is true. - *

    - * if true , you can use {@link com.alibaba.excel.annotation.ExcelIgnore} ignore a field. - *

    - * if false , you must use {@link com.alibaba.excel.annotation.ExcelProperty} to use a filed. - * - * @deprecated Just to be compatible with historical data, The default is always going to be convert all filed. - */ - @Deprecated - private Boolean convertAllFiled; } diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java index 96d55396..2867bdc5 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java @@ -93,11 +93,9 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ */ private Collection includeColumnFieldNames; - public AbstractWriteHolder(WriteBasicParameter writeBasicParameter, AbstractWriteHolder parentAbstractWriteHolder, - Boolean convertAllField) { + public AbstractWriteHolder(WriteBasicParameter writeBasicParameter, AbstractWriteHolder parentAbstractWriteHolder) { super(writeBasicParameter, parentAbstractWriteHolder); - if (writeBasicParameter.getUseScientificFormat() != null) { throw new UnsupportedOperationException("Currently does not support setting useScientificFormat."); } @@ -164,7 +162,7 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ } // Initialization property - this.excelWriteHeadProperty = new ExcelWriteHeadProperty(this, getClazz(), getHead(), convertAllField); + this.excelWriteHeadProperty = new ExcelWriteHeadProperty(this, getClazz(), getHead()); // Set writeHandlerMap List handlerList = new ArrayList(); diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java index 57f13584..dbce0b8b 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteSheetHolder.java @@ -77,7 +77,7 @@ public class WriteSheetHolder extends AbstractWriteHolder { private Integer lastRowIndex; public WriteSheetHolder(WriteSheet writeSheet, WriteWorkbookHolder writeWorkbookHolder) { - super(writeSheet, writeWorkbookHolder, writeWorkbookHolder.getWriteWorkbook().getConvertAllFiled()); + super(writeSheet, writeWorkbookHolder); this.writeSheet = writeSheet; if (writeSheet.getSheetNo() == null && StringUtils.isEmpty(writeSheet.getSheetName())) { this.sheetNo = 0; diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteTableHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteTableHolder.java index f7242a2a..e353a44c 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteTableHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteTableHolder.java @@ -3,11 +3,14 @@ package com.alibaba.excel.write.metadata.holder; import com.alibaba.excel.enums.HolderEnum; import com.alibaba.excel.write.metadata.WriteTable; +import lombok.Data; + /** * sheet holder * * @author Jiaju Zhuang */ +@Data public class WriteTableHolder extends AbstractWriteHolder { /*** * poi sheet @@ -22,38 +25,13 @@ public class WriteTableHolder extends AbstractWriteHolder { */ private WriteTable writeTable; - public WriteTableHolder(WriteTable writeTable, WriteSheetHolder writeSheetHolder, - WriteWorkbookHolder writeWorkbookHolder) { - super(writeTable, writeSheetHolder, writeWorkbookHolder.getWriteWorkbook().getConvertAllFiled()); + public WriteTableHolder(WriteTable writeTable, WriteSheetHolder writeSheetHolder) { + super(writeTable, writeSheetHolder); this.parentWriteSheetHolder = writeSheetHolder; this.tableNo = writeTable.getTableNo(); this.writeTable = writeTable; } - public WriteSheetHolder getParentWriteSheetHolder() { - return parentWriteSheetHolder; - } - - public void setParentWriteSheetHolder(WriteSheetHolder parentWriteSheetHolder) { - this.parentWriteSheetHolder = parentWriteSheetHolder; - } - - public Integer getTableNo() { - return tableNo; - } - - public void setTableNo(Integer tableNo) { - this.tableNo = tableNo; - } - - public WriteTable getWriteTable() { - return writeTable; - } - - public void setWriteTable(WriteTable writeTable) { - this.writeTable = writeTable; - } - @Override public HolderEnum holderType() { return HolderEnum.TABLE; diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java index a7871ba7..fe894454 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java +++ b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java @@ -140,7 +140,7 @@ public class WriteWorkbookHolder extends AbstractWriteHolder { private Map dataFormatMap; public WriteWorkbookHolder(WriteWorkbook writeWorkbook) { - super(writeWorkbook, null, writeWorkbook.getConvertAllFiled()); + super(writeWorkbook, null); this.writeWorkbook = writeWorkbook; this.file = writeWorkbook.getFile(); if (file != null) { diff --git a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java index 26af5512..2e8cc9d2 100644 --- a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java +++ b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java @@ -7,7 +7,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import com.alibaba.excel.annotation.format.NumberFormat; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentFontStyle; import com.alibaba.excel.annotation.write.style.ContentLoopMerge; @@ -17,9 +16,6 @@ import com.alibaba.excel.annotation.write.style.HeadFontStyle; import com.alibaba.excel.annotation.write.style.HeadRowHeight; import com.alibaba.excel.annotation.write.style.HeadStyle; import com.alibaba.excel.annotation.write.style.OnceAbsoluteMerge; -import com.alibaba.excel.converters.ConverterKeyBuild; -import com.alibaba.excel.converters.DefaultConverterLoader; -import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.HeadKindEnum; import com.alibaba.excel.metadata.CellRange; import com.alibaba.excel.metadata.Head; @@ -44,23 +40,23 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty { private RowHeightProperty contentRowHeightProperty; private OnceAbsoluteMergeProperty onceAbsoluteMergeProperty; - public ExcelWriteHeadProperty(Holder holder, Class headClazz, List> head, Boolean convertAllFiled) { - super(holder, headClazz, head, convertAllFiled); + public ExcelWriteHeadProperty(Holder holder, Class headClazz, List> head) { + super(holder, headClazz, head); if (getHeadKind() != HeadKindEnum.CLASS) { return; } this.headRowHeightProperty = - RowHeightProperty.build((HeadRowHeight) headClazz.getAnnotation(HeadRowHeight.class)); + RowHeightProperty.build((HeadRowHeight)headClazz.getAnnotation(HeadRowHeight.class)); this.contentRowHeightProperty = - RowHeightProperty.build((ContentRowHeight) headClazz.getAnnotation(ContentRowHeight.class)); + RowHeightProperty.build((ContentRowHeight)headClazz.getAnnotation(ContentRowHeight.class)); this.onceAbsoluteMergeProperty = - OnceAbsoluteMergeProperty.build((OnceAbsoluteMerge) headClazz.getAnnotation(OnceAbsoluteMerge.class)); + OnceAbsoluteMergeProperty.build((OnceAbsoluteMerge)headClazz.getAnnotation(OnceAbsoluteMerge.class)); - ColumnWidth parentColumnWidth = (ColumnWidth) headClazz.getAnnotation(ColumnWidth.class); - HeadStyle parentHeadStyle = (HeadStyle) headClazz.getAnnotation(HeadStyle.class); - HeadFontStyle parentHeadFontStyle = (HeadFontStyle) headClazz.getAnnotation(HeadFontStyle.class); - ContentStyle parentContentStyle = (ContentStyle) headClazz.getAnnotation(ContentStyle.class); - ContentFontStyle parentContentFontStyle = (ContentFontStyle) headClazz.getAnnotation(ContentFontStyle.class); + ColumnWidth parentColumnWidth = (ColumnWidth)headClazz.getAnnotation(ColumnWidth.class); + HeadStyle parentHeadStyle = (HeadStyle)headClazz.getAnnotation(HeadStyle.class); + HeadFontStyle parentHeadFontStyle = (HeadFontStyle)headClazz.getAnnotation(HeadFontStyle.class); + ContentStyle parentContentStyle = (ContentStyle)headClazz.getAnnotation(ContentStyle.class); + ContentFontStyle parentContentFontStyle = (ContentFontStyle)headClazz.getAnnotation(ContentFontStyle.class); for (Map.Entry entry : getContentPropertyMap().entrySet()) { Integer index = entry.getKey(); From c6915a469c5f2136986888c5ec56810f2dac3f74 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 16:38:41 +0800 Subject: [PATCH 113/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=97=A0=E5=AF=B9?= =?UTF-8?q?=E8=B1=A1=E8=AF=BB=20=E8=BF=94=E5=9B=9Emap=E7=9A=84size?= =?UTF-8?q?=E5=8F=AF=E8=83=BD=E4=BC=9A=E5=A4=B4=E7=9A=84size=E4=B8=8D?= =?UTF-8?q?=E4=B8=80=E8=87=B4=20[Issue=20#2014]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../listener/ModelBuildEventListener.java | 85 +++++++------------ .../read/metadata/holder/ReadSheetHolder.java | 5 ++ .../easyexcel/test/temp/Lock2Test.java | 27 +++--- update.md | 1 + 4 files changed, 53 insertions(+), 65 deletions(-) diff --git a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java index f56eb26c..6a814f4d 100644 --- a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java +++ b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java @@ -16,17 +16,21 @@ import com.alibaba.excel.util.ConverterUtils; import com.alibaba.excel.util.FieldUtils; import com.alibaba.excel.util.MapUtils; +import org.apache.commons.collections4.CollectionUtils; + /** * Convert to the object the user needs * * @author jipengfei */ -public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener> { - private int headSize; +public class ModelBuildEventListener implements ReadListener>> { @Override - public void invokeHead(Map cellDataMap, AnalysisContext context) { - this.headSize = cellDataMap.size(); + public void invokeHead(Map> cellDataMap, AnalysisContext context) { + if (context.readSheetHolder().getMaxDataHeadSize() == null + || context.readSheetHolder().getMaxDataHeadSize() < CollectionUtils.size(cellDataMap)) { + context.readSheetHolder().setMaxDataHeadSize(CollectionUtils.size(cellDataMap)); + } } @Override @@ -43,61 +47,38 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener private Object buildStringList(Map> cellDataMap, ReadSheetHolder readSheetHolder, AnalysisContext context) { int index = 0; - if (context.readWorkbookHolder().getDefaultReturnMap()) { - Map map = new LinkedHashMap(cellDataMap.size() * 4 / 3 + 1); - for (Map.Entry entry : cellDataMap.entrySet()) { - Integer key = entry.getKey(); - CellData cellData = entry.getValue(); - while (index < key) { - map.put(index, null); - index++; - } - index++; - if (cellData.getType() == CellDataTypeEnum.EMPTY) { - map.put(key, null); - continue; - } - map.put(key, - (String)ConverterUtils.convertToJavaObject(cellData, null, null, currentReadHolder.converterMap(), - currentReadHolder.globalConfiguration(), context.readRowHolder().getRowIndex(), key)); - } - int headSize = currentReadHolder.excelReadHeadProperty().getHeadMap().size() == 0 - ? this.headSize : currentReadHolder.excelReadHeadProperty().getHeadMap().size(); - while (index < headSize) { + Map map = MapUtils.newLinkedHashMapWithExpectedSize(cellDataMap.size()); + for (Map.Entry> entry : cellDataMap.entrySet()) { + Integer key = entry.getKey(); + ReadCellData cellData = entry.getValue(); + while (index < key) { map.put(index, null); index++; } - return map; - } else { - // Compatible with the old code the old code returns a list - List list = new ArrayList(); - for (Map.Entry entry : cellDataMap.entrySet()) { - Integer key = entry.getKey(); - CellData cellData = entry.getValue(); - while (index < key) { - list.add(null); - index++; - } - index++; - if (cellData.getType() == CellDataTypeEnum.EMPTY) { - list.add(null); - continue; - } - list.add( - (String)ConverterUtils.convertToJavaObject(cellData, null, null, currentReadHolder.converterMap(), - currentReadHolder.globalConfiguration(), context.readRowHolder().getRowIndex(), key)); - } - int headSize = currentReadHolder.excelReadHeadProperty().getHeadMap().size() == 0 - ? this.headSize : currentReadHolder.excelReadHeadProperty().getHeadMap().size(); - while (index < headSize) { - list.add(null); - index++; - } - return list; + index++; + map.put(key, + (String)ConverterUtils.convertToJavaObject(cellData, null, null, readSheetHolder.converterMap(), + context, context.readRowHolder().getRowIndex(), key)); + } + // fix https://github.com/alibaba/easyexcel/issues/2014 + int headSize = calculateHeadSize(readSheetHolder); + while (index < headSize) { + map.put(index, null); + index++; } return map; } + private int calculateHeadSize(ReadSheetHolder readSheetHolder) { + if (readSheetHolder.excelReadHeadProperty().getHeadMap().size() > 0) { + return readSheetHolder.excelReadHeadProperty().getHeadMap().size(); + } + if (readSheetHolder.getMaxDataHeadSize() != null) { + return readSheetHolder.getMaxDataHeadSize(); + } + return 0; + } + private Object buildUserModel(Map> cellDataMap, ReadSheetHolder readSheetHolder, AnalysisContext context) { ExcelReadHeadProperty excelReadHeadProperty = readSheetHolder.excelReadHeadProperty(); diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java index 12eb5dc4..61b17587 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java +++ b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java @@ -57,6 +57,11 @@ public class ReadSheetHolder extends AbstractReadHolder { * Current CellData */ private ReadCellData tempCellData; + /** + * Read the size of the largest head in sheet head data. + * see https://github.com/alibaba/easyexcel/issues/2014 + */ + private Integer maxDataHeadSize; public ReadSheetHolder(ReadSheet readSheet, ReadWorkbookHolder readWorkbookHolder) { super(readSheet, readWorkbookHolder); diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java index e8545670..94f8ca31 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java @@ -5,14 +5,6 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import org.apache.poi.hssf.util.CellReference; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alibaba.easyexcel.test.demo.write.DemoData; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; @@ -21,6 +13,15 @@ import com.alibaba.excel.write.metadata.style.WriteFont; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy; import com.alibaba.fastjson.JSON; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.poi.hssf.util.CellReference; +import org.apache.poi.ss.usermodel.FillPatternType; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.junit.Ignore; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * 临时测试 * @@ -33,12 +34,12 @@ public class Lock2Test { @Test public void test() throws Exception { -// File file = TestFileUtil.readUserHomeFile("test/test6.xls"); - File file = new File("/Users/zhuangjiaju/Downloads/1.xlsx"); + File file = TestFileUtil.readUserHomeFile("test/test4.xlsx"); - List list = EasyExcel.read(file).sheet(0).headRowNumber(0).doReadSync(); + List list = EasyExcel.read(file).sheet(0).doReadSync(); LOGGER.info("数据:{}", list.size()); for (Object data : list) { + LOGGER.info("返回数据:{}", CollectionUtils.size(data)); LOGGER.info("返回数据:{}", JSON.toJSONString(data)); } } @@ -60,7 +61,7 @@ public class Lock2Test { // 背景设置为红色 headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); WriteFont headWriteFont = new WriteFont(); - headWriteFont.setFontHeightInPoints((short) 20); + headWriteFont.setFontHeightInPoints((short)20); headWriteCellStyle.setWriteFont(headWriteFont); // 内容的策略 WriteCellStyle contentWriteCellStyle = new WriteCellStyle(); @@ -70,7 +71,7 @@ public class Lock2Test { contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); WriteFont contentWriteFont = new WriteFont(); // 字体大小 - contentWriteFont.setFontHeightInPoints((short) 20); + contentWriteFont.setFontHeightInPoints((short)20); contentWriteCellStyle.setWriteFont(contentWriteFont); // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现 HorizontalCellStyleStrategy horizontalCellStyleStrategy = diff --git a/update.md b/update.md index 23aef9c6..7192df0d 100644 --- a/update.md +++ b/update.md @@ -17,6 +17,7 @@ * `Converter`支持null转换 [Issue #1776](https://github.com/alibaba/easyexcel/issues/1776) * cglib 新增命名策略,防止和`spring`的冲突 [Issue #2064](https://github.com/alibaba/easyexcel/issues/2064) * 修改填充可能填充错误的bug [Issue #2035](https://github.com/alibaba/easyexcel/issues/2035) +* 修复无对象读 返回map的size可能会头的size不一致 [Issue #2014](https://github.com/alibaba/easyexcel/issues/2014) # 2.2.10 * 修复读取的时候用string接收数字 可能四舍五入不一致的bug From 041b25abe6fd66afd1ae76a16b6eb3994eb1414e Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 16:46:24 +0800 Subject: [PATCH 114/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/excel/context/WriteContextImpl.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java index 24045101..8e50eb74 100644 --- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java @@ -179,9 +179,12 @@ public class WriteContextImpl implements WriteContext { writeSheetHolder .setCachedSheet(writeWorkbookHolder.getCachedWorkbook().getSheet(writeSheetHolder.getSheetName())); } - } catch (Exception e) { - LOGGER.error("initSheet exception ",e); - currentSheet = createSheet(); + } catch (IllegalArgumentException e) { + if (e.getMessage() != null && e.getMessage().contains(NO_SHEETS)) { + currentSheet = createSheet(); + } else { + throw e; + } } if (currentSheet == null) { currentSheet = createSheet(); From 2dabf6cce3a5abd35fd0b0289a4e668914d7d328 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 16:58:35 +0800 Subject: [PATCH 115/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/excel/context/WriteContextImpl.java | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java index cc260ad1..c9be2233 100644 --- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java @@ -437,7 +437,7 @@ public class WriteContextImpl implements WriteContext { if (writeWorkbookHolder.getFile() != null) { return false; } - File tempXlsx = FileUtils.createTmpFile(UUID.randomUUID().toString() + ".xlsx"); + File tempXlsx = FileUtils.createTmpFile(UUID.randomUUID() + ".xlsx"); FileOutputStream tempFileOutputStream = new FileOutputStream(tempXlsx); try { writeWorkbookHolder.getWorkbook().write(tempFileOutputStream); @@ -483,19 +483,6 @@ public class WriteContextImpl implements WriteContext { POIFSFileSystem fileSystem = new POIFSFileSystem(); Encryptor encryptor = new EncryptionInfo(EncryptionMode.standard).getEncryptor(); encryptor.confirmPassword(writeWorkbookHolder.getPassword()); - OPCPackage opcPackage = null; - OutputStream outputStream = null; - try { - opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE); - outputStream = encryptor.getDataStream(fileSystem); - opcPackage.save(outputStream); - } finally { - if (opcPackage != null) { - opcPackage.close(); - } - if (outputStream != null) { - outputStream.close(); - } try (OPCPackage opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE); OutputStream outputStream = encryptor.getDataStream(fileSystem)) { opcPackage.save(outputStream); From 5aede698ea99bcbde0de4fadcfecce8fe098c954 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 17:17:19 +0800 Subject: [PATCH 116/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E8=AF=BB=E5=8F=9607?= =?UTF-8?q?=E6=B3=A8=E9=87=8A=E7=9A=84=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java index 7e771a6f..329f5250 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java @@ -233,8 +233,8 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor { return; } Iterator cellAddresses = commentsTable.getCellAddresses(); - for (Iterator it = cellAddresses; it.hasNext(); ) { - CellAddress cellAddress = it.next(); + while (cellAddresses.hasNext()) { + CellAddress cellAddress = cellAddresses.next(); XSSFComment cellComment = commentsTable.findCellComment(cellAddress); CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.COMMENT, cellComment.getString().toString(), cellAddress.getRow(), cellAddress.getColumn()); From 59d72a723efab470ff12e144ae3d43e3c14134d8 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 17:28:31 +0800 Subject: [PATCH 117/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/excel/write/executor/ExcelWriteFillExecutor.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 30cc4ab2..1c45c49d 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -367,9 +367,6 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { return analysisCellList; } Sheet sheet = writeContext.writeSheetHolder().getCachedSheet(); - if (sheet.getLastRowNum() == 0) { - throw new ExcelCommonException(sheet.getSheetName() + " not exists in the excel to be written"); - } Map> firstRowCache = MapUtils.newHashMapWithExpectedSize(8); for (int i = 0; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); From 3f2f21f955cf3f56674b22f5bfce640407b8455e Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 19:58:00 +0800 Subject: [PATCH 118/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E5=A4=B4=E5=8F=AF=E8=83=BD=E5=BC=82=E5=B8=B8=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/excel/metadata/CellRange.java | 35 ++----------------- .../property/ExcelWriteHeadProperty.java | 12 ++++--- update.md | 2 ++ 3 files changed, 12 insertions(+), 37 deletions(-) diff --git a/src/main/java/com/alibaba/excel/metadata/CellRange.java b/src/main/java/com/alibaba/excel/metadata/CellRange.java index 6805526e..bd0f54f9 100644 --- a/src/main/java/com/alibaba/excel/metadata/CellRange.java +++ b/src/main/java/com/alibaba/excel/metadata/CellRange.java @@ -1,8 +1,11 @@ package com.alibaba.excel.metadata; +import lombok.Data; + /** * @author jipengfei */ +@Data public class CellRange { private int firstRow; @@ -16,36 +19,4 @@ public class CellRange { this.firstCol = firstCol; this.lastCol = lastCol; } - - public int getFirstRow() { - return firstRow; - } - - public void setFirstRow(int firstRow) { - this.firstRow = firstRow; - } - - public int getLastRow() { - return lastRow; - } - - public void setLastRow(int lastRow) { - this.lastRow = lastRow; - } - - public int getFirstCol() { - return firstCol; - } - - public void setFirstCol(int firstCol) { - this.firstCol = firstCol; - } - - public int getLastCol() { - return lastCol; - } - - public void setLastCol(int lastCol) { - this.lastCol = lastCol; - } } diff --git a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java index bb8f528b..c2779136 100644 --- a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java +++ b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java @@ -146,19 +146,21 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty { int lastCol = i; int lastRow = j; for (int k = i + 1; k < headList.size(); k++) { - boolean flag = (j - 1 >= 0) && !headList.get(k).getHeadNameList().get(j - 1).equals(headName); - if (headList.get(k).getHeadNameList().get(j).equals(headName) && flag) { - alreadyRangeSet.add(k + "-" + j); + String key = k + "-" + j; + if (headList.get(k).getHeadNameList().get(j).equals(headName) && !alreadyRangeSet.contains(key)) { + alreadyRangeSet.add(key); lastCol = k; } else { break; } } - Set tempAlreadyRangeSet = new HashSet(); + Set tempAlreadyRangeSet = new HashSet<>(); outer: for (int k = j + 1; k < headNameList.size(); k++) { for (int l = i; l <= lastCol; l++) { - if (headList.get(l).getHeadNameList().get(k).equals(headName)) { + String key = l + "-" + k; + if (headList.get(l).getHeadNameList().get(k).equals(headName) && !alreadyRangeSet.contains( + key)) { tempAlreadyRangeSet.add(l + "-" + k); } else { break outer; diff --git a/update.md b/update.md index 7192df0d..4d4d96dc 100644 --- a/update.md +++ b/update.md @@ -18,6 +18,8 @@ * cglib 新增命名策略,防止和`spring`的冲突 [Issue #2064](https://github.com/alibaba/easyexcel/issues/2064) * 修改填充可能填充错误的bug [Issue #2035](https://github.com/alibaba/easyexcel/issues/2035) * 修复无对象读 返回map的size可能会头的size不一致 [Issue #2014](https://github.com/alibaba/easyexcel/issues/2014) +* 修复合并头可能异常的bug [Issue #1662](https://github.com/alibaba/easyexcel/issues/1662) + # 2.2.10 * 修复读取的时候用string接收数字 可能四舍五入不一致的bug From bc4ba98d58be35b31c62b348fc72612fb1f619ff Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 20:37:22 +0800 Subject: [PATCH 119/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=A1=AB=E5=85=85?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E6=A8=AA=E5=90=91=E6=A0=B7=E5=BC=8F=E7=AD=96?= =?UTF-8?q?=E7=95=A5=E6=8A=A5=E9=94=99=20[Issue=20#1651]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../style/HorizontalCellStyleStrategy.java | 34 ++++++++++++++----- update.md | 1 + 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java index 0d4228f5..d33a2a74 100644 --- a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java @@ -2,7 +2,7 @@ package com.alibaba.excel.write.style; import java.util.List; -import com.alibaba.excel.metadata.Head; +import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.util.ListUtils; import com.alibaba.excel.write.handler.context.CellWriteHandlerContext; import com.alibaba.excel.write.metadata.style.WriteCellStyle; @@ -14,7 +14,7 @@ import org.apache.commons.collections4.CollectionUtils; * * @author Jiaju Zhuang */ -public class HorizontalCellStyleStrategy extends AbstractVerticalCellStyleStrategy { +public class HorizontalCellStyleStrategy extends AbstractCellStyleStrategy { private WriteCellStyle headWriteCellStyle; private List contentWriteCellStyleList; @@ -33,16 +33,34 @@ public class HorizontalCellStyleStrategy extends AbstractVerticalCellStyleStrate } @Override - protected WriteCellStyle headCellStyle(Head head) { - return headWriteCellStyle; + protected void setHeadCellStyle(CellWriteHandlerContext context) { + if (!continueProcessing(context) || headWriteCellStyle == null) { + return; + } + WriteCellData cellData = context.getCellDataList().get(0); + cellData.setWriteCellStyle(headWriteCellStyle); } @Override - protected WriteCellStyle contentCellStyle(CellWriteHandlerContext context) { - if (CollectionUtils.isEmpty(contentWriteCellStyleList)) { - return null; + protected void setContentCellStyle(CellWriteHandlerContext context) { + if (!continueProcessing(context) || CollectionUtils.isEmpty(contentWriteCellStyleList)) { + return; + } + WriteCellData cellData = context.getCellDataList().get(0); + if (context.getRelativeRowIndex() == null || context.getRelativeRowIndex() <= 0) { + cellData.setWriteCellStyle(contentWriteCellStyleList.get(0)); + } else { + cellData.setWriteCellStyle( + contentWriteCellStyleList.get(context.getRelativeRowIndex() % contentWriteCellStyleList.size())); + } + } + + protected boolean continueProcessing(CellWriteHandlerContext context) { + List> cellDataList = context.getCellDataList(); + if (CollectionUtils.isEmpty(cellDataList) || cellDataList.size() > 1) { + return false; } - return contentWriteCellStyleList.get(context.getRelativeRowIndex() % contentWriteCellStyleList.size()); + return true; } } diff --git a/update.md b/update.md index 4d4d96dc..c2cbf89c 100644 --- a/update.md +++ b/update.md @@ -19,6 +19,7 @@ * 修改填充可能填充错误的bug [Issue #2035](https://github.com/alibaba/easyexcel/issues/2035) * 修复无对象读 返回map的size可能会头的size不一致 [Issue #2014](https://github.com/alibaba/easyexcel/issues/2014) * 修复合并头可能异常的bug [Issue #1662](https://github.com/alibaba/easyexcel/issues/1662) +* 修复填充调用横向样式策略报错 [Issue #1651](https://github.com/alibaba/easyexcel/issues/1651) # 2.2.10 From 6a1717908661ab631485fb5db45dd1e7c60944d2 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 20:40:46 +0800 Subject: [PATCH 120/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=A1=AB=E5=85=85?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E6=A8=AA=E5=90=91=E6=A0=B7=E5=BC=8F=E7=AD=96?= =?UTF-8?q?=E7=95=A5=E6=8A=A5=E9=94=99=20[Issue=20#1651]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../style/AbstractVerticalCellStyleStrategy.java | 10 +++++----- .../write/style/HorizontalCellStyleStrategy.java | 11 ++++------- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java index 8ba8bd2c..7d8e1b46 100644 --- a/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java @@ -18,7 +18,7 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl @Override protected void setHeadCellStyle(CellWriteHandlerContext context) { - if (!continueProcessing(context)) { + if (stopProcessing(context)) { return; } WriteCellData cellData = context.getCellDataList().get(0); @@ -27,7 +27,7 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl @Override protected void setContentCellStyle(CellWriteHandlerContext context) { - if (!continueProcessing(context)) { + if (stopProcessing(context)) { return; } WriteCellData cellData = context.getCellDataList().get(0); @@ -64,11 +64,11 @@ public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyl + "'contentCellStyle(Head head)' must be implemented."); } - protected boolean continueProcessing(CellWriteHandlerContext context) { + protected boolean stopProcessing(CellWriteHandlerContext context) { List> cellDataList = context.getCellDataList(); if (CollectionUtils.isEmpty(cellDataList) || cellDataList.size() > 1) { - return false; + return true; } - return context.getHeadData() != null; + return context.getHeadData() == null; } } diff --git a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java index d33a2a74..58b0836a 100644 --- a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java @@ -34,7 +34,7 @@ public class HorizontalCellStyleStrategy extends AbstractCellStyleStrategy { @Override protected void setHeadCellStyle(CellWriteHandlerContext context) { - if (!continueProcessing(context) || headWriteCellStyle == null) { + if (stopProcessing(context) || headWriteCellStyle == null) { return; } WriteCellData cellData = context.getCellDataList().get(0); @@ -43,7 +43,7 @@ public class HorizontalCellStyleStrategy extends AbstractCellStyleStrategy { @Override protected void setContentCellStyle(CellWriteHandlerContext context) { - if (!continueProcessing(context) || CollectionUtils.isEmpty(contentWriteCellStyleList)) { + if (stopProcessing(context) || CollectionUtils.isEmpty(contentWriteCellStyleList)) { return; } WriteCellData cellData = context.getCellDataList().get(0); @@ -55,12 +55,9 @@ public class HorizontalCellStyleStrategy extends AbstractCellStyleStrategy { } } - protected boolean continueProcessing(CellWriteHandlerContext context) { + protected boolean stopProcessing(CellWriteHandlerContext context) { List> cellDataList = context.getCellDataList(); - if (CollectionUtils.isEmpty(cellDataList) || cellDataList.size() > 1) { - return false; - } - return true; + return CollectionUtils.isEmpty(cellDataList) || cellDataList.size() > 1; } } From 56ab48e3641f1ca4adbccb1263cb4e25e8ac96c9 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 22:39:40 +0800 Subject: [PATCH 121/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=B8=8D=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E8=A1=8C=E9=AB=98=E7=9A=84=E9=97=AE=E9=A2=98=20[Issue?= =?UTF-8?q?=20#1869]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../executor/ExcelWriteFillExecutor.java | 11 ++++-- .../poi/hssf/usermodel/PoiHssfUtils.java | 37 +++++++++++++++++++ .../test/temp/issue1662/Issue1662Test.java | 12 +++--- update.md | 1 + 4 files changed, 52 insertions(+), 9 deletions(-) create mode 100644 src/main/java/org/apache/poi/hssf/usermodel/PoiHssfUtils.java diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 1c45c49d..9041419a 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -28,6 +28,7 @@ import com.alibaba.excel.write.metadata.fill.FillWrapper; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import org.apache.commons.collections4.CollectionUtils; +import org.apache.poi.hssf.usermodel.PoiHssfUtils; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; @@ -322,6 +323,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { AnalysisCell analysisCell, boolean isOriginalCell) { Row row = sheet.getRow(lastRowIndex); if (row != null) { + checkRowHeight(analysisCell, fillConfig, isOriginalCell, row); return row; } row = cachedSheet.getRow(lastRowIndex); @@ -351,7 +353,8 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { if (!analysisCell.getFirstRow() || !WriteDirectionEnum.VERTICAL.equals(fillConfig.getDirection())) { return; } - if (isOriginalCell) { + // fix https://github.com/alibaba/easyexcel/issues/1869 + if (isOriginalCell && PoiHssfUtils.customHeight(row)) { collectionRowHeightCache.put(currentUniqueDataFlag, row.getHeight()); return; } @@ -391,9 +394,9 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { /** * To prepare data * - * @param cell cell - * @param rowIndex row index - * @param columnIndex column index + * @param cell cell + * @param rowIndex row index + * @param columnIndex column index * @param firstRowCache first row cache * @return Returns the data that the cell needs to replace */ diff --git a/src/main/java/org/apache/poi/hssf/usermodel/PoiHssfUtils.java b/src/main/java/org/apache/poi/hssf/usermodel/PoiHssfUtils.java new file mode 100644 index 00000000..80f7f3b8 --- /dev/null +++ b/src/main/java/org/apache/poi/hssf/usermodel/PoiHssfUtils.java @@ -0,0 +1,37 @@ +package org.apache.poi.hssf.usermodel; + +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.util.BitField; +import org.apache.poi.util.BitFieldFactory; +import org.apache.poi.xssf.usermodel.XSSFRow; + +/** + * utils + * + * @author Jiaju Zhuang + */ +public class PoiHssfUtils { + + /** + * Whether to customize the height + */ + public static final BitField CUSTOM_HEIGHT = BitFieldFactory.getInstance(0x640); + + /** + * Whether to customize the height + * + * @param row + * @return + */ + public static boolean customHeight(Row row) { + if (row instanceof XSSFRow) { + XSSFRow xssfRow = (XSSFRow)row; + return xssfRow.getCTRow().getCustomHeight(); + } + if (row instanceof HSSFRow) { + HSSFRow hssfRow = (HSSFRow)row; + return CUSTOM_HEIGHT.getValue(hssfRow.getRowRecord().getOptionFlags()) == 1; + } + return false; + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Issue1662Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Issue1662Test.java index 8fa5a842..cea7e5ee 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Issue1662Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/issue1662/Issue1662Test.java @@ -1,14 +1,16 @@ package com.alibaba.easyexcel.test.temp.issue1662; -import com.alibaba.easyexcel.test.util.TestFileUtil; -import com.alibaba.excel.EasyExcel; -import org.junit.Test; - - import java.util.ArrayList; import java.util.Date; import java.util.List; +import com.alibaba.easyexcel.test.util.TestFileUtil; +import com.alibaba.excel.EasyExcel; + +import org.junit.Ignore; +import org.junit.Test; + +@Ignore public class Issue1662Test { @Test public void test1662() { diff --git a/update.md b/update.md index c2cbf89c..45f4a227 100644 --- a/update.md +++ b/update.md @@ -20,6 +20,7 @@ * 修复无对象读 返回map的size可能会头的size不一致 [Issue #2014](https://github.com/alibaba/easyexcel/issues/2014) * 修复合并头可能异常的bug [Issue #1662](https://github.com/alibaba/easyexcel/issues/1662) * 修复填充调用横向样式策略报错 [Issue #1651](https://github.com/alibaba/easyexcel/issues/1651) +* 修复不自动行高的问题 [Issue #1869](https://github.com/alibaba/easyexcel/issues/1869) # 2.2.10 From 6351fe2c18acd9c42fc19148721a68b5b00317fc Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 22:40:23 +0800 Subject: [PATCH 122/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=B8=8D=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E8=A1=8C=E9=AB=98=E7=9A=84=E9=97=AE=E9=A2=98=20[Issue?= =?UTF-8?q?=20#1869]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/excel/write/executor/ExcelWriteFillExecutor.java | 4 ++-- .../poi/hssf/usermodel/{PoiHssfUtils.java => PoiUtils.java} | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename src/main/java/org/apache/poi/hssf/usermodel/{PoiHssfUtils.java => PoiUtils.java} (96%) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index 9041419a..e7fdcd87 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -28,7 +28,7 @@ import com.alibaba.excel.write.metadata.fill.FillWrapper; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import org.apache.commons.collections4.CollectionUtils; -import org.apache.poi.hssf.usermodel.PoiHssfUtils; +import org.apache.poi.hssf.usermodel.PoiUtils; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; @@ -354,7 +354,7 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { return; } // fix https://github.com/alibaba/easyexcel/issues/1869 - if (isOriginalCell && PoiHssfUtils.customHeight(row)) { + if (isOriginalCell && PoiUtils.customHeight(row)) { collectionRowHeightCache.put(currentUniqueDataFlag, row.getHeight()); return; } diff --git a/src/main/java/org/apache/poi/hssf/usermodel/PoiHssfUtils.java b/src/main/java/org/apache/poi/hssf/usermodel/PoiUtils.java similarity index 96% rename from src/main/java/org/apache/poi/hssf/usermodel/PoiHssfUtils.java rename to src/main/java/org/apache/poi/hssf/usermodel/PoiUtils.java index 80f7f3b8..6708e63b 100644 --- a/src/main/java/org/apache/poi/hssf/usermodel/PoiHssfUtils.java +++ b/src/main/java/org/apache/poi/hssf/usermodel/PoiUtils.java @@ -10,7 +10,7 @@ import org.apache.poi.xssf.usermodel.XSSFRow; * * @author Jiaju Zhuang */ -public class PoiHssfUtils { +public class PoiUtils { /** * Whether to customize the height From 3d19a1962e35d37dfd74405d2e3a1f628853a29e Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 23:16:50 +0800 Subject: [PATCH 123/129] =?UTF-8?q?*=20=E6=96=B0=E5=A2=9E=E5=A4=B4?= =?UTF-8?q?=E7=9A=84=E9=9D=9E=E7=A9=BA=E6=A0=A1=E9=AA=8C=20[Issue=20#1765]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/excel/metadata/Head.java | 11 +- .../com/alibaba/excel/util/StringUtils.java | 97 +++++++++++++++++- .../property/ExcelWriteHeadProperty.java | 2 +- .../test/demo/Test1765/Data1765.xlsx | Bin 3687 -> 0 bytes .../test/demo/Test1765/Issue1765.java | 55 ---------- 5 files changed, 104 insertions(+), 61 deletions(-) delete mode 100644 src/test/java/com/alibaba/easyexcel/test/demo/Test1765/Data1765.xlsx delete mode 100644 src/test/java/com/alibaba/easyexcel/test/demo/Test1765/Issue1765.java diff --git a/src/main/java/com/alibaba/excel/metadata/Head.java b/src/main/java/com/alibaba/excel/metadata/Head.java index c578cbbc..c150fe02 100644 --- a/src/main/java/com/alibaba/excel/metadata/Head.java +++ b/src/main/java/com/alibaba/excel/metadata/Head.java @@ -3,6 +3,7 @@ package com.alibaba.excel.metadata; import java.util.ArrayList; import java.util.List; +import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.metadata.property.ColumnWidthProperty; import com.alibaba.excel.metadata.property.FontProperty; import com.alibaba.excel.metadata.property.LoopMergeProperty; @@ -64,9 +65,15 @@ public class Head { this.columnIndex = columnIndex; this.fieldName = fieldName; if (headNameList == null) { - headNameList = new ArrayList(); + this.headNameList = new ArrayList<>(); + } else { + this.headNameList = headNameList; + for (String headName : headNameList) { + if (headName == null) { + throw new ExcelGenerateException("head name can not be null."); + } + } } - this.headNameList = headNameList; this.forceIndex = forceIndex; this.forceName = forceName; } diff --git a/src/main/java/com/alibaba/excel/util/StringUtils.java b/src/main/java/com/alibaba/excel/util/StringUtils.java index 667233dc..cb6e7227 100644 --- a/src/main/java/com/alibaba/excel/util/StringUtils.java +++ b/src/main/java/com/alibaba/excel/util/StringUtils.java @@ -69,7 +69,6 @@ public class StringUtils { return true; } - /** *

    Checks if a CharSequence is not empty (""), not null and not whitespace only.

    * @@ -83,9 +82,9 @@ public class StringUtils { * StringUtils.isNotBlank(" bob ") = true * * - * @param cs the CharSequence to check, may be null + * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is - * not empty and not null and not whitespace only + * not empty and not null and not whitespace only * @since 2.0 * @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence) */ @@ -93,5 +92,97 @@ public class StringUtils { return !isBlank(cs); } + /** + *

    Compares two CharSequences, returning {@code true} if they represent + * equal sequences of characters.

    + * + *

    {@code null}s are handled without exceptions. Two {@code null} + * references are considered to be equal. The comparison is case sensitive.

    + * + *
    +     * StringUtils.equals(null, null)   = true
    +     * StringUtils.equals(null, "abc")  = false
    +     * StringUtils.equals("abc", null)  = false
    +     * StringUtils.equals("abc", "abc") = true
    +     * StringUtils.equals("abc", "ABC") = false
    +     * 
    + * + * @param cs1 the first CharSequence, may be {@code null} + * @param cs2 the second CharSequence, may be {@code null} + * @return {@code true} if the CharSequences are equal (case-sensitive), or both {@code null} + * @see Object#equals(Object) + * @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence) + */ + public static boolean equals(final CharSequence cs1, final CharSequence cs2) { + if (cs1 == cs2) { + return true; + } + if (cs1 == null || cs2 == null) { + return false; + } + if (cs1.length() != cs2.length()) { + return false; + } + if (cs1 instanceof String && cs2 instanceof String) { + return cs1.equals(cs2); + } + return regionMatches(cs1, false, 0, cs2, 0, cs1.length()); + } + + /** + * Green implementation of regionMatches. + * + * @param cs the {@code CharSequence} to be processed + * @param ignoreCase whether or not to be case insensitive + * @param thisStart the index to start on the {@code cs} CharSequence + * @param substring the {@code CharSequence} to be looked for + * @param start the index to start on the {@code substring} CharSequence + * @param length character length of the region + * @return whether the region matched + */ + public static boolean regionMatches(final CharSequence cs, final boolean ignoreCase, final int thisStart, + final CharSequence substring, final int start, final int length) { + if (cs instanceof String && substring instanceof String) { + return ((String)cs).regionMatches(ignoreCase, thisStart, (String)substring, start, length); + } + int index1 = thisStart; + int index2 = start; + int tmpLen = length; + + // Extract these first so we detect NPEs the same as the java.lang.String version + final int srcLen = cs.length() - thisStart; + final int otherLen = substring.length() - start; + + // Check for invalid parameters + if (thisStart < 0 || start < 0 || length < 0) { + return false; + } + + // Check that the regions are long enough + if (srcLen < length || otherLen < length) { + return false; + } + + while (tmpLen-- > 0) { + final char c1 = cs.charAt(index1++); + final char c2 = substring.charAt(index2++); + + if (c1 == c2) { + continue; + } + + if (!ignoreCase) { + return false; + } + + // The same check as in String.regionMatches(): + if (Character.toUpperCase(c1) != Character.toUpperCase(c2) + && Character.toLowerCase(c1) != Character.toLowerCase(c2)) { + return false; + } + } + + return true; + } } diff --git a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java index dc5275f8..c2779136 100644 --- a/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java +++ b/src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java @@ -142,7 +142,7 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty { continue; } alreadyRangeSet.add(i + "-" + j); - String headName = headNameList.get(j) == null ? "" : headNameList.get(j); + String headName = headNameList.get(j); int lastCol = i; int lastRow = j; for (int k = i + 1; k < headList.size(); k++) { diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/Test1765/Data1765.xlsx b/src/test/java/com/alibaba/easyexcel/test/demo/Test1765/Data1765.xlsx deleted file mode 100644 index 3377bb760f7a27ff706a43fda2d77dd6dd323ab7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3687 zcmaJ^2{@GP8XoHyd)cGx#NW@z7Lx2EYeI~&jb&^z43cfEjmVm{NMQ(3$iDuA(jdQ` zi0n&6b|cA|sdIjgbL#o7Z@!u9dY^Zm=YH?+e(%>vmx7WNKtn?V_*>#SLrZ(<(Nm%OAa(_N6 z6m$UWyQLDT(|A=PD>u}qKP(6SZg+(H_9f-wmCJ0nMUQC+wLmMnIw%K}he*af%@G%1 zrwE7C4cCo?lBZ%=UX3nY0477{twbvXx3Ti>0nauJsWYVqd%50dS5y16yiejx7v1mn z3$#6x5nU1+uh9&ed%ls%=w?l!Y4N5h9nko>eD{{88?W@RzTQ%^1DriN?!EXRWyf^k z4e2@yaCznu^2%_04h2Y&^;?b=&C*NWksxv-T_DZV82`o@V&^*K0D#div0)*OuvAAP zyd4nU)+T-)4qi7UZo9ixUh71(fSJFgycrgk+cYv|3svWBXD{5OxDk+KP7r>Py}EM~ zcp=$1iq>--=IG>jecQguvkI!N#uC{2IHZYGFHOOQ9XeZ?rWjw9brU>BG$0=fgf~B)fsFBtevxEl^|M50SsVS!_XA_Pb73a=T=LMlIDq{>wNHW0xp4v z6RubERB44Wy37?ss9zm?@+tjpdUh4s4VKW&Cd;jDPPbD${fQRyT*fSHcw@1Q^P)H9iNm~yO67c$Q zI9ej`8ehT=m{G`Tf96D)Jiai|fF35Ar6KBv`Vh0Fg^VQsOs@Gglj^UU4N?vq1u6A) ziR5@pZ|}>L_`N*E4g;jT3xwa!F47_yIA_+~wMLn+95XRn*JY9_CWNeM+l&C~cTX#f zq-ooY$iF4?aKN5u7e|L0KfCn$l|`$j+DYy>~ark#4d4M!>h;aTSV!1WM z``2VTakL>A66HYZ$UR~FN*kD2%Q|ni=@FLALTyYlnM&0Y$M&i|A;!IImp|%OP(Xj3 znGrt+KG2CVsjymG+40L_tBt<8xvCCE3o4uboS!N3W)r`~-IlXb&~OH+RJSpxqC`o1 zV>M$C57=G@MxOSZKPV=Sg7RH1dp0COXX@S-v~6?q^aXxv%}66-f5ua}Mgp|ycWNzT zXR#(I(>i$-336dF?E$zQzzj^V74$#--QE0t%0-NAUcR$?x~Z)7!T*1LrS+7L-SXssp0Xj+X8=L z+ueeFmAzbRF)FSIl^>)?u&FGiB9fw%c>fwhRw9PC-6Xx>wkQYtYu+elgp(HuM&%e) z5-|W@!h&f6s-wyNVEc*B9G`I2I@u$nGY_UBstUk#+TnE!7jg5x(y3 zRZCu#eblVGz}w$9#!|fL>9N>)Ctb2E7gRvo+5mjEUBfr?%|p(}IByWn;ul}a?TGwf zaSL77;*85s$rCK8N2kwUbOc+1oH{Q|4#tnlnQQmYS@(j9Xvs>nYv*qAYQ4~hV7IMw zGi5S;pi(Co(^>oPnw->SlAeGqT}(`B;5Eh6poRCXt8dQ*tJr1Qq`ERsi{qpAnrL9|6n{Pbxz4s6dYg1qy z9dQNS=B{OW(#VL@dLmxBuOzJMw~jyW6=FL|i_Bc`fsdc6#u@jyc7D0q&;oXZRYs1^ zctIkbBh}abZoE_h>$a;apVKc!|JZ&+R@Xieh)jo2{f_NSKPlsjM7i1_k**}7$Hu7| zw1Sy6cOdU^50xt^XjECBaz_lDzSlD0BN96}66dJb>0n+u!~Q;h;V&IFn|CQ&TOTeS zxa_V3lxf>>gk$WoFWZ!sdD=dka@hCwVe0(4o};KS>TdTwstY*OlP8mGT)y1HZPiAm zju?eZV0oPX@Z*zV@V$%QS%(%XEydD#oKNWgX z>BxxKu027>R^&TTT3m;1d|dr2c#`u@8GhN*UGCJt8+`C&g&$fId`6b1`BFUZ2fhOD zSZb)OJYPOK1t!HcFRc)4a_~b_r8zCv=7{}U{ZsZNPcM_G?@IJCmk*+Q zgFO3ioVf@|SkI@SeE{qaPq+Y=?%rba7?aSzog~Pe&3Q424qS z0I_rF-Oj!9>#9F`ZQ@gsX()cY8Ki^ z)35Ki%oLvTh1Nm9(8^_B{Y+DI(OFp=|G#z>*Dv+z1fCH0yG(n9b9z8yl6GqzpsGDM zWco)|1^Et}UeDT~u&;a!;)MhkT}?AX6g5Y_Rv)3jV<(Y(!+Da6>M>GIm)6>fO~h%3 zx5%Gc1zeN~{H9_`o-TNf+xEdtL;~53c34wl-T@<*b+4z)b}*R2cW`DT^@W zsthK3-hNrV5yLX~!5v7T#Oh|LlGAY#e0e0mKc27eNW!SCU%p zPRKX?5Iq|UnRo!v&02925Ebxa@7KmU`@l5UwS^A!gnWOFRgpT~MI0OX_Q9JPu2u=L zwrUMF)3Mw~15mlrJHx}PW+<^rBav{X+K8J6sRIJTt$)T0c+N4FrH(gSy)65H7F)9> z5l4A(==28hg~CviWQUBL6>xYaIO>Q=XM+EZBPWF8iAU`m$uJ)V5Am=5k9|Hq!BP7} za(#!9P9*qo4|qKLsBs`!tiy1oIFkJz!*x9U=;lpw7l%=11}`RPp#cM@d1_jKg>b`lpEh YQ4k|tDk6yh01)v~AuiKNdeX0d0kp*88vp> head() { - List> list = new ArrayList>(); - List head0 = new ArrayList(); - List head1 = new ArrayList(); - List head2 = new ArrayList(); - List head3 = new ArrayList(); - head0.add("表头"); - head1.add("日期"); - head2.add(null); - head3.add("数字"); - list.add(head0); - list.add(head1); - list.add(head2); - list.add(head3); - - return list; - } - - private List> dataList() { - List> list = new ArrayList>(); - for (int i = 0; i < 5; i++) { - List data = new ArrayList(); - data.add("字符串" + i); - data.add(new Date()); - data.add(i * 2); - data.add(i * 3); - list.add(data); - } - return list; - } -} From 4346cb43c2ba661d0d1484925ea424fd81cb9af4 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 23:16:53 +0800 Subject: [PATCH 124/129] =?UTF-8?q?*=20=E6=96=B0=E5=A2=9E=E5=A4=B4?= =?UTF-8?q?=E7=9A=84=E9=9D=9E=E7=A9=BA=E6=A0=A1=E9=AA=8C=20[Issue=20#1765]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- update.md | 1 + 1 file changed, 1 insertion(+) diff --git a/update.md b/update.md index 45f4a227..4167a00a 100644 --- a/update.md +++ b/update.md @@ -21,6 +21,7 @@ * 修复合并头可能异常的bug [Issue #1662](https://github.com/alibaba/easyexcel/issues/1662) * 修复填充调用横向样式策略报错 [Issue #1651](https://github.com/alibaba/easyexcel/issues/1651) * 修复不自动行高的问题 [Issue #1869](https://github.com/alibaba/easyexcel/issues/1869) +* 新增头的非空校验 [Issue #1765](https://github.com/alibaba/easyexcel/issues/1765) # 2.2.10 From 51f222770efde8a5ebd0a2bd3889ef1ca7903c84 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 23:35:36 +0800 Subject: [PATCH 125/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../executor/ExcelWriteFillExecutor.java | 4 ---- .../test/temp/issue1663/FillTest.java | 19 ++++++++++-------- .../{ => temp}/issue1663/template.xlsx | Bin 3 files changed, 11 insertions(+), 12 deletions(-) rename src/test/resources/{ => temp}/issue1663/template.xlsx (100%) diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java index ced1f47a..7389735d 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java @@ -191,10 +191,6 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { Map fieldNameContentPropertyMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getFieldNameContentPropertyMap(); - if (analysisCellList == null ){ - return; - } - for (AnalysisCell analysisCell : analysisCellList) { Cell cell = getOneCell(analysisCell, fillConfig); if (analysisCell.getOnlyOneVariable()) { diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/issue1663/FillTest.java b/src/test/java/com/alibaba/easyexcel/test/temp/issue1663/FillTest.java index ddcdf45a..7f89621c 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/issue1663/FillTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/issue1663/FillTest.java @@ -1,5 +1,11 @@ package com.alibaba.easyexcel.test.temp.issue1663; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import com.alibaba.easyexcel.test.demo.fill.FillData; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; @@ -8,21 +14,18 @@ import com.alibaba.excel.enums.WriteDirectionEnum; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.metadata.fill.FillConfig; import com.alibaba.excel.write.metadata.fill.FillWrapper; -import org.junit.Test; -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import org.junit.Ignore; +import org.junit.Test; +@Ignore public class FillTest { @Test public void TestFillNullPoint(){ String templateFileName = - TestFileUtil.getPath() + "issue1663" + File.separator + "template.xlsx"; + TestFileUtil.getPath() + "temp/issue1663" + File.separator + "template.xlsx"; - String fileName = TestFileUtil.getPath() + "issue1663" + File.separator + "issue1663.xlsx"; + String fileName = TestFileUtil.getPath() + "temp/issue1663" + File.separator + "issue1663.xlsx"; ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build(); WriteSheet writeSheet = EasyExcel.writerSheet().build(); FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.VERTICAL).build(); diff --git a/src/test/resources/issue1663/template.xlsx b/src/test/resources/temp/issue1663/template.xlsx similarity index 100% rename from src/test/resources/issue1663/template.xlsx rename to src/test/resources/temp/issue1663/template.xlsx From 5c7a4abd7e1135680ce1be4aa102bb0f41fb9fc0 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Wed, 15 Sep 2021 23:50:50 +0800 Subject: [PATCH 126/129] =?UTF-8?q?*=20=E4=BF=AE=E5=A4=8D=E6=9F=90?= =?UTF-8?q?=E4=BA=9B=E7=89=B9=E6=AE=8A=E7=9A=84excel=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E7=9A=84=E9=97=AE=E9=A2=98=20[Issue=20#1595]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handlers/AbstractCellValueTagHandler.java | 14 ++++-- .../com/alibaba/excel/util/StringUtils.java | 44 +++++++++++++++++++ .../easyexcel/test/temp/Lock2Test.java | 2 +- update.md | 1 + 4 files changed, 56 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java index 5cc75cdc..bf8dfecc 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java @@ -30,7 +30,7 @@ public abstract class AbstractCellValueTagHandler extends AbstractXlsxTagHandler tempCellData.setStringValue(tempData.toString()); break; case BOOLEAN: - if(StringUtils.isEmpty(tempDataString)){ + if (StringUtils.isEmpty(tempDataString)) { tempCellData.setType(CellDataTypeEnum.EMPTY); break; } @@ -38,12 +38,18 @@ public abstract class AbstractCellValueTagHandler extends AbstractXlsxTagHandler break; case NUMBER: case EMPTY: - if(StringUtils.isEmpty(tempDataString)){ + if (StringUtils.isEmpty(tempDataString)) { tempCellData.setType(CellDataTypeEnum.EMPTY); break; } - tempCellData.setType(CellDataTypeEnum.NUMBER); - tempCellData.setNumberValue(BigDecimal.valueOf(Double.parseDouble(tempDataString))); + // fix https://github.com/alibaba/easyexcel/issues/1595 + if (StringUtils.isNumeric(tempDataString)) { + tempCellData.setType(CellDataTypeEnum.NUMBER); + tempCellData.setNumberValue(BigDecimal.valueOf(Double.parseDouble(tempDataString))); + } else { + tempCellData.setType(CellDataTypeEnum.STRING); + tempCellData.setStringValue(tempData.toString()); + } break; default: throw new IllegalStateException("Cannot set values now"); diff --git a/src/main/java/com/alibaba/excel/util/StringUtils.java b/src/main/java/com/alibaba/excel/util/StringUtils.java index cb6e7227..6c636908 100644 --- a/src/main/java/com/alibaba/excel/util/StringUtils.java +++ b/src/main/java/com/alibaba/excel/util/StringUtils.java @@ -185,4 +185,48 @@ public class StringUtils { return true; } + + /** + *

    Checks if the CharSequence contains only Unicode digits. + * A decimal point is not a Unicode digit and returns false.

    + * + *

    {@code null} will return {@code false}. + * An empty CharSequence (length()=0) will return {@code false}.

    + * + *

    Note that the method does not allow for a leading sign, either positive or negative. + * Also, if a String passes the numeric test, it may still generate a NumberFormatException + * when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range + * for int or long respectively.

    + * + *
    +     * StringUtils.isNumeric(null)   = false
    +     * StringUtils.isNumeric("")     = false
    +     * StringUtils.isNumeric("  ")   = false
    +     * StringUtils.isNumeric("123")  = true
    +     * StringUtils.isNumeric("\u0967\u0968\u0969")  = true
    +     * StringUtils.isNumeric("12 3") = false
    +     * StringUtils.isNumeric("ab2c") = false
    +     * StringUtils.isNumeric("12-3") = false
    +     * StringUtils.isNumeric("12.3") = false
    +     * StringUtils.isNumeric("-123") = false
    +     * StringUtils.isNumeric("+123") = false
    +     * 
    + * + * @param cs the CharSequence to check, may be null + * @return {@code true} if only contains digits, and is non-null + * @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence) + * @since 3.0 Changed "" to return false and not true + */ + public static boolean isNumeric(final CharSequence cs) { + if (isEmpty(cs)) { + return false; + } + final int sz = cs.length(); + for (int i = 0; i < sz; i++) { + if (!Character.isDigit(cs.charAt(i))) { + return false; + } + } + return true; + } } diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java index 94f8ca31..cc81f194 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java @@ -36,7 +36,7 @@ public class Lock2Test { public void test() throws Exception { File file = TestFileUtil.readUserHomeFile("test/test4.xlsx"); - List list = EasyExcel.read(file).sheet(0).doReadSync(); + List list = EasyExcel.read("/Users/zhuangjiaju/Downloads/olay的副本.xlsx").sheet(0).doReadSync(); LOGGER.info("数据:{}", list.size()); for (Object data : list) { LOGGER.info("返回数据:{}", CollectionUtils.size(data)); diff --git a/update.md b/update.md index 4167a00a..8e976243 100644 --- a/update.md +++ b/update.md @@ -22,6 +22,7 @@ * 修复填充调用横向样式策略报错 [Issue #1651](https://github.com/alibaba/easyexcel/issues/1651) * 修复不自动行高的问题 [Issue #1869](https://github.com/alibaba/easyexcel/issues/1869) * 新增头的非空校验 [Issue #1765](https://github.com/alibaba/easyexcel/issues/1765) +* 修复某些特殊的excel读取失败的问题 [Issue #1595](https://github.com/alibaba/easyexcel/issues/1595) # 2.2.10 From c30a89d4f6141ff6c369f4dc4b0f4e8b7a1a1863 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Thu, 16 Sep 2021 15:59:24 +0800 Subject: [PATCH 127/129] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E8=A1=8C=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../executor/AbstractExcelWriteExecutor.java | 4 +++ .../easyexcel/test/temp/Lock2Test.java | 30 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java index ed2806de..5cd0cda2 100644 --- a/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/AbstractExcelWriteExecutor.java @@ -75,6 +75,10 @@ public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { // Fill in style information fillStyle(cell, cellData.getWriteCellStyle()); + // Fill index + cellData.setRowIndex(cell.getRowIndex()); + cellData.setColumnIndex(cell.getColumnIndex()); + if (cellData.getType() == null) { cellData.setType(CellDataTypeEnum.EMPTY); } diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java index cc81f194..e722344d 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java @@ -82,6 +82,36 @@ public class Lock2Test { .doWrite(data()); } + @Test + public void simpleWrite() { + String fileName = TestFileUtil.getPath() + System.currentTimeMillis() + ".xlsx"; + System.out.println(fileName); + EasyExcel.write(fileName).head(head()).sheet("模板").doWrite(dataList()); + } + + private List> head() { + List> list = new ArrayList>(); + List head0 = new ArrayList(); + head0.add("表头"); + + list.add(head0); + List head1 = new ArrayList(); + head1.add("表头2"); + + list.add(head1); + return list; + } + + private List> dataList() { + List> list = new ArrayList>(); + List data = new ArrayList(); + data.add("字符串"); + data.add(new Date()); + //data.add(0.56); + list.add(data); + return list; + } + private List data() { List list = new ArrayList(); for (int i = 0; i < 10; i++) { From 41d1220c01d1b2fdb7534bd92e0b9381c16b6e7b Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Thu, 16 Sep 2021 16:05:51 +0800 Subject: [PATCH 128/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=B8=8D=E5=88=9B?= =?UTF-8?q?=E5=BB=BA=E5=AF=B9=E8=B1=A1=E5=86=99=E5=85=A5=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BC=82=E5=B8=B8=20[Issue=20#1702]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../write/executor/ExcelWriteAddExecutor.java | 4 +- .../test/demo/Test1702/Date1702.java | 35 ------------- .../test/demo/Test1702/Date1702.xlsx | Bin 3557 -> 0 bytes .../test/demo/Test1702/Issue1702.java | 47 ------------------ .../easyexcel/test/demo/write/WriteTest.java | 16 ------ .../easyexcel/test/temp/Lock2Test.java | 6 +-- update.md | 1 + 7 files changed, 5 insertions(+), 104 deletions(-) delete mode 100644 src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.java delete mode 100644 src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.xlsx delete mode 100644 src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Issue1702.java diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index c634b79c..cd1a6f4e 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -92,12 +92,14 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { } cellIndex = entry.getKey(); Head head = entry.getValue(); - doAddBasicTypeToExcel(oneRowData, head, row, relativeRowIndex, dataIndex++, cellIndex++); + doAddBasicTypeToExcel(oneRowData, head, row, relativeRowIndex, dataIndex++, cellIndex); } // Finish if (dataIndex >= oneRowData.size()) { return; } + // fix https://github.com/alibaba/easyexcel/issues/1702 + // If there is data, it is written to the next cell if (dataIndex != 0) { cellIndex++; } diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.java b/src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.java deleted file mode 100644 index c2bd7314..00000000 --- a/src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.alibaba.easyexcel.test.demo.Test1702; - -import com.alibaba.excel.annotation.ExcelProperty; - -import java.util.Date; - -public class Date1702 { - @ExcelProperty(index = 0) - private String str; - @ExcelProperty(index = 1) - private Date date; - @ExcelProperty(index = 2) - private double r; - public void setStr(String str) { - this.str = str; - } - public void setDate(Date date) { - this.date = date; - } - public void setR(double r) { - this.r = r; - } - - public String getStr() { - return str; - } - - public Date getDate(){ - return date; - } - public double getR(){ - return r; - } -} - diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.xlsx b/src/test/java/com/alibaba/easyexcel/test/demo/Test1702/Date1702.xlsx deleted file mode 100644 index 66cd1a2f361b792492007e460b335908f3aa95af..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3557 zcmaJ@c|25Y8>Yd`kdP%?*;RP6h9a^yvP;>@Hiogzf-;t|HX;UDix!ORh3rh4RI(&X zA~MO6tz^we^3CY`US8i@_xYVO=Z|wgbKloAetY$lN;{e8<7Klw>BUUpmC~X?ld=P3ONd45^cuTgyewpd{RjHIZ~oL zfJjJvfBiuCo-`ci^TBCVV2bT0`@@xD-v}z+LB&g^Oj(M3-Fz?4)G+x!eV@#mad@K> z6YO*-GqyB7LAMD!@n9)!pO*tb&*tUh3_9ZHinYrqFCoQ#W25ON7@Q{-|6Zz(p>4GA zqGG*`Tt(J2;%t9H4gh?T>qm|~X!?=RK*%05Lm((WE|54z?c87w9i7>4vEihCVW)%e z@q_vJIap$lFyBkZ0=&Jd&b9kIm1F;r`m$e2dD-kdcesvF3s2!P;9^j+HAUiK_WbH4 zplXUm3^QsG>gwid_06RkRc))I%^BSMBKVoqycB$_0T&`;KNEDpDb3zcKwYT=sGMoS zGX%0WFKofBoM-`xn5~S6FS3(3dvN0}_n|YoDIQ1F*lTjTZ<~?a=Ic83B8?B5cD1Fx z>KmJT3{f$90gu0N(;}v-|4hz`ed6IV05FJi0S77xBqz2#5YSGFQ53|pwBMW|!;iJX zDOQzT)%xN4JSGaFbjySjd0hq-~4El{MZ8 zMe%+Mea9vo>%=F7zVJR1Kt=< zVx|JG`!!;d9gV07WKUAc6OK3>)Wrsxe#>;r7;<5HGBY_ai|^BdWzBcJMtRtQg4Blk zq&=;;?(Rpa3F~<$+e{ED9uN^{=V+T0;KYT_js=FqFLC7Y`VPyqqvD9#XUkD?#+{=l z2GY+s52(DNN5TjkEmGKUi(-uz&uyCZv{$>i2)sU4jGM%WyOBSs@zuby-2r+sRXJV_=Kf3j4$O{M9wZSFW|J|{ z2QfV>VU-u++bn9fANhpCfBuODlcv{cmG7azG#814#}0+=w|WY#Yil_o^M^9mVQYl` zrGAN?diBCOzax93_A{yn4-CA#vS@wL{&q)q1yujH~vIPVkEszd7O^PX59?Ctns zS!a=hH=2i6I!a$l{3xvZ$w0#}E)_7tNF_xX_5MAETvQALykvdhPH33RIX|?!kDD(I z##3=xG-A+wjR*w=)x;dqCAhOi$aVpv{Ji(Pl5|xWU3%3zCf6Ldq~bjjnF^I;X(5Ga zFJfXUZ38ssqFFk6u__AJ7weL&rwno_J^|~#ciHVgq7y~O*TY&D5?L%%9$rjN#{2hO zl&Zf9$RQZtjXN3$e5*jCM@mWKE@a_qxmC}4Y# zg^fgELlb&r<$*3$d>1V3z(Z5fyLiyg~xs%mCY>j`rw?HgfanF z#0Q(p*!rjLq)g2`vC;-?#wT@GIXkdhyXr_^!l1JCncfM9Zg3GZed(FHiAzHI4~-#& zZ}x^+N?HE4@*MjzxO%Ty?l)vpBtxgwlad>S&f{va5*rRR0TZE`&RLFWp6sKNWg6AK zMKu{S*%F0?WR>i@kb)NX*iE-A$;?X7PtTfhV#TY?wzR!pK5we6TsCjISbXLBEjj43 z6I_D>p5Oq1I<|YneI)&RQe_)z5?YwWRt4WMr$J^!)}%jtn7@W((c{_v)x7bkoGY{{ zdT`7a67>L~v+$azQ3>sIuCJIdF2Qb%AIbTJSqhcu5XL{To$VK8t{~8!&Ip7jjp*@s zEt6)dUaUgilWv`=0)Vu*@&%&a9K8ON>@OMLH-L9FYKK{ujq$v{Kl#Lf+wooM%E|}z zO^>y?pz<@$2O@FK*{2=L%27_mA7LAQ{%q~v7jsVP4thJkkLduu?aEV1v8edcC1C%I zUdLw;LM8~hOJjtUSg%}bU0t*-RGW@xK`Ny9;l-*;A5nO}WVR%l?0-roG^VMk$h~Q5 zzhj^z>9laq=Xm9PHwGIk=+eymlh6^~tL3dBj#Of>dUA)33pQya2z?MP z@QY`%J+2~rADar5=li61BGhtoOH&nj?G`4e{oDUh5BPr}^vl2O#OarpNiz1NdYRLk zvE3o49ujY^k1Vun_U#58R2l^rT z2{YowSohhlnyRci>Ymcml+Ok@5BR)&t%@nt6pyzt(o0l@6s?hL!C*I8RyRWZbX|x2 z?4!NP>&SV);Q1l)J9KB5MDORE$cpO+Gl;T)B7nhT$KY;@c0%Du{Ylp!32E!ty_A<9 zz4d!oE;ocl5(OWfyxu())&G!k|7Tv)MqeoM1VsDIIn2S~Dnl$oK5s+qw@)lI!NCF4 zlHO1|SNx-S;oWABFB}H*^QFor^+%pYBYz8$&yd_+B5+C*B-LdnYGb0HQgx|PAmWRe zqjfczJG1)g;0+P^R*le<2Ibl6Lk#mVfe8tO#i6@8ukj<1sOphcZ8TFgx~klp6dL@Y zQxR)t-?5myWSR{)t6p&3o`149 zqj1Sy8sqCHo!BU409J?DNaPdr^xx(Z)mA^FasBKgHe5dYaC zmt*Nm;!q2p8-B?$n>w2mql6&UG<3P`MPfL?s3a#l&E@U z>CAKFW%*Z5S#{||_DXmDSZd7Y9j0Uo^sjus+vY&qHm2{uR1}rYkz3nFzlV!%+mY|| zqclhU&)DJ5%?$sUxYJD0?CN$1Qvd2-% list = EasyExcelFactory.read(inputStream).head(Date1702.class).sheet(0).doReadSync(); - Assert.assertEquals("字符串",list.get(0).getStr()); - } - - - private List> head() { - List> list = new ArrayList>(); - List head0 = new ArrayList(); - head0.add("表头"); - list.add(head0); - return list; - } - - private List> dataList() { - List> list = new ArrayList>(); - List data = new ArrayList(); - data.add("字符串"); - data.add(new Date()); - data.add(0.56); - list.add(data); - return list; - } -} diff --git a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java index ec124a43..1bf11fe4 100644 --- a/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java +++ b/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java @@ -601,22 +601,6 @@ public class WriteTest { EasyExcel.write(fileName, ConverterData.class).head(variableTitleHead()).sheet("模板").doWrite(data()); } - @Test - public void noModelWriteWithOneHead() { - // 写法1 - String fileName = TestFileUtil.getPath() + "noModelSimpleWrite" + System.currentTimeMillis() + ".xlsx"; - // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - EasyExcel.write(fileName).head(noModelOneHead()).sheet("模板").doWrite(dataList()); - } - - private List> noModelOneHead() { - List> list = new ArrayList>(); - List head0 = new ArrayList(); - head0.add("表头1"); - list.add(head0); - return list; - } - /** * 不创建对象的写 */ diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java index e722344d..88e3211f 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/Lock2Test.java @@ -95,10 +95,6 @@ public class Lock2Test { head0.add("表头"); list.add(head0); - List head1 = new ArrayList(); - head1.add("表头2"); - - list.add(head1); return list; } @@ -107,7 +103,7 @@ public class Lock2Test { List data = new ArrayList(); data.add("字符串"); data.add(new Date()); - //data.add(0.56); + data.add(0.56); list.add(data); return list; } diff --git a/update.md b/update.md index 8e976243..db002b67 100644 --- a/update.md +++ b/update.md @@ -23,6 +23,7 @@ * 修复不自动行高的问题 [Issue #1869](https://github.com/alibaba/easyexcel/issues/1869) * 新增头的非空校验 [Issue #1765](https://github.com/alibaba/easyexcel/issues/1765) * 修复某些特殊的excel读取失败的问题 [Issue #1595](https://github.com/alibaba/easyexcel/issues/1595) +* 修复不创建对象写入数据异常 [Issue #1702](https://github.com/alibaba/easyexcel/issues/1702) # 2.2.10 From e5b579fdfa40732f98f3fa45170e783b7c0b3169 Mon Sep 17 00:00:00 2001 From: Jiaju Zhuang Date: Thu, 16 Sep 2021 16:30:17 +0800 Subject: [PATCH 129/129] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=A4=B4=E5=92=8C?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=AF=B9=E8=B1=A1=E4=B8=8D=E4=B8=80=E8=87=B4?= =?UTF-8?q?=E4=BC=9A=E8=A6=86=E7=9B=96=E7=9A=84=E9=97=AE=E9=A2=98=20[Issue?= =?UTF-8?q?=20#1870]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../write/executor/ExcelWriteAddExecutor.java | 43 +++++++-------- .../easyexcel/test/temp/WriteV33Test.java | 37 ++++++++++--- .../easyexcel/test/temp/data/DataType.java | 29 ++++++++++ .../easyexcel/test/temp/data/HeadType.java | 24 +++++++++ update.md | 54 +++++++++++++++++-- 5 files changed, 153 insertions(+), 34 deletions(-) create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/data/DataType.java create mode 100644 src/test/java/com/alibaba/easyexcel/test/temp/data/HeadType.java diff --git a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java index 2bd63b6a..c0d2f47f 100644 --- a/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java +++ b/src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java @@ -24,20 +24,11 @@ import com.alibaba.excel.write.metadata.RowData; import com.alibaba.excel.write.metadata.holder.WriteHolder; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; + import net.sf.cglib.beans.BeanMap; import org.apache.commons.collections4.CollectionUtils; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; /** * Add the data into excel @@ -70,7 +61,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { } private void addOneRowOfDataToExcel(Object oneRowData, int n, int relativeRowIndex, - Map sortedAllFiledMap) { + Map sortedAllFiledMap) { if (oneRowData == null) { return; } @@ -94,14 +85,15 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { } Map headMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadMap(); int dataIndex = 0; - int cellIndex = 0; + int maxCellIndex = -1; for (Map.Entry entry : headMap.entrySet()) { if (dataIndex >= oneRowData.size()) { return; } - cellIndex = entry.getKey(); + int cellIndex = entry.getKey(); Head head = entry.getValue(); doAddBasicTypeToExcel(oneRowData, head, row, relativeRowIndex, dataIndex++, cellIndex); + maxCellIndex = Math.max(maxCellIndex, cellIndex); } // Finish if (dataIndex >= oneRowData.size()) { @@ -109,17 +101,16 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { } // fix https://github.com/alibaba/easyexcel/issues/1702 // If there is data, it is written to the next cell - if (dataIndex != 0) { - cellIndex++; - } + maxCellIndex++; + int size = oneRowData.size() - dataIndex; for (int i = 0; i < size; i++) { - doAddBasicTypeToExcel(oneRowData, null, row, relativeRowIndex, dataIndex++, cellIndex++); + doAddBasicTypeToExcel(oneRowData, null, row, relativeRowIndex, dataIndex++, maxCellIndex++); } } private void doAddBasicTypeToExcel(RowData oneRowData, Head head, Row row, int relativeRowIndex, int dataIndex, - int cellIndex) { + 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); @@ -130,18 +121,18 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { } private void addJavaObjectToExcel(Object oneRowData, Row row, int relativeRowIndex, - Map sortedAllFiledMap) { + Map sortedAllFiledMap) { WriteHolder currentWriteHolder = writeContext.currentWriteHolder(); BeanMap beanMap = BeanMapUtils.create(oneRowData); Set beanMapHandledSet = new HashSet(); - int cellIndex; + int maxCellIndex = -1; // If it's a class it needs to be cast by type if (HeadKindEnum.CLASS.equals(writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadKind())) { Map headMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadMap(); Map contentPropertyMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getContentPropertyMap(); for (Map.Entry entry : contentPropertyMap.entrySet()) { - cellIndex = entry.getKey(); + int cellIndex = entry.getKey(); ExcelContentProperty excelContentProperty = entry.getValue(); String name = FieldUtils.resolveCglibFieldName(excelContentProperty.getField()); if (!beanMap.containsKey(name)) { @@ -157,13 +148,15 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { null, cell, value, excelContentProperty, head, relativeRowIndex); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE); beanMapHandledSet.add(name); + maxCellIndex = Math.max(maxCellIndex, cellIndex); } - cellIndex++; } // Finish if (beanMapHandledSet.size() == beanMap.size()) { return; } + maxCellIndex++; + Map ignoreMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getIgnoreMap(); initSortedAllFiledMapFieldList(oneRowData.getClass(), sortedAllFiledMap); for (Map.Entry entry : sortedAllFiledMap.entrySet()) { @@ -175,8 +168,10 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { continue; } Object value = beanMap.get(filedName); - WriteHandlerUtils.beforeCellCreate(writeContext, row, null, cellIndex, relativeRowIndex, Boolean.FALSE); - Cell cell = WorkBookUtil.createCell(row, cellIndex++); + WriteHandlerUtils.beforeCellCreate(writeContext, row, null, maxCellIndex, relativeRowIndex, Boolean.FALSE); + // fix https://github.com/alibaba/easyexcel/issues/1870 + // If there is data, it is written to the next cell + Cell cell = WorkBookUtil.createCell(row, maxCellIndex++); WriteHandlerUtils.afterCellCreate(writeContext, cell, null, relativeRowIndex, Boolean.FALSE); WriteCellData cellData = converterAndSet(currentWriteHolder, FieldUtils.getFieldClass(beanMap, filedName), null, cell, value, null, null, relativeRowIndex); diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/WriteV33Test.java b/src/test/java/com/alibaba/easyexcel/test/temp/WriteV33Test.java index ea7b39a2..c992522f 100644 --- a/src/test/java/com/alibaba/easyexcel/test/temp/WriteV33Test.java +++ b/src/test/java/com/alibaba/easyexcel/test/temp/WriteV33Test.java @@ -1,20 +1,23 @@ package com.alibaba.easyexcel.test.temp; import java.util.ArrayList; +import java.util.Collections; import java.util.List; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alibaba.easyexcel.test.demo.write.DemoData; +import com.alibaba.easyexcel.test.temp.data.DataType; +import com.alibaba.easyexcel.test.temp.data.HeadType; import com.alibaba.easyexcel.test.util.TestFileUtil; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy; import com.alibaba.excel.write.metadata.WriteSheet; +import org.junit.Ignore; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * 临时测试 * @@ -32,7 +35,8 @@ public class WriteV33Test { OnceAbsoluteMergeStrategy onceAbsoluteMergeStrategy = new OnceAbsoluteMergeStrategy(2, 2, 0, 1); // 这里 指定文件 - ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).registerWriteHandler(onceAbsoluteMergeStrategy).build(); + ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).registerWriteHandler( + onceAbsoluteMergeStrategy).build(); WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "模板1").build(); WriteSheet writeSheet2 = EasyExcel.writerSheet(2, "模板2").build(); WriteSheet writeSheet3 = EasyExcel.writerSheet(3, "模板3").build(); @@ -55,4 +59,25 @@ public class WriteV33Test { return list; } + @Test + public void test33() throws Exception { + List data = getData(); + String fileName = TestFileUtil.getPath() + "repeatedWrite" + System.currentTimeMillis() + ".xlsx"; + + ExcelWriter excelWriter = null; + excelWriter = EasyExcel.write(fileName).build(); + WriteSheet writeSheet = EasyExcel.writerSheet(1, "test") + .head(HeadType.class) + .build(); + excelWriter.write(data, writeSheet); + excelWriter.finish(); + } + + private List getData() { + DataType vo = new DataType(); + vo.setId(738); + vo.setFirstRemark("1222"); + vo.setSecRemark("22222"); + return Collections.singletonList(vo); + } } diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/data/DataType.java b/src/test/java/com/alibaba/easyexcel/test/temp/data/DataType.java new file mode 100644 index 00000000..8a4b1fb7 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/data/DataType.java @@ -0,0 +1,29 @@ +package com.alibaba.easyexcel.test.temp.data; + +import com.alibaba.excel.annotation.ExcelProperty; + +import lombok.Data; + +@Data +public class DataType { + /** + * 任务id + */ + @ExcelProperty("任务ID") + private Integer id; + + @ExcelProperty("多余字段1") + private String firstSurplus; + + @ExcelProperty("多余字段2") + private String secSurplus; + + @ExcelProperty("多余字段3") + private String thirdSurplus; + + @ExcelProperty(value = "备注1") + private String firstRemark; + + @ExcelProperty(value = "备注2") + private String secRemark; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/temp/data/HeadType.java b/src/test/java/com/alibaba/easyexcel/test/temp/data/HeadType.java new file mode 100644 index 00000000..32bd065e --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/temp/data/HeadType.java @@ -0,0 +1,24 @@ +package com.alibaba.easyexcel.test.temp.data; + +import com.alibaba.excel.annotation.ExcelProperty; + +import lombok.Data; + +@Data +public class HeadType { + + + /** + * 任务id + */ + @ExcelProperty("任务ID") + private Integer id; + + + @ExcelProperty(value = "备注1") + private String firstRemark; + + @ExcelProperty(value = "备注2") + private String secRemark; + +} diff --git a/update.md b/update.md index db002b67..9d91fae3 100644 --- a/update.md +++ b/update.md @@ -1,4 +1,5 @@ # 3.0.0-beta1 + * 升级jdk8 不再支持jdk6 jdk7 * 升级poi 到 4.1.2 * 升级cglib 到 3.3.0 @@ -24,28 +25,35 @@ * 新增头的非空校验 [Issue #1765](https://github.com/alibaba/easyexcel/issues/1765) * 修复某些特殊的excel读取失败的问题 [Issue #1595](https://github.com/alibaba/easyexcel/issues/1595) * 修复不创建对象写入数据异常 [Issue #1702](https://github.com/alibaba/easyexcel/issues/1702) - +* 修复头和数据对象不一致会覆盖的问题 [Issue #1870](https://github.com/alibaba/easyexcel/issues/1870) # 2.2.10 + * 修复读取的时候用string接收数字 可能四舍五入不一致的bug # 2.2.9 + * 修复读取的时候用string接收数字 可能四舍五入不一致的bug # 2.2.8 + * 兼容07在特殊的excel的情况下,读取数据异常 # 2.2.7 + * 修改07在特殊情况下用`String`接收数字会丢小数位的bug # 2.2.6 + * 修改跳着读取03版本空指针bug # 2.2.5 + * `ExcelProperty`新增`order` 用于排序 -* 修复导出指定`index`会导致空行的bug +* 修复导出指定`index`会导致空行的bug # 2.2.4 + * 撤销删除`AbstractMergeStrategy` * 修改默认用String读取数字不使用科学计数法 通过`useScientificFormat`修改 * 修复07版仅有样式的空行 默认不忽略的bug @@ -59,14 +67,17 @@ * 修复`@NumberFormat`注解转换double时可能会丢失精度 [Issue #1306](https://github.com/alibaba/easyexcel/issues/1306) # 2.2.3 + * 修改填充数据空数据的bug [Issue #1274](https://github.com/alibaba/easyexcel/issues/1274) * 回退自定义转换器入参为空 # 2.2.2 + * 修改`sheet`事件未调用的bug * 修复复杂表头不是`index=0`开始 合并异常的bug [Issue #1322](https://github.com/alibaba/easyexcel/issues/1322) # 2.2.1 + * 发布正式版 * 修复第一行为空不会调用`invokeHeadMap`的bug [Issue #993](https://github.com/alibaba/easyexcel/issues/993) * 当类的属性没有按照ExcelProperty的属性index顺序排序的时候,写数据出现错乱 [Issue #1046](https://github.com/alibaba/easyexcel/issues/1046) @@ -76,11 +87,13 @@ * 修复`table`、`sheet`中创建的拦截器不执行`workbook`事件的bug [Issue #1202](https://github.com/alibaba/easyexcel/issues/1202) # 2.2.0-beta2 + * 修复最长匹配策略不同表格会有影响的bug [Issue #1010](https://github.com/alibaba/easyexcel/issues/1010) * `LinkedList`写入的性能问题 #1121 * 修复在某些情况下可能出现不必要的`warn`日志 # 2.2.0-beta1 + * 重写主流程,代码更加优雅 * 修复用String接收日期、数字和excel显示不一致的bug(不是完美修复,但是大部分情况已经兼容) * 降低Ehcache版本 3.7.1(jkd7) -> 3.4.0(jdk6) @@ -98,19 +111,24 @@ * 填充支持多个List对象 # 2.1.7 + * 修复使用1+版本的写法,第1条开始读修改为第0条开始读 # 2.1.6 + * 修复写入只有`sheetName`会抛异常 # 2.1.5 + * 修复部分xlsx没有行号读取异常 * 填充时候支持根据`sheetName`定位`sheet` # 2.1.4 + * 新增参数`useDefaultListener` 可以排除默认对象转换 # 2.1.3 + * 每个java进程单独创建一个缓存目录 [Issue #813](https://github.com/alibaba/easyexcel/issues/813) * 统一修改合并为unsafe,提高大量数据导出的合并的效率 * 修改merge返回参数`relativeRowIndex`为`Integer` @@ -120,9 +138,11 @@ * `SimpleColumnWidthStyleStrategy` 新增 参数`columnIndex` [Issue #806](https://github.com/alibaba/easyexcel/issues/806) # 2.1.2 + * 修复强制创建新行填充,只有一行数据会未填充的bug # 2.1.1 + * 发布正式版 * 修改map返回为LinkedHashMap * 修改同步读取返回对象支持泛型 @@ -138,11 +158,13 @@ * 修复03版无法获取大概总行数的bug # 2.1.0-beta4 + * 修改最长匹配策略会空指针的bug [Issue #747](https://github.com/alibaba/easyexcel/issues/747) * 修改afterRowDispose错误 [Issue #751](https://github.com/alibaba/easyexcel/issues/751) * 修复多个头的情况下会读取数据为空 # 2.1.0-beta3 + * 支持强行指定在内存处理,以支持备注、RichTextString等的写入 * 修复关闭流失败,可能会不删除临时文件的问题 * 支持根据参数自定义导出列 @@ -151,11 +173,13 @@ * 修复填充的时候有数字会异常 # 2.1.0-beta2 + * 修改模板通过流创建报错的bug * 修复空数据未替换掉的bug * 修复空模板会空一行的bug # 2.1.0-beta1 + * 新增支持导入、导出支持公式 * 新增支持读取单元格类型、写入指定单元格类型 * 支持通过模板填充数据 @@ -168,53 +192,65 @@ * 支持导入加密 [Issue #295](https://github.com/alibaba/easyexcel/issues/295) # 2.0.5 + * 优化07版超大文件读取方案 * 支持自己设置超大文件读取参数 * 读取xlsx会改变修改时间的bug [Issue #574](https://github.com/alibaba/easyexcel/issues/574) * 默认读取忽略空行 根据参数ignoreEmptyRow参数设置 # 2.0.4 + * 修复07版整个excel仅存在数字时会出现的NPE * 修复03版 用String接收电话会出现科学计数法的问题 # 2.0.3 + * 修复重大bug 在07版读取文件的时候 小概率导致数字部分丢失 # 2.0.2 + * 修复xls无法获取sheetList的bug [Issue #621](https://github.com/alibaba/easyexcel/issues/621) * 修复监听器转换异常会重复提示的bug # 2.0.1 + * 降级poi为3.17 兼容jdk6 # 2.0.0 + * 修复当cell为空可能会抛出空指针的bug * 修复电话等长数字可能出现科学计数法的问题 [Issue #583](https://github.com/alibaba/easyexcel/issues/583) * 升级为正式版 # 2.0.0-beta6 + * 修复空行读取空指针异常 * 修复写入指定头为List>,但是数据用List导致的空指针 # 2.0.0-beta5 + * 修复在读取值的时候读取了额外值导致数据转换异常 # 2.0.0-beta4 + * 修改在传入List>判断行数错误 [Issue #526](https://github.com/alibaba/easyexcel/issues/526) * 修复在mac 2016 2017导出的excel 可能存在多余字段的问题 * 修复03版 读取无法指定sheet的问题 [Issue #533](https://github.com/alibaba/easyexcel/issues/533) # 2.0.0-beta3 + * 导出完成移除临时目录 [Issue #386](https://github.com/alibaba/easyexcel/issues/386) * 新增读取返回头数据 # 2.0.0-beta2 + * 加速gc回收 [Issue #511](https://github.com/alibaba/easyexcel/issues/511) * 修改空字符串读取可能读取上个字段的数据的bug * 修改换行数据无法读取的bug [Issue #521](https://github.com/alibaba/easyexcel/issues/521) * 修复在空字符串的时候 格式转换异常 [Issue #520](https://github.com/alibaba/easyexcel/issues/520) # 2.0.0-beta1 + * 优化读写逻辑 * 优化读写对外接口 * 加入转换器,方便格式转换 @@ -224,31 +260,41 @@ * 升级poi 到4.0.1 # 1.2.4 + 修复read()方法存在的bug # 1.2.1 + 修复POI在大并发情况下创建临时目录失败的bug -# 1.0.9 +# 1.0.9 + 修复excel超过16列被覆盖的问题,修复数据只有一行时候无法透传的bug。 # 1.0.8 + 如果整行excel数据全部为空,则不解析返回。完善多sheet的解析。 # 1.0.6 + 增加@ExcelColumnNum,修复字符串前后空白,增加过滤功能。 # 1.0.5 + 优化类型转换的性能。 # 1.0.4 + 修复日期类型转换时候数字问题。基础模型支持字段类型int,long,double,boolean,date,string # 1.0.3 + 修复无@ExcelProperty标注的多余字段时候报错。 -# 1.0.2 +# 1.0.2 + 修复拿到一行数据后,存到list中,但最后处理时候变为空的bug。 # 1.0.1 + 完善测试用例,防止歧义,模型字段映射不上时候有抛异常,改为提醒。 \ No newline at end of file