Browse Source

Merge branch 'developing' into patch-1

developing
Jiaju Zhuang 3 years ago committed by GitHub
parent
commit
253b5a87b0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 6
      README.md
  2. 2
      lombok.config
  3. 52
      pom.xml
  4. 139
      src/main/java/com/alibaba/excel/EasyExcelFactory.java
  5. 181
      src/main/java/com/alibaba/excel/ExcelReader.java
  6. 242
      src/main/java/com/alibaba/excel/ExcelWriter.java
  7. 26
      src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java
  8. 122
      src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java
  9. 10
      src/main/java/com/alibaba/excel/analysis/v03/handlers/BlankRecordHandler.java
  10. 10
      src/main/java/com/alibaba/excel/analysis/v03/handlers/BoolErrRecordHandler.java
  11. 12
      src/main/java/com/alibaba/excel/analysis/v03/handlers/DummyRecordHandler.java
  12. 36
      src/main/java/com/alibaba/excel/analysis/v03/handlers/FormulaRecordHandler.java
  13. 10
      src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelRecordHandler.java
  14. 14
      src/main/java/com/alibaba/excel/analysis/v03/handlers/LabelSstRecordHandler.java
  15. 21
      src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java
  16. 10
      src/main/java/com/alibaba/excel/analysis/v03/handlers/RkRecordHandler.java
  17. 4
      src/main/java/com/alibaba/excel/analysis/v03/handlers/StringRecordHandler.java
  18. 58
      src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java
  19. 6
      src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java
  20. 10
      src/main/java/com/alibaba/excel/analysis/v07/handlers/CellFormulaTagHandler.java
  21. 8
      src/main/java/com/alibaba/excel/analysis/v07/handlers/CellInlineStringValueTagHandler.java
  22. 27
      src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java
  23. 2
      src/main/java/com/alibaba/excel/analysis/v07/handlers/CellValueTagHandler.java
  24. 11
      src/main/java/com/alibaba/excel/analysis/v07/handlers/RowTagHandler.java
  25. 2
      src/main/java/com/alibaba/excel/annotation/ExcelProperty.java
  26. 6
      src/main/java/com/alibaba/excel/annotation/write/style/HeadStyle.java
  27. 92
      src/main/java/com/alibaba/excel/cache/Ehcache.java
  28. 10
      src/main/java/com/alibaba/excel/cache/MapCache.java
  29. 32
      src/main/java/com/alibaba/excel/constant/BuiltinFormats.java
  30. 24
      src/main/java/com/alibaba/excel/constant/OrderConstant.java
  31. 10
      src/main/java/com/alibaba/excel/context/AnalysisContext.java
  32. 35
      src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java
  33. 82
      src/main/java/com/alibaba/excel/context/WriteContextImpl.java
  34. 26
      src/main/java/com/alibaba/excel/context/csv/CsvReadContext.java
  35. 29
      src/main/java/com/alibaba/excel/context/csv/DefaultCsvReadContext.java
  36. 29
      src/main/java/com/alibaba/excel/converters/AutoConverter.java
  37. 73
      src/main/java/com/alibaba/excel/converters/Converter.java
  38. 14
      src/main/java/com/alibaba/excel/converters/ConverterKeyBuild.java
  39. 40
      src/main/java/com/alibaba/excel/converters/DefaultConverterLoader.java
  40. 10
      src/main/java/com/alibaba/excel/converters/NullableObjectConverter.java
  41. 30
      src/main/java/com/alibaba/excel/converters/ReadConverterContext.java
  42. 32
      src/main/java/com/alibaba/excel/converters/WriteConverterContext.java
  43. 13
      src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java
  44. 12
      src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java
  45. 11
      src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java
  46. 11
      src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanBooleanConverter.java
  47. 13
      src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanNumberConverter.java
  48. 11
      src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanStringConverter.java
  49. 20
      src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java
  50. 21
      src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java
  51. 13
      src/main/java/com/alibaba/excel/converters/byteconverter/ByteBooleanConverter.java
  52. 14
      src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java
  53. 11
      src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java
  54. 34
      src/main/java/com/alibaba/excel/converters/date/DateDateConverter.java
  55. 17
      src/main/java/com/alibaba/excel/converters/date/DateNumberConverter.java
  56. 13
      src/main/java/com/alibaba/excel/converters/date/DateStringConverter.java
  57. 13
      src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleBooleanConverter.java
  58. 15
      src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java
  59. 11
      src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java
  60. 21
      src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java
  61. 13
      src/main/java/com/alibaba/excel/converters/floatconverter/FloatBooleanConverter.java
  62. 17
      src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java
  63. 11
      src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java
  64. 20
      src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java
  65. 13
      src/main/java/com/alibaba/excel/converters/integer/IntegerBooleanConverter.java
  66. 16
      src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java
  67. 11
      src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java
  68. 13
      src/main/java/com/alibaba/excel/converters/longconverter/LongBooleanConverter.java
  69. 16
      src/main/java/com/alibaba/excel/converters/longconverter/LongNumberConverter.java
  70. 11
      src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java
  71. 13
      src/main/java/com/alibaba/excel/converters/shortconverter/ShortBooleanConverter.java
  72. 17
      src/main/java/com/alibaba/excel/converters/shortconverter/ShortNumberConverter.java
  73. 11
      src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java
  74. 11
      src/main/java/com/alibaba/excel/converters/string/StringBooleanConverter.java
  75. 11
      src/main/java/com/alibaba/excel/converters/string/StringErrorConverter.java
  76. 20
      src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java
  77. 24
      src/main/java/com/alibaba/excel/converters/string/StringNumberConverter.java
  78. 11
      src/main/java/com/alibaba/excel/converters/string/StringStringConverter.java
  79. 23
      src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java
  80. 10
      src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java
  81. 22
      src/main/java/com/alibaba/excel/enums/NumericCellTypeEnum.java
  82. 8
      src/main/java/com/alibaba/excel/event/AbstractIgnoreExceptionReadListener.java
  83. 4
      src/main/java/com/alibaba/excel/event/AnalysisEventListener.java
  84. 15
      src/main/java/com/alibaba/excel/event/Handler.java
  85. 38
      src/main/java/com/alibaba/excel/event/WriteHandler.java
  86. 38
      src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java
  87. 19
      src/main/java/com/alibaba/excel/metadata/AbstractCell.java
  88. 69
      src/main/java/com/alibaba/excel/metadata/AbstractHolder.java
  89. 8
      src/main/java/com/alibaba/excel/metadata/AbstractParameterBuilder.java
  90. 40
      src/main/java/com/alibaba/excel/metadata/BaseRowModel.java
  91. 63
      src/main/java/com/alibaba/excel/metadata/BasicParameter.java
  92. 286
      src/main/java/com/alibaba/excel/metadata/CellData.java
  93. 2
      src/main/java/com/alibaba/excel/metadata/ConfigurationHolder.java
  94. 38
      src/main/java/com/alibaba/excel/metadata/GlobalConfiguration.java
  95. 9
      src/main/java/com/alibaba/excel/metadata/NullObject.java
  96. 162
      src/main/java/com/alibaba/excel/metadata/Sheet.java
  97. 62
      src/main/java/com/alibaba/excel/metadata/Table.java
  98. 65
      src/main/java/com/alibaba/excel/metadata/TableStyle.java
  99. 354
      src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java
  100. 333
      src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java
  101. Some files were not shown because too many files have changed in this diff Show More

6
README.md

@ -18,10 +18,10 @@ EasyExcel
#### 因为公司不方便用QQ,所以建议加钉钉群 #### 因为公司不方便用QQ,所以建议加钉钉群
# JAVA解析Excel工具EasyExcel # 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 ## 64M内存1分钟内读取75M(46W行25列)的Excel
当然还有速模式能更快,但是内存占用会在100M多一点 当然还有速模式能更快,但是内存占用会在100M多一点
![img](img/readme/large.png) ![img](img/readme/large.png)
## 相关文档 ## 相关文档
@ -83,7 +83,7 @@ DEMO代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/ja
@GetMapping("download") @GetMapping("download")
public void download(HttpServletResponse response) throws IOException { public void download(HttpServletResponse response) throws IOException {
// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
response.setContentType("application/vnd.ms-excel"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系 // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20"); String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");

2
lombok.config

@ -0,0 +1,2 @@
lombok.toString.callSuper = CALL
lombok.equalsAndHashCode.callSuper= CALL

52
pom.xml

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId> <artifactId>easyexcel</artifactId>
<version>2.2.10</version> <version>3.0.0-beta1</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>easyexcel</name> <name>easyexcel</name>
@ -16,7 +16,7 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jdk.version>1.6</jdk.version> <jdk.version>1.8</jdk.version>
<gpg.skip>true</gpg.skip> <gpg.skip>true</gpg.skip>
<maven.javadoc.skip>true</maven.javadoc.skip> <maven.javadoc.skip>true</maven.javadoc.skip>
</properties> </properties>
@ -60,22 +60,27 @@
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId> <artifactId>poi</artifactId>
<version>3.17</version> <version>4.1.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId> <artifactId>poi-ooxml</artifactId>
<version>3.17</version> <version>4.1.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId> <artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version> <version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.8</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>cglib</groupId> <groupId>cglib</groupId>
<artifactId>cglib</artifactId> <artifactId>cglib</artifactId>
<version>3.1</version> <version>3.3.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
@ -85,8 +90,15 @@
<dependency> <dependency>
<groupId>org.ehcache</groupId> <groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId> <artifactId>ehcache</artifactId>
<version>3.4.0</version> <version>3.8.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency> </dependency>
<!--test--> <!--test-->
<dependency> <dependency>
<groupId>ch.qos.logback</groupId> <groupId>ch.qos.logback</groupId>
@ -100,12 +112,6 @@
<version>1.2.71</version> <version>1.2.71</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId> <artifactId>spring-boot</artifactId>
@ -121,7 +127,7 @@
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.12</version> <version>4.13.1</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
@ -162,6 +168,7 @@
<exclude>com/alibaba/excel/event/AnalysisEventListener.java</exclude> <exclude>com/alibaba/excel/event/AnalysisEventListener.java</exclude>
<exclude>com/alibaba/excel/metadata/DataFormatter.java</exclude> <exclude>com/alibaba/excel/metadata/DataFormatter.java</exclude>
<exclude>com/alibaba/excel/util/DateUtils.java</exclude> <exclude>com/alibaba/excel/util/DateUtils.java</exclude>
<exclude>com/alibaba/excel/util/MapUtils.java</exclude>
<exclude>com/alibaba/excel/metadata/format/DataFormatter.java</exclude> <exclude>com/alibaba/excel/metadata/format/DataFormatter.java</exclude>
<exclude>com/alibaba/excel/metadata/format/ExcelGeneralNumberFormat.java</exclude> <exclude>com/alibaba/excel/metadata/format/ExcelGeneralNumberFormat.java</exclude>
</excludes> </excludes>
@ -187,8 +194,8 @@
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<configuration> <configuration>
<source>1.6</source> <source>1.8</source>
<target>1.6</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
@ -232,6 +239,19 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-maven-plugin</artifactId>
<version>1.18.20.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>delombok</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
</project> </project>

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

@ -3,17 +3,10 @@ package com.alibaba.excel;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; 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.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder; import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.read.listener.ReadListener; 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.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder; import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterTableBuilder; import com.alibaba.excel.write.builder.ExcelWriterTableBuilder;
@ -39,138 +32,6 @@ import com.alibaba.excel.write.builder.ExcelWriterTableBuilder;
*/ */
public class EasyExcelFactory { public class EasyExcelFactory {
/**
* Quickly read small filesno 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<Object> read(InputStream in, Sheet sheet) {
final List<Object> rows = new ArrayList<Object>();
new ExcelReader(in, null, new AnalysisEventListener<Object>() {
@Override
public void invoke(Object object, AnalysisContext context) {
rows.add(object);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {}
}, false).read(sheet);
return rows;
}
/**
* 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 nullthe 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 nullthe 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 * Build excel the write

181
src/main/java/com/alibaba/excel/ExcelReader.java

@ -1,25 +1,17 @@
package com.alibaba.excel; package com.alibaba.excel;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.analysis.ExcelAnalyser; import com.alibaba.excel.analysis.ExcelAnalyser;
import com.alibaba.excel.analysis.ExcelAnalyserImpl; import com.alibaba.excel.analysis.ExcelAnalyserImpl;
import com.alibaba.excel.analysis.ExcelReadExecutor; import com.alibaba.excel.analysis.ExcelReadExecutor;
import com.alibaba.excel.cache.MapCache;
import com.alibaba.excel.context.AnalysisContext; 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.ReadSheet;
import com.alibaba.excel.read.metadata.ReadWorkbook; 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. * Excel readers are all read in event mode.
@ -34,113 +26,6 @@ public class ExcelReader {
*/ */
private ExcelAnalyser excelAnalyser; 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<ReadListener> customReadListenerList = new ArrayList<ReadListener>();
customReadListenerList.add(eventListener);
readWorkbook.setCustomReadListenerList(customReadListenerList);
}
readWorkbook.setAutoTrim(trim);
readWorkbook.setAutoCloseStream(Boolean.FALSE);
readWorkbook.setMandatoryUseInputStream(Boolean.TRUE);
readWorkbook.setReadCache(new MapCache());
readWorkbook.setConvertAllFiled(Boolean.FALSE);
readWorkbook.setDefaultReturnMap(Boolean.FALSE);
// The previous logic was that Article 0 started reading
readWorkbook.setHeadRowNumber(0);
excelAnalyser = new ExcelAnalyserImpl(readWorkbook);
}
public ExcelReader(ReadWorkbook readWorkbook) { public ExcelReader(ReadWorkbook readWorkbook) {
excelAnalyser = new ExcelAnalyserImpl(readWorkbook); excelAnalyser = new ExcelAnalyserImpl(readWorkbook);
} }
@ -183,44 +68,6 @@ public class ExcelReader {
return this; return this;
} }
/**
* Parse the specified sheetSheetNo start from 1
*
* @param sheet
* Read sheet
* @deprecated please us {@link #read(ReadSheet...)}
*/
@Deprecated
public void read(Sheet sheet) {
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 * Context for the entire execution process
@ -240,28 +87,6 @@ public class ExcelReader {
return excelAnalyser.excelExecutor(); return excelAnalyser.excelExecutor();
} }
/**
* Parse the workBook get all sheets
*
* @return workBook all sheets
*
* @deprecated please use {@link #excelExecutor()}
*/
@Deprecated
public List<Sheet> getSheets() {
List<ReadSheet> sheetList = excelExecutor().sheetList();
List<Sheet> sheets = new ArrayList<Sheet>();
if (sheetList == null || sheetList.isEmpty()) {
return sheets;
}
for (ReadSheet readSheet : sheetList) {
Sheet sheet = new Sheet(readSheet.getSheetNo() + 1);
sheet.setSheetName(readSheet.getSheetName());
sheets.add(sheet);
}
return sheets;
}
/** /**
* *
* @return * @return

242
src/main/java/com/alibaba/excel/ExcelWriter.java

@ -1,27 +1,18 @@
package com.alibaba.excel; package com.alibaba.excel;
import java.io.InputStream; import java.util.Collection;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.context.WriteContext; 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.ExcelBuilder;
import com.alibaba.excel.write.ExcelBuilderImpl; 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.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable; import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.WriteWorkbook; import com.alibaba.excel.write.metadata.WriteWorkbook;
import com.alibaba.excel.write.metadata.fill.FillConfig; 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 * Excel Writer This tool is used to write value out to Excel via POI. This object can perform the following two
* functions. * functions.
@ -47,92 +38,6 @@ public class ExcelWriter {
excelBuilder = new ExcelBuilderImpl(writeWorkbook); 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 nullthe 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 nullthe 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<WriteHandler> customWriteHandlerList = new ArrayList<WriteHandler>();
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 * Write data to a sheet
* *
@ -142,7 +47,7 @@ public class ExcelWriter {
* Write to this sheet * Write to this sheet
* @return this current writer * @return this current writer
*/ */
public ExcelWriter write(List data, WriteSheet writeSheet) { public ExcelWriter write(Collection<?> data, WriteSheet writeSheet) {
return write(data, writeSheet, null); return write(data, writeSheet, null);
} }
@ -157,7 +62,7 @@ public class ExcelWriter {
* Write to this table * Write to this table
* @return this * @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); excelBuilder.addContent(data, writeSheet, writeTable);
return this; return this;
} }
@ -186,141 +91,6 @@ public class ExcelWriter {
return this; return this;
} }
/**
* Write data to a sheet
*
* @param data
* Data to be written
* @param sheet
* Write to this sheet
* @return this current writer
* @deprecated please use {@link ExcelWriter#write(List, WriteSheet)}
*/
@Deprecated
public ExcelWriter write(List data, Sheet sheet) {
return write(data, sheet, null);
}
/**
* Write value to a sheet
*
* @param data
* Data to be written
* @param sheet
* Write to this sheet
* @param table
* Write to this table
* @return this
* @deprecated * @deprecated please use {@link ExcelWriter#write(List, 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(List, 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(List, WriteSheet,WriteTable)}
*/
@Deprecated
public ExcelWriter write0(List data, Sheet sheet, Table table) {
return write(data, sheet, table);
}
/**
* Write data to a sheet
*
* @param data
* Data to be written
* @param sheet
* Write to this sheet
* @return this current writer
* @deprecated please use {@link ExcelWriter#write(List, WriteSheet)}
*/
@Deprecated
public ExcelWriter write1(List data, Sheet sheet) {
return write(data, sheet, null);
}
/**
* 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(List, WriteSheet,WriteTable)}
*/
@Deprecated
public ExcelWriter write1(List data, Sheet sheet, Table table) {
return write(data, sheet, table);
}
/**
* Merge CellsIndexes 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 * Close IO
*/ */

26
src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java

@ -3,17 +3,12 @@ package com.alibaba.excel.analysis;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import com.alibaba.excel.analysis.csv.CsvExcelReadExecutor;
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.v03.XlsSaxAnalyser; import com.alibaba.excel.analysis.v03.XlsSaxAnalyser;
import com.alibaba.excel.analysis.v07.XlsxSaxAnalyser; import com.alibaba.excel.analysis.v07.XlsxSaxAnalyser;
import com.alibaba.excel.context.AnalysisContext; 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.DefaultXlsReadContext;
import com.alibaba.excel.context.xls.XlsReadContext; import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.context.xlsx.DefaultXlsxReadContext; import com.alibaba.excel.context.xlsx.DefaultXlsxReadContext;
@ -26,12 +21,20 @@ import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder;
import com.alibaba.excel.read.metadata.holder.xls.XlsReadWorkbookHolder; import com.alibaba.excel.read.metadata.holder.xls.XlsReadWorkbookHolder;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadWorkbookHolder; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadWorkbookHolder;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.DateUtils; import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.NumberDataFormatterUtils; import com.alibaba.excel.util.NumberDataFormatterUtils;
import com.alibaba.excel.util.StringUtils; 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 * @author jipengfei
*/ */
@ -98,6 +101,11 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
analysisContext = xlsxReadContext; analysisContext = xlsxReadContext;
excelReadExecutor = new XlsxSaxAnalyser(xlsxReadContext, null); excelReadExecutor = new XlsxSaxAnalyser(xlsxReadContext, null);
break; break;
case CSV:
CsvReadContext csvReadContext = new DefaultCsvReadContext(readWorkbook, ExcelTypeEnum.CSV);
analysisContext = csvReadContext;
excelReadExecutor = new CsvExcelReadExecutor(csvReadContext);
break;
default: default:
break; break;
} }

122
src/main/java/com/alibaba/excel/analysis/csv/CsvExcelReadExecutor.java

@ -0,0 +1,122 @@
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 com.alibaba.excel.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
/**
* read executor
*
* @author zhuangjiaju
*/
@Slf4j
public class CsvExcelReadExecutor implements ExcelReadExecutor {
private List<ReadSheet> 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<ReadSheet> sheetList() {
return sheetList;
}
@Override
public void execute() {
Iterable<CSVRecord> 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<CSVRecord> 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<Integer, Cell> cellMap = new LinkedHashMap<>();
Iterator<String> cellIterator = record.iterator();
int columnIndex = 0;
while (cellIterator.hasNext()) {
String cellString = cellIterator.next();
ReadCellData<String> readCellData = new ReadCellData<>();
readCellData.setRowIndex(rowIndex);
readCellData.setColumnIndex(columnIndex);
// csv is an empty string of whether <code>,,</code> is read or <code>,"",</code>
if (StringUtils.isNotBlank(cellString)) {
readCellData.setType(CellDataTypeEnum.STRING);
readCellData.setStringValue(cellString);
} else {
readCellData.setType(CellDataTypeEnum.EMPTY);
}
cellMap.put(columnIndex++, 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);
}
}

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

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

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

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

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

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

36
src/main/java/com/alibaba/excel/analysis/v03/handlers/FormulaRecordHandler.java

@ -3,36 +3,36 @@ package com.alibaba.excel.analysis.v03.handlers;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Map; 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.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.constant.BuiltinFormats; import com.alibaba.excel.constant.BuiltinFormats;
import com.alibaba.excel.context.xls.XlsReadContext; import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.enums.RowTypeEnum; import com.alibaba.excel.enums.RowTypeEnum;
import com.alibaba.excel.metadata.Cell; 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;
/** /**
* Record handler * Record handler
* *
* @author Dan Zheng * @author Dan Zheng
*/ */
@Slf4j
public class FormulaRecordHandler extends AbstractXlsRecordHandler implements IgnorableXlsRecordHandler { public class FormulaRecordHandler extends AbstractXlsRecordHandler implements IgnorableXlsRecordHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(FormulaRecordHandler.class);
private static final String ERROR = "#VALUE!"; private static final String ERROR = "#VALUE!";
@Override @Override
public void processRecord(XlsReadContext xlsReadContext, Record record) { public void processRecord(XlsReadContext xlsReadContext, Record record) {
FormulaRecord frec = (FormulaRecord)record; FormulaRecord frec = (FormulaRecord)record;
Map<Integer, Cell> cellMap = xlsReadContext.xlsReadSheetHolder().getCellMap(); Map<Integer, Cell> cellMap = xlsReadContext.xlsReadSheetHolder().getCellMap();
CellData tempCellData = new CellData(); ReadCellData<?> tempCellData = new ReadCellData<>();
tempCellData.setRowIndex(frec.getRow()); tempCellData.setRowIndex(frec.getRow());
tempCellData.setColumnIndex((int)frec.getColumn()); tempCellData.setColumnIndex((int)frec.getColumn());
CellType cellType = CellType.forInt(frec.getCachedResultType()); CellType cellType = CellType.forInt(frec.getCachedResultType());
@ -41,10 +41,11 @@ public class FormulaRecordHandler extends AbstractXlsRecordHandler implements Ig
formulaValue = HSSFFormulaParser.toFormulaString(xlsReadContext.xlsReadWorkbookHolder().getHssfWorkbook(), formulaValue = HSSFFormulaParser.toFormulaString(xlsReadContext.xlsReadWorkbookHolder().getHssfWorkbook(),
frec.getParsedExpression()); frec.getParsedExpression());
} catch (Exception e) { } catch (Exception e) {
LOGGER.debug("Get formula value error.", e); log.debug("Get formula value error.", e);
} }
tempCellData.setFormula(Boolean.TRUE); FormulaData formulaData = new FormulaData();
tempCellData.setFormulaValue(formulaValue); formulaData.setFormulaValue(formulaValue);
tempCellData.setFormulaData(formulaData);
xlsReadContext.xlsReadSheetHolder().setTempRowType(RowTypeEnum.DATA); xlsReadContext.xlsReadSheetHolder().setTempRowType(RowTypeEnum.DATA);
switch (cellType) { switch (cellType) {
case STRING: case STRING:
@ -56,10 +57,11 @@ public class FormulaRecordHandler extends AbstractXlsRecordHandler implements Ig
case NUMERIC: case NUMERIC:
tempCellData.setType(CellDataTypeEnum.NUMBER); tempCellData.setType(CellDataTypeEnum.NUMBER);
tempCellData.setNumberValue(BigDecimal.valueOf(frec.getValue())); tempCellData.setNumberValue(BigDecimal.valueOf(frec.getValue()));
Integer dataFormat = int dataFormat =
xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatIndex(frec); xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatIndex(frec);
tempCellData.setDataFormat(dataFormat); DataFormatData dataFormatData = new DataFormatData();
tempCellData.setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormat, dataFormatData.setIndex((short)dataFormat);
dataFormatData.setFormat(BuiltinFormats.getBuiltinFormat(dataFormatData.getIndex(),
xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatString(frec), xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatString(frec),
xlsReadContext.readSheetHolder().getGlobalConfiguration().getLocale())); xlsReadContext.readSheetHolder().getGlobalConfiguration().getLocale()));
cellMap.put((int)frec.getColumn(), tempCellData); cellMap.put((int)frec.getColumn(), tempCellData);

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

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

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

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

21
src/main/java/com/alibaba/excel/analysis/v03/handlers/NumberRecordHandler.java

@ -2,14 +2,15 @@ package com.alibaba.excel.analysis.v03.handlers;
import java.math.BigDecimal; 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.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.constant.BuiltinFormats; import com.alibaba.excel.constant.BuiltinFormats;
import com.alibaba.excel.context.xls.XlsReadContext; import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.enums.RowTypeEnum; 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;
/** /**
* Record handler * Record handler
@ -21,12 +22,16 @@ public class NumberRecordHandler extends AbstractXlsRecordHandler implements Ign
@Override @Override
public void processRecord(XlsReadContext xlsReadContext, Record record) { public void processRecord(XlsReadContext xlsReadContext, Record record) {
NumberRecord nr = (NumberRecord)record; NumberRecord nr = (NumberRecord)record;
CellData cellData = CellData.newInstance(BigDecimal.valueOf(nr.getValue()), nr.getRow(), (int)nr.getColumn()); ReadCellData<?> cellData = ReadCellData.newInstance(BigDecimal.valueOf(nr.getValue()), nr.getRow(),
Integer dataFormat = xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatIndex(nr); (int)nr.getColumn());
cellData.setDataFormat(dataFormat); short dataFormat = (short)xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatIndex(
cellData.setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormat, nr);
DataFormatData dataFormatData = new DataFormatData();
dataFormatData.setIndex(dataFormat);
dataFormatData.setFormat(BuiltinFormats.getBuiltinFormat(dataFormat,
xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatString(nr), xlsReadContext.xlsReadWorkbookHolder().getFormatTrackingHSSFListener().getFormatString(nr),
xlsReadContext.readSheetHolder().getGlobalConfiguration().getLocale())); xlsReadContext.readSheetHolder().getGlobalConfiguration().getLocale()));
cellData.setDataFormatData(dataFormatData);
xlsReadContext.xlsReadSheetHolder().getCellMap().put((int)nr.getColumn(), cellData); xlsReadContext.xlsReadSheetHolder().getCellMap().put((int)nr.getColumn(), cellData);
xlsReadContext.xlsReadSheetHolder().setTempRowType(RowTypeEnum.DATA); xlsReadContext.xlsReadSheetHolder().setTempRowType(RowTypeEnum.DATA);
} }

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

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

4
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.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.context.xls.XlsReadContext; 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; import com.alibaba.excel.read.metadata.holder.xls.XlsReadSheetHolder;
/** /**
@ -23,7 +23,7 @@ public class StringRecordHandler extends AbstractXlsRecordHandler implements Ign
// String for formula // String for formula
StringRecord srec = (StringRecord)record; StringRecord srec = (StringRecord)record;
XlsReadSheetHolder xlsReadSheetHolder = xlsReadContext.xlsReadSheetHolder(); XlsReadSheetHolder xlsReadSheetHolder = xlsReadContext.xlsReadSheetHolder();
CellData tempCellData = xlsReadSheetHolder.getTempCellData(); CellData<?>tempCellData = xlsReadSheetHolder.getTempCellData();
if (tempCellData == null) { if (tempCellData == null) {
LOGGER.warn("String type formula but no value found."); LOGGER.warn("String type formula but no value found.");
return; return;

58
src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java

@ -9,9 +9,26 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory; 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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess; import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackagePart;
@ -25,26 +42,13 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument; import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader; 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.CollectionUtils;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.SheetUtils;
import com.alibaba.excel.util.StringUtils;
/** /**
* @author jipengfei * @author jipengfei
*/ */
@Slf4j
public class XlsxSaxAnalyser implements ExcelReadExecutor { public class XlsxSaxAnalyser implements ExcelReadExecutor {
private XlsxReadContext xlsxReadContext; private XlsxReadContext xlsxReadContext;
@ -78,7 +82,9 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor {
XSSFReader xssfReader = new XSSFReader(pkg); XSSFReader xssfReader = new XSSFReader(pkg);
analysisUse1904WindowDate(xssfReader, xlsxReadWorkbookHolder); analysisUse1904WindowDate(xssfReader, xlsxReadWorkbookHolder);
xlsxReadWorkbookHolder.setStylesTable(xssfReader.getStylesTable()); // set style table
setStylesTable(xlsxReadWorkbookHolder, xssfReader);
sheetList = new ArrayList<ReadSheet>(); sheetList = new ArrayList<ReadSheet>();
sheetMap = new HashMap<Integer, InputStream>(); sheetMap = new HashMap<Integer, InputStream>();
commentsTableMap = new HashMap<Integer, CommentsTable>(); commentsTableMap = new HashMap<Integer, CommentsTable>();
@ -101,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, private void defaultReadCache(XlsxReadWorkbookHolder xlsxReadWorkbookHolder,
PackagePart sharedStringsTablePackagePart) { PackagePart sharedStringsTablePackagePart) {
ReadCache readCache = xlsxReadWorkbookHolder.getReadCacheSelector().readCache(sharedStringsTablePackagePart); ReadCache readCache = xlsxReadWorkbookHolder.getReadCacheSelector().readCache(sharedStringsTablePackagePart);
@ -147,9 +164,10 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor {
xlsxReadWorkbookHolder.setTempFile(readTempFile); xlsxReadWorkbookHolder.setTempFile(readTempFile);
File tempFile = new File(readTempFile.getPath(), UUID.randomUUID().toString() + ".xlsx"); File tempFile = new File(readTempFile.getPath(), UUID.randomUUID().toString() + ".xlsx");
if (decryptedStream != null) { if (decryptedStream != null) {
FileUtils.writeToFile(tempFile, decryptedStream); FileUtils.writeToFile(tempFile, decryptedStream, false);
} else { } else {
FileUtils.writeToFile(tempFile, xlsxReadWorkbookHolder.getInputStream()); FileUtils.writeToFile(tempFile, xlsxReadWorkbookHolder.getInputStream(),
xlsxReadWorkbookHolder.getAutoCloseStream());
} }
return OPCPackage.open(tempFile, PackageAccess.READ); return OPCPackage.open(tempFile, PackageAccess.READ);
} }
@ -177,9 +195,7 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor {
xmlReader.setContentHandler(handler); xmlReader.setContentHandler(handler);
xmlReader.parse(inputSource); xmlReader.parse(inputSource);
inputStream.close(); inputStream.close();
} catch (ExcelAnalysisException e) { } catch (IOException | ParserConfigurationException | SAXException e) {
throw e;
} catch (Exception e) {
throw new ExcelAnalysisException(e); throw new ExcelAnalysisException(e);
} finally { } finally {
if (inputStream != null) { if (inputStream != null) {

6
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.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData; import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder;
import com.alibaba.excel.util.BooleanUtils; import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.util.StringUtils;
@ -19,7 +19,7 @@ public abstract class AbstractCellValueTagHandler extends AbstractXlsxTagHandler
@Override @Override
public void endElement(XlsxReadContext xlsxReadContext, String name) { public void endElement(XlsxReadContext xlsxReadContext, String name) {
XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder(); XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder();
CellData tempCellData = xlsxReadSheetHolder.getTempCellData(); ReadCellData<?> tempCellData = xlsxReadSheetHolder.getTempCellData();
StringBuilder tempData = xlsxReadSheetHolder.getTempData(); StringBuilder tempData = xlsxReadSheetHolder.getTempData();
String tempDataString = tempData.toString(); String tempDataString = tempData.toString();
CellDataTypeEnum oldType = tempCellData.getType(); CellDataTypeEnum oldType = tempCellData.getType();
@ -54,7 +54,7 @@ public abstract class AbstractCellValueTagHandler extends AbstractXlsxTagHandler
if (tempCellData.getStringValue() != null if (tempCellData.getStringValue() != null
&& xlsxReadContext.currentReadHolder().globalConfiguration().getAutoTrim()) { && xlsxReadContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
tempCellData.setStringValue(tempCellData.getStringValue()); tempCellData.setStringValue(tempCellData.getStringValue().trim());
} }
tempCellData.checkEmpty(); tempCellData.checkEmpty();

10
src/main/java/com/alibaba/excel/analysis/v07/handlers/CellFormulaTagHandler.java

@ -1,10 +1,11 @@
package com.alibaba.excel.analysis.v07.handlers; package com.alibaba.excel.analysis.v07.handlers;
import org.xml.sax.Attributes;
import com.alibaba.excel.context.xlsx.XlsxReadContext; import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.metadata.data.FormulaData;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder;
import org.xml.sax.Attributes;
/** /**
* Cell Handler * Cell Handler
* *
@ -15,14 +16,15 @@ public class CellFormulaTagHandler extends AbstractXlsxTagHandler {
@Override @Override
public void startElement(XlsxReadContext xlsxReadContext, String name, Attributes attributes) { public void startElement(XlsxReadContext xlsxReadContext, String name, Attributes attributes) {
XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder(); XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder();
xlsxReadSheetHolder.getTempCellData().setFormula(Boolean.TRUE);
xlsxReadSheetHolder.setTempFormula(new StringBuilder()); xlsxReadSheetHolder.setTempFormula(new StringBuilder());
} }
@Override @Override
public void endElement(XlsxReadContext xlsxReadContext, String name) { public void endElement(XlsxReadContext xlsxReadContext, String name) {
XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder(); XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder();
xlsxReadSheetHolder.getTempCellData().setFormulaValue(xlsxReadSheetHolder.getTempFormula().toString()); FormulaData formulaData = new FormulaData();
formulaData.setFormulaValue(xlsxReadSheetHolder.getTempFormula().toString());
xlsxReadSheetHolder.getTempCellData().setFormulaData(formulaData);
} }
@Override @Override

8
src/main/java/com/alibaba/excel/analysis/v07/handlers/CellInlineStringValueTagHandler.java

@ -1,9 +1,9 @@
package com.alibaba.excel.analysis.v07.handlers; 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.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 * Cell inline string value handler
@ -15,7 +15,7 @@ public class CellInlineStringValueTagHandler extends AbstractCellValueTagHandler
@Override @Override
protected void setStringValue(XlsxReadContext xlsxReadContext) { protected void setStringValue(XlsxReadContext xlsxReadContext) {
// This is a special form of string // This is a special form of string
CellData tempCellData = xlsxReadContext.xlsxReadSheetHolder().getTempCellData(); CellData<?> tempCellData = xlsxReadContext.xlsxReadSheetHolder().getTempCellData();
XSSFRichTextString richTextString = new XSSFRichTextString(tempCellData.getStringValue()); XSSFRichTextString richTextString = new XSSFRichTextString(tempCellData.getStringValue());
tempCellData.setStringValue(richTextString.toString()); tempCellData.setStringValue(richTextString.toString());
} }

27
src/main/java/com/alibaba/excel/analysis/v07/handlers/CellTagHandler.java

@ -1,17 +1,19 @@
package com.alibaba.excel.analysis.v07.handlers; 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.BuiltinFormats;
import com.alibaba.excel.constant.ExcelXmlConstants; import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.xlsx.XlsxReadContext; import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellDataTypeEnum; 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.read.metadata.holder.xlsx.XlsxReadSheetHolder;
import com.alibaba.excel.util.PositionUtils; import com.alibaba.excel.util.PositionUtils;
import com.alibaba.excel.util.StringUtils; 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 * Cell Handler
* *
@ -35,7 +37,7 @@ public class CellTagHandler extends AbstractXlsxTagHandler {
// t="n" ,it's means Number // t="n" ,it's means Number
// t is null ,it's means Empty or Number // t is null ,it's means Empty or Number
CellDataTypeEnum type = CellDataTypeEnum.buildFromCellType(attributes.getValue(ExcelXmlConstants.ATTRIBUTE_T)); CellDataTypeEnum type = CellDataTypeEnum.buildFromCellType(attributes.getValue(ExcelXmlConstants.ATTRIBUTE_T));
xlsxReadSheetHolder.setTempCellData(new CellData(type)); xlsxReadSheetHolder.setTempCellData(new ReadCellData<>(type));
xlsxReadSheetHolder.setTempData(new StringBuilder()); xlsxReadSheetHolder.setTempData(new StringBuilder());
// Put in data transformation information // Put in data transformation information
@ -46,12 +48,17 @@ public class CellTagHandler extends AbstractXlsxTagHandler {
} else { } else {
dateFormatIndexInteger = Integer.parseInt(dateFormatIndex); dateFormatIndexInteger = Integer.parseInt(dateFormatIndex);
} }
XSSFCellStyle xssfCellStyle = StylesTable stylesTable = xlsxReadContext.xlsxReadWorkbookHolder().getStylesTable();
xlsxReadContext.xlsxReadWorkbookHolder().getStylesTable().getStyleAt(dateFormatIndexInteger); if (stylesTable == null) {
int dataFormat = xssfCellStyle.getDataFormat(); return;
xlsxReadSheetHolder.getTempCellData().setDataFormat(dataFormat); }
xlsxReadSheetHolder.getTempCellData().setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormat, XSSFCellStyle xssfCellStyle = stylesTable.getStyleAt(dateFormatIndexInteger);
short dataFormat = xssfCellStyle.getDataFormat();
DataFormatData dataFormatData = new DataFormatData();
dataFormatData.setIndex(dataFormat);
dataFormatData.setFormat(BuiltinFormats.getBuiltinFormat(dataFormat,
xssfCellStyle.getDataFormatString(), xlsxReadSheetHolder.getGlobalConfiguration().getLocale())); xssfCellStyle.getDataFormatString(), xlsxReadSheetHolder.getGlobalConfiguration().getLocale()));
xlsxReadSheetHolder.getTempCellData().setDataFormatData(dataFormatData);
} }
} }

2
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.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellDataTypeEnum; 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; import com.alibaba.excel.util.StringUtils;
/** /**

11
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 java.util.LinkedHashMap;
import org.xml.sax.Attributes;
import com.alibaba.excel.constant.ExcelXmlConstants; import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.xlsx.XlsxReadContext; import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.RowTypeEnum; import com.alibaba.excel.enums.RowTypeEnum;
import com.alibaba.excel.metadata.Cell; import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder; import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.PositionUtils; import com.alibaba.excel.util.PositionUtils;
import org.apache.commons.collections4.MapUtils;
import org.xml.sax.Attributes;
/** /**
* Cell Handler * Cell Handler
* *
@ -40,13 +40,12 @@ public class RowTagHandler extends AbstractXlsxTagHandler {
@Override @Override
public void endElement(XlsxReadContext xlsxReadContext, String name) { public void endElement(XlsxReadContext xlsxReadContext, String name) {
XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder(); XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder();
RowTypeEnum rowType = RowTypeEnum rowType = MapUtils.isEmpty(xlsxReadSheetHolder.getCellMap()) ? RowTypeEnum.EMPTY : RowTypeEnum.DATA;
CollectionUtils.isEmpty(xlsxReadSheetHolder.getCellMap()) ? RowTypeEnum.EMPTY : RowTypeEnum.DATA;
xlsxReadContext.readRowHolder(new ReadRowHolder(xlsxReadSheetHolder.getRowIndex(), rowType, xlsxReadContext.readRowHolder(new ReadRowHolder(xlsxReadSheetHolder.getRowIndex(), rowType,
xlsxReadSheetHolder.getGlobalConfiguration(), xlsxReadSheetHolder.getCellMap())); xlsxReadSheetHolder.getGlobalConfiguration(), xlsxReadSheetHolder.getCellMap()));
xlsxReadContext.analysisEventProcessor().endRow(xlsxReadContext); xlsxReadContext.analysisEventProcessor().endRow(xlsxReadContext);
xlsxReadSheetHolder.setColumnIndex(null); xlsxReadSheetHolder.setColumnIndex(null);
xlsxReadSheetHolder.setCellMap(new LinkedHashMap<Integer, Cell>()); xlsxReadSheetHolder.setCellMap(new LinkedHashMap<>());
} }
} }

2
src/main/java/com/alibaba/excel/annotation/ExcelProperty.java

@ -23,7 +23,7 @@ public @interface ExcelProperty {
* <p> * <p>
* write: It automatically merges when you have more than one head * write: It automatically merges when you have more than one head
* <p> * <p>
* 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 * @return The name of the sheet header
*/ */

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

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

92
src/main/java/com/alibaba/excel/cache/Ehcache.java vendored

@ -1,50 +1,49 @@
package com.alibaba.excel.cache; package com.alibaba.excel.cache;
import java.io.File; import java.io.File;
import java.util.HashMap; import java.util.ArrayList;
import java.util.UUID; 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.ehcache.CacheManager; import org.ehcache.CacheManager;
import org.ehcache.config.CacheConfiguration; import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.MemoryUnit; 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.CollectionUtils;
import com.alibaba.excel.util.FileUtils;
/** /**
* Default cache * Default cache
* *
* @author Jiaju Zhuang * @author Jiaju Zhuang
*/ */
@Slf4j
public class Ehcache implements ReadCache { public class Ehcache implements ReadCache {
public static final int BATCH_COUNT = 1000;
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;
/** /**
* Key index * Key index
*/ */
private int index = 0; private int activeIndex = 0;
private HashMap<Integer, String> dataMap = new HashMap<Integer, String>(BATCH_COUNT * 4 / 3 + 1); public static final int DEBUG_CACHE_MISS_SIZE = 1000;
private static CacheManager fileCacheManager; public static final int DEBUG_WRITE_SIZE = 100 * 10000;
private static CacheConfiguration<Integer, HashMap> fileCacheConfiguration; private ArrayList<String> dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
private static CacheManager activeCacheManager; private static final CacheManager FILE_CACHE_MANAGER;
private CacheConfiguration<Integer, HashMap> activeCacheConfiguration; private static final CacheConfiguration<Integer, ArrayList> FILE_CACHE_CONFIGURATION;
private static final CacheManager ACTIVE_CACHE_MANAGER;
private final CacheConfiguration<Integer, ArrayList> activeCacheConfiguration;
/** /**
* Bulk storage data * Bulk storage data
*/ */
private org.ehcache.Cache<Integer, HashMap> fileCache; private org.ehcache.Cache<Integer, ArrayList> fileCache;
/** /**
* Currently active cache * Currently active cache
*/ */
private org.ehcache.Cache<Integer, HashMap> activeCache; private org.ehcache.Cache<Integer, ArrayList> activeCache;
private String cacheAlias; private String cacheAlias;
/** /**
* Count the number of cache misses * Count the number of cache misses
@ -53,7 +52,7 @@ public class Ehcache implements ReadCache {
public Ehcache(int maxCacheActivateSize) { public Ehcache(int maxCacheActivateSize) {
activeCacheConfiguration = CacheConfigurationBuilder activeCacheConfiguration = CacheConfigurationBuilder
.newCacheConfigurationBuilder(Integer.class, HashMap.class, .newCacheConfigurationBuilder(Integer.class, ArrayList.class,
ResourcePoolsBuilder.newResourcePoolsBuilder().heap(maxCacheActivateSize, MemoryUnit.MB)) ResourcePoolsBuilder.newResourcePoolsBuilder().heap(maxCacheActivateSize, MemoryUnit.MB))
.withSizeOfMaxObjectGraph(1000 * 1000L).withSizeOfMaxObjectSize(maxCacheActivateSize, MemoryUnit.MB) .withSizeOfMaxObjectGraph(1000 * 1000L).withSizeOfMaxObjectSize(maxCacheActivateSize, MemoryUnit.MB)
.build(); .build();
@ -61,11 +60,11 @@ public class Ehcache implements ReadCache {
static { static {
File cacheFile = FileUtils.createCacheTmpFile(); File cacheFile = FileUtils.createCacheTmpFile();
fileCacheManager = FILE_CACHE_MANAGER =
CacheManagerBuilder.newCacheManagerBuilder().with(CacheManagerBuilder.persistence(cacheFile)).build(true); CacheManagerBuilder.newCacheManagerBuilder().with(CacheManagerBuilder.persistence(cacheFile)).build(true);
activeCacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true); ACTIVE_CACHE_MANAGER = CacheManagerBuilder.newCacheManagerBuilder().build(true);
fileCacheConfiguration = CacheConfigurationBuilder FILE_CACHE_CONFIGURATION = CacheConfigurationBuilder
.newCacheConfigurationBuilder(Integer.class, HashMap.class, .newCacheConfigurationBuilder(Integer.class, ArrayList.class,
ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MemoryUnit.GB)) ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MemoryUnit.GB))
.withSizeOfMaxObjectGraph(1000 * 1000L).withSizeOfMaxObjectSize(10, MemoryUnit.GB).build(); .withSizeOfMaxObjectGraph(1000 * 1000L).withSizeOfMaxObjectSize(10, MemoryUnit.GB).build();
} }
@ -73,21 +72,22 @@ public class Ehcache implements ReadCache {
@Override @Override
public void init(AnalysisContext analysisContext) { public void init(AnalysisContext analysisContext) {
cacheAlias = UUID.randomUUID().toString(); cacheAlias = UUID.randomUUID().toString();
fileCache = fileCacheManager.createCache(cacheAlias, fileCacheConfiguration); fileCache = FILE_CACHE_MANAGER.createCache(cacheAlias, FILE_CACHE_CONFIGURATION);
activeCache = activeCacheManager.createCache(cacheAlias, activeCacheConfiguration); activeCache = ACTIVE_CACHE_MANAGER.createCache(cacheAlias, activeCacheConfiguration);
} }
@Override @Override
public void put(String value) { public void put(String value) {
dataMap.put(index, value); dataList.add(value);
if ((index + 1) % BATCH_COUNT == 0) { if (dataList.size() >= BATCH_COUNT) {
fileCache.put(index / BATCH_COUNT, dataMap); fileCache.put(activeIndex, dataList);
dataMap = new HashMap<Integer, String>(BATCH_COUNT * 4 / 3 + 1); activeIndex++;
dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
} }
index++; if (log.isDebugEnabled()) {
if (LOGGER.isDebugEnabled()) { int alreadyPut = activeIndex * BATCH_COUNT + dataList.size();
if (index % DEBUG_WRITE_SIZE == 0) { if (alreadyPut % DEBUG_WRITE_SIZE == 0) {
LOGGER.debug("Already put :{}", index); log.debug("Already put :{}", alreadyPut);
} }
} }
} }
@ -98,31 +98,31 @@ public class Ehcache implements ReadCache {
return null; return null;
} }
int route = key / BATCH_COUNT; int route = key / BATCH_COUNT;
HashMap<Integer, String> dataMap = activeCache.get(route); ArrayList<String> dataList = activeCache.get(route);
if (dataMap == null) { if (dataList == null) {
dataMap = fileCache.get(route); dataList = fileCache.get(route);
activeCache.put(route, dataMap); activeCache.put(route, dataList);
if (LOGGER.isDebugEnabled()) { if (log.isDebugEnabled()) {
if (cacheMiss++ % DEBUG_CACHE_MISS_SIZE == 0) { 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 @Override
public void putFinished() { public void putFinished() {
if (CollectionUtils.isEmpty(dataMap)) { if (CollectionUtils.isEmpty(dataList)) {
return; return;
} }
fileCache.put(index / BATCH_COUNT, dataMap); fileCache.put(activeIndex, dataList);
} }
@Override @Override
public void destroy() { public void destroy() {
fileCacheManager.removeCache(cacheAlias); FILE_CACHE_MANAGER.removeCache(cacheAlias);
activeCacheManager.removeCache(cacheAlias); ACTIVE_CACHE_MANAGER.removeCache(cacheAlias);
} }
} }

10
src/main/java/com/alibaba/excel/cache/MapCache.java vendored

@ -1,26 +1,24 @@
package com.alibaba.excel.cache; package com.alibaba.excel.cache;
import java.util.HashMap; import java.util.ArrayList;
import java.util.Map; import java.util.List;
import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
/** /**
*
* Putting temporary data directly into a map is a little more efficient but very memory intensive * Putting temporary data directly into a map is a little more efficient but very memory intensive
* *
* @author Jiaju Zhuang * @author Jiaju Zhuang
*/ */
public class MapCache implements ReadCache { public class MapCache implements ReadCache {
private Map<Integer, String> cache = new HashMap<Integer, String>(); private List<String> cache = new ArrayList<>();
private int index = 0;
@Override @Override
public void init(AnalysisContext analysisContext) {} public void init(AnalysisContext analysisContext) {}
@Override @Override
public void put(String value) { public void put(String value) {
cache.put(index++, value); cache.add(value);
} }
@Override @Override

32
src/main/java/com/alibaba/excel/constant/BuiltinFormats.java

@ -1,6 +1,9 @@
package com.alibaba.excel.constant; package com.alibaba.excel.constant;
import java.util.Locale; import java.util.Locale;
import java.util.Map;
import com.alibaba.excel.util.MapUtils;
/** /**
* Excel's built-in format conversion.Currently only supports Chinese. * Excel's built-in format conversion.Currently only supports Chinese.
@ -17,7 +20,9 @@ import java.util.Locale;
**/ **/
public class BuiltinFormats { public class BuiltinFormats {
private static final String[] BUILTIN_FORMATS_CN = { public static short GENERAL = 0;
public static final String[] BUILTIN_FORMATS_CN = {
// 0 // 0
"General", "General",
// 1 // 1
@ -189,7 +194,7 @@ public class BuiltinFormats {
// end // end
}; };
private static final String[] BUILTIN_FORMATS_US = { public static final String[] BUILTIN_FORMATS_US = {
// 0 // 0
"General", "General",
// 1 // 1
@ -361,7 +366,11 @@ public class BuiltinFormats {
// end // end
}; };
public static String getBuiltinFormat(Integer index, String defaultFormat, Locale locale) { public static final Map<String, Short> BUILTIN_FORMATS_MAP_CN = buildMap(BUILTIN_FORMATS_CN);
public static final Map<String, Short> 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); String[] builtinFormat = switchBuiltinFormats(locale);
if (index == null || index < 0 || index >= builtinFormat.length) { if (index == null || index < 0 || index >= builtinFormat.length) {
return defaultFormat; return defaultFormat;
@ -369,11 +378,26 @@ public class BuiltinFormats {
return builtinFormat[index]; return builtinFormat[index];
} }
private static String[] switchBuiltinFormats(Locale locale) { public static String[] switchBuiltinFormats(Locale locale) {
if (locale != null && Locale.US.getCountry().equals(locale.getCountry())) { if (locale != null && Locale.US.getCountry().equals(locale.getCountry())) {
return BUILTIN_FORMATS_US; return BUILTIN_FORMATS_US;
} }
return BUILTIN_FORMATS_CN; return BUILTIN_FORMATS_CN;
} }
public static Map<String, Short> 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<String, Short> buildMap(String[] builtinFormats) {
Map<String, Short> map = MapUtils.newHashMapWithExpectedSize(builtinFormats.length);
for (int i = 0; i < builtinFormats.length; i++) {
map.put(builtinFormats[i], (short)i);
}
return map;
}
} }

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

@ -0,0 +1,24 @@
package com.alibaba.excel.constant;
/**
* Order 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_STYLE = 50000;
}

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

@ -4,7 +4,6 @@ import java.io.InputStream;
import java.util.List; import java.util.List;
import com.alibaba.excel.event.AnalysisEventListener; 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.ReadSheet;
import com.alibaba.excel.read.metadata.holder.ReadHolder; import com.alibaba.excel.read.metadata.holder.ReadHolder;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder; import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
@ -92,15 +91,6 @@ public interface AnalysisContext {
*/ */
void readSheetList(List<ReadSheet> readSheetList); void readSheetList(List<ReadSheet> readSheetList);
/**
* get current sheet
*
* @return current analysis sheet
* @deprecated please use {@link #readSheetHolder()}
*/
@Deprecated
Sheet getCurrentSheet();
/** /**
* *
* get excel type * get excel type

35
src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java

@ -3,17 +3,15 @@ package com.alibaba.excel.context;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.exception.ExcelAnalysisException; 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.ReadSheet;
import com.alibaba.excel.read.metadata.ReadWorkbook; import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.read.metadata.holder.ReadHolder; import com.alibaba.excel.read.metadata.holder.ReadHolder;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder; import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; import com.alibaba.excel.read.metadata.holder.ReadSheetHolder;
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder; 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.XlsReadSheetHolder;
import com.alibaba.excel.read.metadata.holder.xls.XlsReadWorkbookHolder; import com.alibaba.excel.read.metadata.holder.xls.XlsReadWorkbookHolder;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder; import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder;
@ -22,12 +20,13 @@ import com.alibaba.excel.read.processor.AnalysisEventProcessor;
import com.alibaba.excel.read.processor.DefaultAnalysisEventProcessor; import com.alibaba.excel.read.processor.DefaultAnalysisEventProcessor;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
/** /**
*
* @author jipengfei * @author jipengfei
*/ */
@Slf4j
public class AnalysisContextImpl implements AnalysisContext { public class AnalysisContextImpl implements AnalysisContext {
private static final Logger LOGGER = LoggerFactory.getLogger(AnalysisContextImpl.class);
/** /**
* The Workbook currently written * The Workbook currently written
*/ */
@ -60,13 +59,16 @@ public class AnalysisContextImpl implements AnalysisContext {
case XLSX: case XLSX:
readWorkbookHolder = new XlsxReadWorkbookHolder(readWorkbook); readWorkbookHolder = new XlsxReadWorkbookHolder(readWorkbook);
break; break;
case CSV:
readWorkbookHolder = new CsvReadWorkbookHolder(readWorkbook);
break;
default: default:
break; break;
} }
currentReadHolder = readWorkbookHolder; currentReadHolder = readWorkbookHolder;
analysisEventProcessor = new DefaultAnalysisEventProcessor(); analysisEventProcessor = new DefaultAnalysisEventProcessor();
if (LOGGER.isDebugEnabled()) { if (log.isDebugEnabled()) {
LOGGER.debug("Initialization 'AnalysisContextImpl' complete"); log.debug("Initialization 'AnalysisContextImpl' complete");
} }
} }
@ -79,6 +81,9 @@ public class AnalysisContextImpl implements AnalysisContext {
case XLSX: case XLSX:
readSheetHolder = new XlsxReadSheetHolder(readSheet, readWorkbookHolder); readSheetHolder = new XlsxReadSheetHolder(readSheet, readWorkbookHolder);
break; break;
case CSV:
readSheetHolder = new CsvReadSheetHolder(readSheet, readWorkbookHolder);
break;
default: default:
break; break;
} }
@ -87,8 +92,8 @@ public class AnalysisContextImpl implements AnalysisContext {
throw new ExcelAnalysisException("Cannot read sheet repeatedly."); throw new ExcelAnalysisException("Cannot read sheet repeatedly.");
} }
readWorkbookHolder.getHasReadSheet().add(readSheetHolder.getSheetNo()); readWorkbookHolder.getHasReadSheet().add(readSheetHolder.getSheetNo());
if (LOGGER.isDebugEnabled()) { if (log.isDebugEnabled()) {
LOGGER.debug("Began to read:{}", readSheetHolder); log.debug("Began to read:{}", readSheetHolder);
} }
} }
@ -137,16 +142,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 @Override
public ExcelTypeEnum getExcelType() { public ExcelTypeEnum getExcelType() {
return readWorkbookHolder.getExcelType(); return readWorkbookHolder.getExcelType();

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

@ -6,26 +6,10 @@ import java.io.OutputStream;
import java.util.Map; import java.util.Map;
import java.util.UUID; 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.enums.WriteTypeEnum;
import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.DateUtils; import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.util.FileUtils;
@ -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.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.property.ExcelWriteHeadProperty; 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. * 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 { public class WriteContextImpl implements WriteContext {
private static final Logger LOGGER = LoggerFactory.getLogger(WriteContextImpl.class); private static final Logger LOGGER = LoggerFactory.getLogger(WriteContextImpl.class);
private static final String NO_SHEETS = "no sheets";
/** /**
* The Workbook currently written * The Workbook currently written
@ -178,8 +179,12 @@ public class WriteContextImpl implements WriteContext {
writeSheetHolder writeSheetHolder
.setCachedSheet(writeWorkbookHolder.getCachedWorkbook().getSheet(writeSheetHolder.getSheetName())); .setCachedSheet(writeWorkbookHolder.getCachedWorkbook().getSheet(writeSheetHolder.getSheetName()));
} }
} catch (Exception e) { } catch (IllegalArgumentException e) {
if (e.getMessage() != null && e.getMessage().contains(NO_SHEETS)) {
currentSheet = createSheet(); currentSheet = createSheet();
} else {
throw e;
}
} }
if (currentSheet == null) { if (currentSheet == null) {
currentSheet = createSheet(); currentSheet = createSheet();
@ -240,10 +245,16 @@ public class WriteContextImpl implements WriteContext {
Head head = entry.getValue(); Head head = entry.getValue();
int columnIndex = entry.getKey(); int columnIndex = entry.getKey();
WriteHandlerUtils.beforeCellCreate(this, row, head, columnIndex, relativeRowIndex, Boolean.TRUE); WriteHandlerUtils.beforeCellCreate(this, row, head, columnIndex, relativeRowIndex, Boolean.TRUE);
Cell cell = row.createCell(columnIndex); Cell cell = row.createCell(columnIndex);
WriteHandlerUtils.afterCellCreate(this, cell, head, relativeRowIndex, Boolean.TRUE); WriteHandlerUtils.afterCellCreate(this, cell, head, relativeRowIndex, Boolean.TRUE);
cell.setCellValue(head.getHeadNameList().get(relativeRowIndex));
WriteHandlerUtils.afterCellDispose(this, (CellData) null, cell, head, relativeRowIndex, Boolean.TRUE); WriteCellData<String> writeCellData = new WriteCellData<>(head.getHeadNameList().get(relativeRowIndex));
cell.setCellValue(writeCellData.getStringValue());
WriteHandlerUtils.afterCellDispose(this, writeCellData, cell, head, relativeRowIndex,
Boolean.TRUE);
} }
} }
@ -441,14 +452,9 @@ public class WriteContextImpl implements WriteContext {
throw e; throw e;
} }
} }
POIFSFileSystem fileSystem = null; try (POIFSFileSystem fileSystem = openFileSystemAndEncrypt(tempXlsx)) {
try {
fileSystem = openFileSystemAndEncrypt(tempXlsx);
fileSystem.writeFilesystem(writeWorkbookHolder.getOutputStream()); fileSystem.writeFilesystem(writeWorkbookHolder.getOutputStream());
} finally { } finally {
if (fileSystem != null) {
fileSystem.close();
}
if (!tempXlsx.delete()) { if (!tempXlsx.delete()) {
throw new ExcelGenerateException("Can not delete temp File!"); throw new ExcelGenerateException("Can not delete temp File!");
} }
@ -467,19 +473,9 @@ public class WriteContextImpl implements WriteContext {
if (writeWorkbookHolder.getFile() == null) { if (writeWorkbookHolder.getFile() == null) {
return; return;
} }
FileOutputStream fileOutputStream = null; try (POIFSFileSystem fileSystem = openFileSystemAndEncrypt(writeWorkbookHolder.getFile());
POIFSFileSystem fileSystem = null; FileOutputStream fileOutputStream = new FileOutputStream(writeWorkbookHolder.getFile())) {
try {
fileSystem = openFileSystemAndEncrypt(writeWorkbookHolder.getFile());
fileOutputStream = new FileOutputStream(writeWorkbookHolder.getFile());
fileSystem.writeFilesystem(fileOutputStream); fileSystem.writeFilesystem(fileOutputStream);
} finally {
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (fileSystem != null) {
fileSystem.close();
}
} }
} }
@ -487,15 +483,9 @@ public class WriteContextImpl implements WriteContext {
POIFSFileSystem fileSystem = new POIFSFileSystem(); POIFSFileSystem fileSystem = new POIFSFileSystem();
Encryptor encryptor = new EncryptionInfo(EncryptionMode.standard).getEncryptor(); Encryptor encryptor = new EncryptionInfo(EncryptionMode.standard).getEncryptor();
encryptor.confirmPassword(writeWorkbookHolder.getPassword()); encryptor.confirmPassword(writeWorkbookHolder.getPassword());
OPCPackage opcPackage = null; try (OPCPackage opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE);
try { OutputStream outputStream = encryptor.getDataStream(fileSystem)) {
opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE);
OutputStream outputStream = encryptor.getDataStream(fileSystem);
opcPackage.save(outputStream); opcPackage.save(outputStream);
} finally {
if (opcPackage != null) {
opcPackage.close();
}
} }
return fileSystem; return fileSystem;
} }

26
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();
}

29
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();
}
}

29
src/main/java/com/alibaba/excel/converters/AutoConverter.java

@ -1,36 +1,9 @@
package com.alibaba.excel.converters; 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. * An empty converter.It's automatically converted by type.
* *
* @author Jiaju Zhuang * @author Jiaju Zhuang
*/ */
public class AutoConverter implements Converter { public class AutoConverter implements Converter<Object> {
@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;
}
} }

73
src/main/java/com/alibaba/excel/converters/Converter.java

@ -1,15 +1,16 @@
package com.alibaba.excel.converters; package com.alibaba.excel.converters;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
* Convert between Java objects and excel objects * Convert between Java objects and excel objects
* *
* @author Dan Zheng
* @param <T> * @param <T>
* @author Dan Zheng
*/ */
public interface Converter<T> { public interface Converter<T> {
@ -18,44 +19,68 @@ public interface Converter<T> {
* *
* @return Support for Java class * @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 * Back to object enum in excel
* *
* @return Support for {@link CellDataTypeEnum} * @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(ReadCellData<?> 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 * Convert excel objects to Java objects
* *
* @param cellData * @param context read converter context
* Excel cell data.NotNull.
* @param contentProperty
* Content property.Nullable.
* @param globalConfiguration
* Global configuration.NotNull.
* @return Data to put into a Java object * @return Data to put into a Java object
* @throws Exception * @throws Exception Exception.
* Exception. */
default T convertToJavaData(ReadConverterContext<?> context) throws Exception {
return convertToJavaData(context.getReadCellData(), context.getContentProperty(),
context.getAnalysisContext().currentReadHolder().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, default WriteCellData<?> convertToExcelData(T value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws Exception; GlobalConfiguration globalConfiguration) throws Exception {
throw new UnsupportedOperationException("The current operation is not supported by the current converter.");
}
/** /**
* Convert Java objects to excel objects * Convert Java objects to excel objects
* *
* @param value * @param context write context
* Java Data.NotNull.
* @param contentProperty
* Content property.Nullable.
* @param globalConfiguration
* Global configuration.NotNull.
* @return Data to put into a Excel * @return Data to put into a Excel
* @throws Exception * @throws Exception Exception.
* Exception.
*/ */
CellData convertToExcelData(T value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) default WriteCellData<?> convertToExcelData(WriteConverterContext<T> context) throws Exception {
throws Exception; return convertToExcelData(context.getValue(), context.getContentProperty(),
context.getWriteContext().currentWriteHolder().globalConfiguration());
}
} }

14
src/main/java/com/alibaba/excel/converters/ConverterKeyBuild.java

@ -1,9 +1,9 @@
package com.alibaba.excel.converters; package com.alibaba.excel.converters;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import com.alibaba.excel.enums.CellDataTypeEnum; 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. * 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 { public class ConverterKeyBuild {
private static final Map<String, String> BOXING_MAP = new HashMap<String, String>(16); private static final Map<String, String> BOXING_MAP = MapUtils.newHashMap();
static { static {
BOXING_MAP.put(int.class.getName(), Integer.class.getName()); 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()); 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 className = clazz.getName();
String boxingClassName = BOXING_MAP.get(clazz.getName()); String boxingClassName = BOXING_MAP.get(clazz.getName());
if (boxingClassName == null) { if (boxingClassName == null) {
@ -34,7 +34,11 @@ public class ConverterKeyBuild {
return boxingClassName; return boxingClassName;
} }
public static String buildKey(Class clazz, CellDataTypeEnum cellDataTypeEnum) { public static String buildKey(Class<?> clazz, CellDataTypeEnum cellDataTypeEnum) {
return buildKey(clazz) + "-" + cellDataTypeEnum.toString(); String key = buildKey(clazz);
if (cellDataTypeEnum == null) {
return key;
}
return key + "-" + cellDataTypeEnum;
} }
} }

40
src/main/java/com/alibaba/excel/converters/DefaultConverterLoader.java

@ -1,6 +1,5 @@
package com.alibaba.excel.converters; package com.alibaba.excel.converters;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import com.alibaba.excel.converters.bigdecimal.BigDecimalBooleanConverter; 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.ByteBooleanConverter;
import com.alibaba.excel.converters.byteconverter.ByteNumberConverter; import com.alibaba.excel.converters.byteconverter.ByteNumberConverter;
import com.alibaba.excel.converters.byteconverter.ByteStringConverter; 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.DateNumberConverter;
import com.alibaba.excel.converters.date.DateStringConverter; import com.alibaba.excel.converters.date.DateStringConverter;
import com.alibaba.excel.converters.doubleconverter.DoubleBooleanConverter; 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.StringNumberConverter;
import com.alibaba.excel.converters.string.StringStringConverter; import com.alibaba.excel.converters.string.StringStringConverter;
import com.alibaba.excel.converters.url.UrlImageConverter; import com.alibaba.excel.converters.url.UrlImageConverter;
import com.alibaba.excel.util.MapUtils;
/** /**
* Load default handler * Load default handler
@ -45,8 +46,8 @@ import com.alibaba.excel.converters.url.UrlImageConverter;
* @author Jiaju Zhuang * @author Jiaju Zhuang
*/ */
public class DefaultConverterLoader { public class DefaultConverterLoader {
private static Map<String, Converter> defaultWriteConverter; private static Map<String, Converter<?>> defaultWriteConverter;
private static Map<String, Converter> allConverter; private static Map<String, Converter<?>> allConverter;
static { static {
initDefaultWriteConverter(); initDefaultWriteConverter();
@ -54,7 +55,7 @@ public class DefaultConverterLoader {
} }
private static void initAllConverter() { private static void initAllConverter() {
allConverter = new HashMap<String, Converter>(64); allConverter = MapUtils.newHashMapWithExpectedSize(40);
putAllConverter(new BigDecimalBooleanConverter()); putAllConverter(new BigDecimalBooleanConverter());
putAllConverter(new BigDecimalNumberConverter()); putAllConverter(new BigDecimalNumberConverter());
putAllConverter(new BigDecimalStringConverter()); putAllConverter(new BigDecimalStringConverter());
@ -97,11 +98,11 @@ public class DefaultConverterLoader {
} }
private static void initDefaultWriteConverter() { private static void initDefaultWriteConverter() {
defaultWriteConverter = new HashMap<String, Converter>(32); defaultWriteConverter = MapUtils.newHashMapWithExpectedSize(40);
putWriteConverter(new BigDecimalNumberConverter()); putWriteConverter(new BigDecimalNumberConverter());
putWriteConverter(new BooleanBooleanConverter()); putWriteConverter(new BooleanBooleanConverter());
putWriteConverter(new ByteNumberConverter()); putWriteConverter(new ByteNumberConverter());
putWriteConverter(new DateStringConverter()); putWriteConverter(new DateDateConverter());
putWriteConverter(new DoubleNumberConverter()); putWriteConverter(new DoubleNumberConverter());
putWriteConverter(new FloatNumberConverter()); putWriteConverter(new FloatNumberConverter());
putWriteConverter(new IntegerNumberConverter()); putWriteConverter(new IntegerNumberConverter());
@ -113,6 +114,18 @@ public class DefaultConverterLoader {
putWriteConverter(new ByteArrayImageConverter()); putWriteConverter(new ByteArrayImageConverter());
putWriteConverter(new BoxingByteArrayImageConverter()); putWriteConverter(new BoxingByteArrayImageConverter());
putWriteConverter(new UrlImageConverter()); 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());
} }
/** /**
@ -120,20 +133,25 @@ public class DefaultConverterLoader {
* *
* @return * @return
*/ */
public static Map<String, Converter> loadDefaultWriteConverter() { public static Map<String, Converter<?>> loadDefaultWriteConverter() {
return defaultWriteConverter; return defaultWriteConverter;
} }
private static void putWriteConverter(Converter converter) { private static void putWriteConverter(Converter<?> converter) {
defaultWriteConverter.put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey()), converter); 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 * Load default read converter
* *
* @return * @return
*/ */
public static Map<String, Converter> loadDefaultReadConverter() { public static Map<String, Converter<?>> loadDefaultReadConverter() {
return loadAllConverter(); return loadAllConverter();
} }
@ -142,11 +160,11 @@ public class DefaultConverterLoader {
* *
* @return * @return
*/ */
public static Map<String, Converter> loadAllConverter() { public static Map<String, Converter<?>> loadAllConverter() {
return allConverter; return allConverter;
} }
private static void putAllConverter(Converter converter) { private static void putAllConverter(Converter<?> converter) {
allConverter.put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey(), converter.supportExcelTypeKey()), allConverter.put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey(), converter.supportExcelTypeKey()),
converter); converter);
} }

10
src/main/java/com/alibaba/excel/converters/NullableObjectConverter.java

@ -0,0 +1,10 @@
package com.alibaba.excel.converters;
/**
* When implementing <code>convertToExcelData</code> method, pay attention to the reference <code>value</code> may be
* null
*
* @author JiaJu Zhuang
**/
public interface NullableObjectConverter<T> extends Converter<T> {
}

30
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<T> {
/**
* Excel cell data.NotNull.
*/
private ReadCellData<T> readCellData;
/**
* Content property.Nullable.
*/
private ExcelContentProperty contentProperty;
/**
* context.NotNull.
*/
private AnalysisContext analysisContext;
}

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

@ -0,0 +1,32 @@
package com.alibaba.excel.converters;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* write converter context
*
* @author Jiaju Zhuang
*/
@Data
@AllArgsConstructor
public class WriteConverterContext<T> {
/**
* Java Data.NotNull.
*/
private T value;
/**
* Content property.Nullable.
*/
private ExcelContentProperty contentProperty;
/**
* write context
*/
private WriteContext writeContext;
}

13
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -16,7 +17,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class BigDecimalBooleanConverter implements Converter<BigDecimal> { public class BigDecimalBooleanConverter implements Converter<BigDecimal> {
@Override @Override
public Class supportJavaTypeKey() { public Class<BigDecimal> supportJavaTypeKey() {
return BigDecimal.class; return BigDecimal.class;
} }
@ -26,7 +27,7 @@ public class BigDecimalBooleanConverter implements Converter<BigDecimal> {
} }
@Override @Override
public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public BigDecimal convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (cellData.getBooleanValue()) { if (cellData.getBooleanValue()) {
return BigDecimal.ONE; return BigDecimal.ONE;
@ -35,12 +36,12 @@ public class BigDecimalBooleanConverter implements Converter<BigDecimal> {
} }
@Override @Override
public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (BigDecimal.ONE.equals(value)) { 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);
} }
} }

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

@ -4,9 +4,11 @@ import java.math.BigDecimal;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
/** /**
* BigDecimal and number converter * BigDecimal and number converter
@ -16,7 +18,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class BigDecimalNumberConverter implements Converter<BigDecimal> { public class BigDecimalNumberConverter implements Converter<BigDecimal> {
@Override @Override
public Class supportJavaTypeKey() { public Class<BigDecimal> supportJavaTypeKey() {
return BigDecimal.class; return BigDecimal.class;
} }
@ -26,14 +28,14 @@ public class BigDecimalNumberConverter implements Converter<BigDecimal> {
} }
@Override @Override
public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public BigDecimal convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return cellData.getNumberValue(); return cellData.getNumberValue();
} }
@Override @Override
public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return new CellData(value); return NumberUtils.formatToCellData(value, contentProperty);
} }
} }

11
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils; import com.alibaba.excel.util.NumberUtils;
@ -18,7 +19,7 @@ import com.alibaba.excel.util.NumberUtils;
public class BigDecimalStringConverter implements Converter<BigDecimal> { public class BigDecimalStringConverter implements Converter<BigDecimal> {
@Override @Override
public Class supportJavaTypeKey() { public Class<BigDecimal> supportJavaTypeKey() {
return BigDecimal.class; return BigDecimal.class;
} }
@ -28,14 +29,14 @@ public class BigDecimalStringConverter implements Converter<BigDecimal> {
} }
@Override @Override
public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public BigDecimal convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException { GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseBigDecimal(cellData.getStringValue(), contentProperty); return NumberUtils.parseBigDecimal(cellData.getStringValue(), contentProperty);
} }
@Override @Override
public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return NumberUtils.formatToCellData(value, contentProperty); return NumberUtils.formatToCellDataString(value, contentProperty);
} }
} }

11
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -14,7 +15,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class BooleanBooleanConverter implements Converter<Boolean> { public class BooleanBooleanConverter implements Converter<Boolean> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Boolean.class; return Boolean.class;
} }
@ -24,15 +25,15 @@ public class BooleanBooleanConverter implements Converter<Boolean> {
} }
@Override @Override
public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Boolean convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return cellData.getBooleanValue(); return cellData.getBooleanValue();
} }
@Override @Override
public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Boolean value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return new CellData(value); return new WriteCellData<>(value);
} }
} }

13
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -15,7 +16,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
*/ */
public class BooleanNumberConverter implements Converter<Boolean> { public class BooleanNumberConverter implements Converter<Boolean> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Boolean.class; return Boolean.class;
} }
@ -25,7 +26,7 @@ public class BooleanNumberConverter implements Converter<Boolean> {
} }
@Override @Override
public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Boolean convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (BigDecimal.ONE.compareTo(cellData.getNumberValue()) == 0) { if (BigDecimal.ONE.compareTo(cellData.getNumberValue()) == 0) {
return Boolean.TRUE; return Boolean.TRUE;
@ -34,12 +35,12 @@ public class BooleanNumberConverter implements Converter<Boolean> {
} }
@Override @Override
public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Boolean value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (value) { if (value) {
return new CellData(BigDecimal.ONE); return new WriteCellData<>(BigDecimal.ONE);
} }
return new CellData(BigDecimal.ZERO); return new WriteCellData<>(BigDecimal.ZERO);
} }
} }

11
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -14,7 +15,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class BooleanStringConverter implements Converter<Boolean> { public class BooleanStringConverter implements Converter<Boolean> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Boolean.class; return Boolean.class;
} }
@ -24,15 +25,15 @@ public class BooleanStringConverter implements Converter<Boolean> {
} }
@Override @Override
public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Boolean convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return Boolean.valueOf(cellData.getStringValue()); return Boolean.valueOf(cellData.getStringValue());
} }
@Override @Override
public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Boolean value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return new CellData(value.toString()); return new WriteCellData<>(value.toString());
} }
} }

20
src/main/java/com/alibaba/excel/converters/bytearray/BoxingByteArrayImageConverter.java

@ -1,9 +1,8 @@
package com.alibaba.excel.converters.bytearray; package com.alibaba.excel.converters.bytearray;
import com.alibaba.excel.converters.Converter; 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.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.metadata.property.ExcelContentProperty;
/** /**
@ -13,29 +12,18 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
*/ */
public class BoxingByteArrayImageConverter implements Converter<Byte[]> { public class BoxingByteArrayImageConverter implements Converter<Byte[]> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Byte[].class; return Byte[].class;
} }
@Override @Override
public CellDataTypeEnum supportExcelTypeKey() { public WriteCellData<?> convertToExcelData(Byte[] value, ExcelContentProperty contentProperty,
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,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
byte[] byteValue = new byte[value.length]; byte[] byteValue = new byte[value.length];
for (int i = 0; i < value.length; i++) { for (int i = 0; i < value.length; i++) {
byteValue[i] = value[i]; byteValue[i] = value[i];
} }
return new CellData(byteValue); return new WriteCellData<>(byteValue);
} }
} }

21
src/main/java/com/alibaba/excel/converters/bytearray/ByteArrayImageConverter.java

@ -1,9 +1,8 @@
package com.alibaba.excel.converters.bytearray; package com.alibaba.excel.converters.bytearray;
import com.alibaba.excel.converters.Converter; 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.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.metadata.property.ExcelContentProperty;
/** /**
@ -12,26 +11,16 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
* @author Jiaju Zhuang * @author Jiaju Zhuang
*/ */
public class ByteArrayImageConverter implements Converter<byte[]> { public class ByteArrayImageConverter implements Converter<byte[]> {
@Override
public Class supportJavaTypeKey() {
return byte[].class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.IMAGE;
}
@Override @Override
public byte[] convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Class<byte[]> supportJavaTypeKey() {
GlobalConfiguration globalConfiguration) { return byte[].class;
throw new UnsupportedOperationException("Cannot convert images to byte arrays");
} }
@Override @Override
public CellData convertToExcelData(byte[] value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(byte[] value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return new CellData(value); return new WriteCellData<>(value);
} }
} }

13
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -16,7 +17,7 @@ public class ByteBooleanConverter implements Converter<Byte> {
private static final Byte ZERO = (byte)0; private static final Byte ZERO = (byte)0;
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Byte.class; return Byte.class;
} }
@ -26,7 +27,7 @@ public class ByteBooleanConverter implements Converter<Byte> {
} }
@Override @Override
public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Byte convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (cellData.getBooleanValue()) { if (cellData.getBooleanValue()) {
return ONE; return ONE;
@ -35,12 +36,12 @@ public class ByteBooleanConverter implements Converter<Byte> {
} }
@Override @Override
public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Byte value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (ONE.equals(value)) { if (ONE.equals(value)) {
return new CellData(Boolean.TRUE); return new WriteCellData<>(Boolean.TRUE);
} }
return new CellData(Boolean.FALSE); return new WriteCellData<>(Boolean.FALSE);
} }
} }

14
src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java

@ -1,12 +1,12 @@
package com.alibaba.excel.converters.byteconverter; package com.alibaba.excel.converters.byteconverter;
import java.math.BigDecimal;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
/** /**
* Byte and number converter * Byte and number converter
@ -16,7 +16,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class ByteNumberConverter implements Converter<Byte> { public class ByteNumberConverter implements Converter<Byte> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Byte.class; return Byte.class;
} }
@ -26,15 +26,15 @@ public class ByteNumberConverter implements Converter<Byte> {
} }
@Override @Override
public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Byte convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return cellData.getNumberValue().byteValue(); return cellData.getNumberValue().byteValue();
} }
@Override @Override
public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Byte value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return new CellData(new BigDecimal(Byte.toString(value))); return NumberUtils.formatToCellData(value, contentProperty);
} }
} }

11
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils; import com.alibaba.excel.util.NumberUtils;
@ -17,7 +18,7 @@ import com.alibaba.excel.util.NumberUtils;
public class ByteStringConverter implements Converter<Byte> { public class ByteStringConverter implements Converter<Byte> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Byte.class; return Byte.class;
} }
@ -27,15 +28,15 @@ public class ByteStringConverter implements Converter<Byte> {
} }
@Override @Override
public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Byte convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException { GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseByte(cellData.getStringValue(), contentProperty); return NumberUtils.parseByte(cellData.getStringValue(), contentProperty);
} }
@Override @Override
public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Byte value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return NumberUtils.formatToCellData(value, contentProperty); return NumberUtils.formatToCellDataString(value, contentProperty);
} }
} }

34
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.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;
/**
* Date and date converter
*
* @author Jiaju Zhuang
*/
public class DateDateConverter implements Converter<Date> {
@Override
public Class<Date> supportJavaTypeKey() {
return Date.class;
}
@Override
public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws Exception {
WriteCellData<?> cellData = new WriteCellData<>(value);
String format = null;
if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) {
format = contentProperty.getDateTimeFormatProperty().getFormat();
}
WorkBookUtil.fillDataFormat(cellData, format, DateUtils.defaultDateFormat);
return cellData;
}
}

17
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.math.BigDecimal;
import java.util.Date; import java.util.Date;
import org.apache.poi.ss.usermodel.DateUtil;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import org.apache.poi.ss.usermodel.DateUtil;
/** /**
* Date and number converter * Date and number converter
* *
@ -19,7 +20,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class DateNumberConverter implements Converter<Date> { public class DateNumberConverter implements Converter<Date> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Date.class; return Date.class;
} }
@ -29,7 +30,7 @@ public class DateNumberConverter implements Converter<Date> {
} }
@Override @Override
public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
return DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(), return DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(),
@ -41,13 +42,13 @@ public class DateNumberConverter implements Converter<Date> {
} }
@Override @Override
public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
return new CellData( return new WriteCellData<>(
BigDecimal.valueOf(DateUtil.getExcelDate(value, globalConfiguration.getUse1904windowing()))); BigDecimal.valueOf(DateUtil.getExcelDate(value, globalConfiguration.getUse1904windowing())));
} else { } else {
return new CellData(BigDecimal.valueOf( return new WriteCellData<>(BigDecimal.valueOf(
DateUtil.getExcelDate(value, contentProperty.getDateTimeFormatProperty().getUse1904windowing()))); DateUtil.getExcelDate(value, contentProperty.getDateTimeFormatProperty().getUse1904windowing())));
} }
} }

13
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.DateUtils; import com.alibaba.excel.util.DateUtils;
@ -17,7 +18,7 @@ import com.alibaba.excel.util.DateUtils;
*/ */
public class DateStringConverter implements Converter<Date> { public class DateStringConverter implements Converter<Date> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Date.class; return Date.class;
} }
@ -27,7 +28,7 @@ public class DateStringConverter implements Converter<Date> {
} }
@Override @Override
public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException { GlobalConfiguration globalConfiguration) throws ParseException {
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
return DateUtils.parseDate(cellData.getStringValue(), null); return DateUtils.parseDate(cellData.getStringValue(), null);
@ -38,12 +39,12 @@ public class DateStringConverter implements Converter<Date> {
} }
@Override @Override
public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
return new CellData(DateUtils.format(value, null)); return new WriteCellData<>(DateUtils.format(value, null));
} else { } else {
return new CellData(DateUtils.format(value, contentProperty.getDateTimeFormatProperty().getFormat())); return new WriteCellData<>(DateUtils.format(value, contentProperty.getDateTimeFormatProperty().getFormat()));
} }
} }
} }

13
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -16,7 +17,7 @@ public class DoubleBooleanConverter implements Converter<Double> {
private static final Double ZERO = 0.0; private static final Double ZERO = 0.0;
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Double.class; return Double.class;
} }
@ -26,7 +27,7 @@ public class DoubleBooleanConverter implements Converter<Double> {
} }
@Override @Override
public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Double convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (cellData.getBooleanValue()) { if (cellData.getBooleanValue()) {
return ONE; return ONE;
@ -35,12 +36,12 @@ public class DoubleBooleanConverter implements Converter<Double> {
} }
@Override @Override
public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Double value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (ONE.equals(value)) { if (ONE.equals(value)) {
return new CellData(Boolean.TRUE); return new WriteCellData<>(Boolean.TRUE);
} }
return new CellData(Boolean.FALSE); return new WriteCellData<>(Boolean.FALSE);
} }
} }

15
src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleNumberConverter.java

@ -1,12 +1,12 @@
package com.alibaba.excel.converters.doubleconverter; package com.alibaba.excel.converters.doubleconverter;
import java.math.BigDecimal;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
/** /**
* Double and number converter * Double and number converter
@ -16,7 +16,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class DoubleNumberConverter implements Converter<Double> { public class DoubleNumberConverter implements Converter<Double> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Double.class; return Double.class;
} }
@ -26,15 +26,14 @@ public class DoubleNumberConverter implements Converter<Double> {
} }
@Override @Override
public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Double convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return cellData.getNumberValue().doubleValue(); return cellData.getNumberValue().doubleValue();
} }
@Override @Override
public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Double value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return new CellData(BigDecimal.valueOf(value)); return NumberUtils.formatToCellData(value, contentProperty);
} }
} }

11
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils; import com.alibaba.excel.util.NumberUtils;
@ -17,7 +18,7 @@ import com.alibaba.excel.util.NumberUtils;
public class DoubleStringConverter implements Converter<Double> { public class DoubleStringConverter implements Converter<Double> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Double.class; return Double.class;
} }
@ -27,14 +28,14 @@ public class DoubleStringConverter implements Converter<Double> {
} }
@Override @Override
public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Double convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException { GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseDouble(cellData.getStringValue(), contentProperty); return NumberUtils.parseDouble(cellData.getStringValue(), contentProperty);
} }
@Override @Override
public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Double value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return NumberUtils.formatToCellData(value, contentProperty); return NumberUtils.formatToCellDataString(value, contentProperty);
} }
} }

21
src/main/java/com/alibaba/excel/converters/file/FileImageConverter.java

@ -4,9 +4,8 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import com.alibaba.excel.converters.Converter; 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.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.util.FileUtils;
@ -17,25 +16,13 @@ import com.alibaba.excel.util.FileUtils;
*/ */
public class FileImageConverter implements Converter<File> { public class FileImageConverter implements Converter<File> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return File.class; return File.class;
} }
@Override @Override
public CellDataTypeEnum supportExcelTypeKey() { public WriteCellData<?> convertToExcelData(File value, ExcelContentProperty contentProperty,
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,
GlobalConfiguration globalConfiguration) throws IOException { GlobalConfiguration globalConfiguration) throws IOException {
return new CellData(FileUtils.readFileToByteArray(value)); return new WriteCellData<>(FileUtils.readFileToByteArray(value));
} }
} }

13
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -16,7 +17,7 @@ public class FloatBooleanConverter implements Converter<Float> {
private static final Float ZERO = (float)0.0; private static final Float ZERO = (float)0.0;
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Float.class; return Float.class;
} }
@ -26,7 +27,7 @@ public class FloatBooleanConverter implements Converter<Float> {
} }
@Override @Override
public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Float convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (cellData.getBooleanValue()) { if (cellData.getBooleanValue()) {
return ONE; return ONE;
@ -35,12 +36,12 @@ public class FloatBooleanConverter implements Converter<Float> {
} }
@Override @Override
public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Float value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (ONE.equals(value)) { if (ONE.equals(value)) {
return new CellData(Boolean.TRUE); return new WriteCellData<>(Boolean.TRUE);
} }
return new CellData(Boolean.FALSE); return new WriteCellData<>(Boolean.FALSE);
} }
} }

17
src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java

@ -1,12 +1,13 @@
package com.alibaba.excel.converters.floatconverter; package com.alibaba.excel.converters.floatconverter;
import java.math.BigDecimal;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
/** /**
* Float and number converter * Float and number converter
@ -16,7 +17,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class FloatNumberConverter implements Converter<Float> { public class FloatNumberConverter implements Converter<Float> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Float.class; return Float.class;
} }
@ -26,15 +27,13 @@ public class FloatNumberConverter implements Converter<Float> {
} }
@Override @Override
public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Float convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return cellData.getNumberValue().floatValue(); return cellData.getNumberValue().floatValue();
} }
@Override @Override
public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(WriteConverterContext<Float> context) {
GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty());
return new CellData(new BigDecimal(Float.toString(value)));
} }
} }

11
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils; import com.alibaba.excel.util.NumberUtils;
@ -17,7 +18,7 @@ import com.alibaba.excel.util.NumberUtils;
public class FloatStringConverter implements Converter<Float> { public class FloatStringConverter implements Converter<Float> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Float.class; return Float.class;
} }
@ -27,14 +28,14 @@ public class FloatStringConverter implements Converter<Float> {
} }
@Override @Override
public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Float convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException { GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseFloat(cellData.getStringValue(), contentProperty); return NumberUtils.parseFloat(cellData.getStringValue(), contentProperty);
} }
@Override @Override
public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Float value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return NumberUtils.formatToCellData(value, contentProperty); return NumberUtils.formatToCellDataString(value, contentProperty);
} }
} }

20
src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java

@ -4,9 +4,8 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import com.alibaba.excel.converters.Converter; 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.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.IoUtils; import com.alibaba.excel.util.IoUtils;
@ -17,25 +16,14 @@ import com.alibaba.excel.util.IoUtils;
*/ */
public class InputStreamImageConverter implements Converter<InputStream> { public class InputStreamImageConverter implements Converter<InputStream> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return InputStream.class; return InputStream.class;
} }
@Override @Override
public CellDataTypeEnum supportExcelTypeKey() { public WriteCellData<?> convertToExcelData(InputStream value, ExcelContentProperty contentProperty,
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,
GlobalConfiguration globalConfiguration) throws IOException { GlobalConfiguration globalConfiguration) throws IOException {
return new CellData(IoUtils.toByteArray(value)); return new WriteCellData<>(IoUtils.toByteArray(value));
} }
} }

13
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -16,7 +17,7 @@ public class IntegerBooleanConverter implements Converter<Integer> {
private static final Integer ZERO = 0; private static final Integer ZERO = 0;
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Integer.class; return Integer.class;
} }
@ -26,7 +27,7 @@ public class IntegerBooleanConverter implements Converter<Integer> {
} }
@Override @Override
public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (cellData.getBooleanValue()) { if (cellData.getBooleanValue()) {
return ONE; return ONE;
@ -35,12 +36,12 @@ public class IntegerBooleanConverter implements Converter<Integer> {
} }
@Override @Override
public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (ONE.equals(value)) { if (ONE.equals(value)) {
return new CellData(Boolean.TRUE); return new WriteCellData<>(Boolean.TRUE);
} }
return new CellData(Boolean.FALSE); return new WriteCellData<>(Boolean.FALSE);
} }
} }

16
src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java

@ -1,12 +1,13 @@
package com.alibaba.excel.converters.integer; package com.alibaba.excel.converters.integer;
import java.math.BigDecimal;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
/** /**
* Integer and number converter * Integer and number converter
@ -16,7 +17,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class IntegerNumberConverter implements Converter<Integer> { public class IntegerNumberConverter implements Converter<Integer> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Integer.class; return Integer.class;
} }
@ -26,15 +27,14 @@ public class IntegerNumberConverter implements Converter<Integer> {
} }
@Override @Override
public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return cellData.getNumberValue().intValue(); return cellData.getNumberValue().intValue();
} }
@Override @Override
public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(WriteConverterContext<Integer> context) {
GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty());
return new CellData(new BigDecimal(Integer.toString(value)));
} }
} }

11
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils; import com.alibaba.excel.util.NumberUtils;
@ -17,7 +18,7 @@ import com.alibaba.excel.util.NumberUtils;
public class IntegerStringConverter implements Converter<Integer> { public class IntegerStringConverter implements Converter<Integer> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Integer.class; return Integer.class;
} }
@ -27,14 +28,14 @@ public class IntegerStringConverter implements Converter<Integer> {
} }
@Override @Override
public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException { GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseInteger(cellData.getStringValue(), contentProperty); return NumberUtils.parseInteger(cellData.getStringValue(), contentProperty);
} }
@Override @Override
public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return NumberUtils.formatToCellData(value, contentProperty); return NumberUtils.formatToCellDataString(value, contentProperty);
} }
} }

13
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -16,7 +17,7 @@ public class LongBooleanConverter implements Converter<Long> {
private static final Long ZERO = 0L; private static final Long ZERO = 0L;
@Override @Override
public Class supportJavaTypeKey() { public Class<Long> supportJavaTypeKey() {
return Long.class; return Long.class;
} }
@ -26,7 +27,7 @@ public class LongBooleanConverter implements Converter<Long> {
} }
@Override @Override
public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (cellData.getBooleanValue()) { if (cellData.getBooleanValue()) {
return ONE; return ONE;
@ -35,12 +36,12 @@ public class LongBooleanConverter implements Converter<Long> {
} }
@Override @Override
public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Long value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (ONE.equals(value)) { if (ONE.equals(value)) {
return new CellData(Boolean.TRUE); return new WriteCellData<>(Boolean.TRUE);
} }
return new CellData(Boolean.FALSE); return new WriteCellData<>(Boolean.FALSE);
} }
} }

16
src/main/java/com/alibaba/excel/converters/longconverter/LongNumberConverter.java

@ -1,12 +1,13 @@
package com.alibaba.excel.converters.longconverter; package com.alibaba.excel.converters.longconverter;
import java.math.BigDecimal;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
/** /**
* Long and number converter * Long and number converter
@ -16,7 +17,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class LongNumberConverter implements Converter<Long> { public class LongNumberConverter implements Converter<Long> {
@Override @Override
public Class supportJavaTypeKey() { public Class<Long> supportJavaTypeKey() {
return Long.class; return Long.class;
} }
@ -26,15 +27,14 @@ public class LongNumberConverter implements Converter<Long> {
} }
@Override @Override
public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return cellData.getNumberValue().longValue(); return cellData.getNumberValue().longValue();
} }
@Override @Override
public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(WriteConverterContext<Long> context) {
GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty());
return new CellData(BigDecimal.valueOf(value));
} }
} }

11
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils; import com.alibaba.excel.util.NumberUtils;
@ -17,7 +18,7 @@ import com.alibaba.excel.util.NumberUtils;
public class LongStringConverter implements Converter<Long> { public class LongStringConverter implements Converter<Long> {
@Override @Override
public Class supportJavaTypeKey() { public Class<Long> supportJavaTypeKey() {
return Long.class; return Long.class;
} }
@ -27,14 +28,14 @@ public class LongStringConverter implements Converter<Long> {
} }
@Override @Override
public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException { GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseLong(cellData.getStringValue(), contentProperty); return NumberUtils.parseLong(cellData.getStringValue(), contentProperty);
} }
@Override @Override
public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Long value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return NumberUtils.formatToCellData(value, contentProperty); return NumberUtils.formatToCellDataString(value, contentProperty);
} }
} }

13
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -16,7 +17,7 @@ public class ShortBooleanConverter implements Converter<Short> {
private static final Short ZERO = 0; private static final Short ZERO = 0;
@Override @Override
public Class supportJavaTypeKey() { public Class<Short> supportJavaTypeKey() {
return Short.class; return Short.class;
} }
@ -26,7 +27,7 @@ public class ShortBooleanConverter implements Converter<Short> {
} }
@Override @Override
public Short convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Short convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (cellData.getBooleanValue()) { if (cellData.getBooleanValue()) {
return ONE; return ONE;
@ -35,12 +36,12 @@ public class ShortBooleanConverter implements Converter<Short> {
} }
@Override @Override
public CellData convertToExcelData(Short value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Short value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
if (ONE.equals(value)) { if (ONE.equals(value)) {
return new CellData(Boolean.TRUE); return new WriteCellData<>(Boolean.TRUE);
} }
return new CellData(Boolean.FALSE); return new WriteCellData<>(Boolean.FALSE);
} }
} }

17
src/main/java/com/alibaba/excel/converters/shortconverter/ShortNumberConverter.java

@ -1,12 +1,13 @@
package com.alibaba.excel.converters.shortconverter; package com.alibaba.excel.converters.shortconverter;
import java.math.BigDecimal;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
/** /**
* Short and number converter * Short and number converter
@ -16,7 +17,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class ShortNumberConverter implements Converter<Short> { public class ShortNumberConverter implements Converter<Short> {
@Override @Override
public Class supportJavaTypeKey() { public Class<Short> supportJavaTypeKey() {
return Short.class; return Short.class;
} }
@ -26,15 +27,13 @@ public class ShortNumberConverter implements Converter<Short> {
} }
@Override @Override
public Short convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Short convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return cellData.getNumberValue().shortValue(); return cellData.getNumberValue().shortValue();
} }
@Override @Override
public CellData convertToExcelData(Short value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(WriteConverterContext<Short> context) {
GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty());
return new CellData(new BigDecimal(Short.toString(value)));
} }
} }

11
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils; import com.alibaba.excel.util.NumberUtils;
@ -17,7 +18,7 @@ import com.alibaba.excel.util.NumberUtils;
public class ShortStringConverter implements Converter<Short> { public class ShortStringConverter implements Converter<Short> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return Short.class; return Short.class;
} }
@ -27,14 +28,14 @@ public class ShortStringConverter implements Converter<Short> {
} }
@Override @Override
public Short convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public Short convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException { GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseShort(cellData.getStringValue(), contentProperty); return NumberUtils.parseShort(cellData.getStringValue(), contentProperty);
} }
@Override @Override
public CellData convertToExcelData(Short value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(Short value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return NumberUtils.formatToCellData(value, contentProperty); return NumberUtils.formatToCellDataString(value, contentProperty);
} }
} }

11
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -14,7 +15,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class StringBooleanConverter implements Converter<String> { public class StringBooleanConverter implements Converter<String> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return String.class; return String.class;
} }
@ -24,15 +25,15 @@ public class StringBooleanConverter implements Converter<String> {
} }
@Override @Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return cellData.getBooleanValue().toString(); return cellData.getBooleanValue().toString();
} }
@Override @Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return new CellData(Boolean.valueOf(value)); return new WriteCellData<>(Boolean.valueOf(value));
} }
} }

11
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -13,7 +14,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
*/ */
public class StringErrorConverter implements Converter<String> { public class StringErrorConverter implements Converter<String> {
@Override @Override
public Class supportJavaTypeKey() { public Class<String> supportJavaTypeKey() {
return String.class; return String.class;
} }
@ -23,15 +24,15 @@ public class StringErrorConverter implements Converter<String> {
} }
@Override @Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return cellData.getStringValue(); return cellData.getStringValue();
} }
@Override @Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return new CellData(CellDataTypeEnum.ERROR, value); return new WriteCellData<>(CellDataTypeEnum.ERROR, value);
} }
} }

20
src/main/java/com/alibaba/excel/converters/string/StringImageConverter.java

@ -4,9 +4,8 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import com.alibaba.excel.converters.Converter; 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.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.util.FileUtils;
@ -17,25 +16,14 @@ import com.alibaba.excel.util.FileUtils;
*/ */
public class StringImageConverter implements Converter<String> { public class StringImageConverter implements Converter<String> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return String.class; return String.class;
} }
@Override @Override
public CellDataTypeEnum supportExcelTypeKey() { public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
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,
GlobalConfiguration globalConfiguration) throws IOException { GlobalConfiguration globalConfiguration) throws IOException {
return new CellData(FileUtils.readFileToByteArray(new File(value))); return new WriteCellData<>(FileUtils.readFileToByteArray(new File(value)));
} }
} }

24
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 java.math.BigDecimal;
import org.apache.poi.ss.usermodel.DateUtil;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.DateUtils; import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.NumberDataFormatterUtils; import com.alibaba.excel.util.NumberDataFormatterUtils;
import com.alibaba.excel.util.NumberUtils; import com.alibaba.excel.util.NumberUtils;
import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.util.StringUtils;
import org.apache.poi.ss.usermodel.DateUtil;
/** /**
* String and number converter * String and number converter
* *
@ -22,7 +23,7 @@ import com.alibaba.excel.util.StringUtils;
public class StringNumberConverter implements Converter<String> { public class StringNumberConverter implements Converter<String> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return String.class; return String.class;
} }
@ -32,7 +33,7 @@ public class StringNumberConverter implements Converter<String> {
} }
@Override @Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
// If there are "DateTimeFormat", read as date // If there are "DateTimeFormat", read as date
if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) { if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) {
@ -46,17 +47,20 @@ public class StringNumberConverter implements Converter<String> {
return NumberUtils.format(cellData.getNumberValue(), contentProperty); return NumberUtils.format(cellData.getNumberValue(), contentProperty);
} }
// Excel defines formatting // Excel defines formatting
if (cellData.getDataFormat() != null && !StringUtils.isEmpty(cellData.getDataFormatString())) { boolean hasDataFormatData = cellData.getDataFormatData() != null
return NumberDataFormatterUtils.format(cellData.getNumberValue(), cellData.getDataFormat(), && cellData.getDataFormatData().getIndex() != null && !StringUtils.isEmpty(
cellData.getDataFormatString(), globalConfiguration); cellData.getDataFormatData().getFormat());
if (hasDataFormatData) {
return NumberDataFormatterUtils.format(cellData.getNumberValue(),
cellData.getDataFormatData().getIndex(), cellData.getDataFormatData().getFormat(), globalConfiguration);
} }
// Default conversion number // Default conversion number
return NumberUtils.format(cellData.getNumberValue(), contentProperty); return NumberUtils.format(cellData.getNumberValue(), contentProperty);
} }
@Override @Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return new CellData(new BigDecimal(value)); return new WriteCellData<>(new BigDecimal(value));
} }
} }

11
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.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration; 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.metadata.property.ExcelContentProperty;
/** /**
@ -13,7 +14,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
*/ */
public class StringStringConverter implements Converter<String> { public class StringStringConverter implements Converter<String> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return String.class; return String.class;
} }
@ -23,15 +24,15 @@ public class StringStringConverter implements Converter<String> {
} }
@Override @Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return cellData.getStringValue(); return cellData.getStringValue();
} }
@Override @Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) { GlobalConfiguration globalConfiguration) {
return new CellData(value); return new WriteCellData<>(value);
} }
} }

23
src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java

@ -6,47 +6,34 @@ import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import com.alibaba.excel.converters.Converter; 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.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.IoUtils; import com.alibaba.excel.util.IoUtils;
/** /**
* Url and image converter * Url and image converter
* *
* @since 2.1.1
* @author Jiaju Zhuang * @author Jiaju Zhuang
* @since 2.1.1
*/ */
public class UrlImageConverter implements Converter<URL> { public class UrlImageConverter implements Converter<URL> {
@Override @Override
public Class supportJavaTypeKey() { public Class<?> supportJavaTypeKey() {
return URL.class; return URL.class;
} }
@Override @Override
public CellDataTypeEnum supportExcelTypeKey() { public WriteCellData<?> convertToExcelData(URL value, ExcelContentProperty contentProperty,
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,
GlobalConfiguration globalConfiguration) throws IOException { GlobalConfiguration globalConfiguration) throws IOException {
InputStream inputStream = null; InputStream inputStream = null;
try { try {
URLConnection conn = value.openConnection(); URLConnection conn = value.openConnection();
conn.setConnectTimeout(1000); conn.setConnectTimeout(1000);
conn.setReadTimeout(5000); conn.setReadTimeout(5000);
inputStream = con.getInputStream(); inputStream = con.getInputStream();
byte[] bytes = IoUtils.toByteArray(inputStream); byte[] bytes = IoUtils.toByteArray(inputStream);
return new CellData(bytes); return new WriteCellData<>(bytes);
} finally { } finally {
if (inputStream != null) { if (inputStream != null) {
inputStream.close(); inputStream.close();

10
src/main/java/com/alibaba/excel/enums/CellDataTypeEnum.java

@ -37,11 +37,17 @@ public enum CellDataTypeEnum {
*/ */
ERROR, ERROR,
/** /**
* Images are currently supported only when writing * date. Support only when writing.
*/ */
IMAGE; DATE,
/**
* rich text string.Support only when writing.
*/
RICH_TEXT_STRING,
;
private static final Map<String, CellDataTypeEnum> TYPE_ROUTING_MAP = new HashMap<String, CellDataTypeEnum>(16); private static final Map<String, CellDataTypeEnum> TYPE_ROUTING_MAP = new HashMap<String, CellDataTypeEnum>(16);
static { static {
TYPE_ROUTING_MAP.put("s", STRING); TYPE_ROUTING_MAP.put("s", STRING);
TYPE_ROUTING_MAP.put("str", DIRECT_STRING); TYPE_ROUTING_MAP.put("str", DIRECT_STRING);

22
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,
;
}

8
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 * Receives the return of each piece of data parsed
* *
* @author jipengfei * @author jipengfei
* @deprecated Use directly {@link ReadListener}
*/ */
@Deprecated
public abstract class AbstractIgnoreExceptionReadListener<T> implements ReadListener<T> { public abstract class AbstractIgnoreExceptionReadListener<T> implements ReadListener<T> {
/** /**
@ -24,10 +26,8 @@ public abstract class AbstractIgnoreExceptionReadListener<T> implements ReadList
/** /**
* The current method is called when extra information is returned * The current method is called when extra information is returned
* *
* @param extra * @param extra extra information
* extra information * @param context analysis context
* @param context
* analysis context
*/ */
@Override @Override
public void extra(CellExtra extra, AnalysisContext context) {} public void extra(CellExtra extra, AnalysisContext context) {}

4
src/main/java/com/alibaba/excel/event/AnalysisEventListener.java

@ -3,8 +3,8 @@ package com.alibaba.excel.event;
import java.util.Map; import java.util.Map;
import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.CellExtra; import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener; import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ConverterUtils; import com.alibaba.excel.util.ConverterUtils;
@ -16,7 +16,7 @@ import com.alibaba.excel.util.ConverterUtils;
public abstract class AnalysisEventListener<T> implements ReadListener<T> { public abstract class AnalysisEventListener<T> implements ReadListener<T> {
@Override @Override
public void invokeHead(Map<Integer, CellData> headMap, AnalysisContext context) { public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
invokeHeadMap(ConverterUtils.convertToStringMap(headMap, context), context); invokeHeadMap(ConverterUtils.convertToStringMap(headMap, context), context);
} }

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

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

38
src/main/java/com/alibaba/excel/event/WriteHandler.java

@ -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);
}

38
src/main/java/com/alibaba/excel/exception/ExcelDataConvertException.java

@ -1,14 +1,17 @@
package com.alibaba.excel.exception; 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.metadata.property.ExcelContentProperty;
import com.alibaba.excel.write.builder.ExcelWriterBuilder; import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import lombok.Data;
/** /**
* Data convert exception * Data convert exception
* *
* @author Jiaju Zhuang * @author Jiaju Zhuang
*/ */
@Data
public class ExcelDataConvertException extends RuntimeException { public class ExcelDataConvertException extends RuntimeException {
/** /**
* NotNull. * NotNull.
@ -21,7 +24,7 @@ public class ExcelDataConvertException extends RuntimeException {
/** /**
* NotNull. * NotNull.
*/ */
private CellData cellData; private CellData<?> cellData;
/** /**
* Nullable.Only when the header is configured and when the class header is used is not null. * Nullable.Only when the header is configured and when the class header is used is not null.
* *
@ -47,35 +50,4 @@ public class ExcelDataConvertException extends RuntimeException {
this.excelContentProperty = excelContentProperty; 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;
}
} }

19
src/main/java/com/alibaba/excel/metadata/AbstractCell.java

@ -1,10 +1,13 @@
package com.alibaba.excel.metadata; package com.alibaba.excel.metadata;
import lombok.Data;
/** /**
* cell * cell
* *
* @author Jiaju Zhuang * @author Jiaju Zhuang
**/ **/
@Data
public class AbstractCell implements Cell { public class AbstractCell implements Cell {
/** /**
* Row index * Row index
@ -14,20 +17,4 @@ public class AbstractCell implements Cell {
* Column index * Column index
*/ */
private Integer columnIndex; 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;
}
} }

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

@ -1,16 +1,20 @@
package com.alibaba.excel.metadata; package com.alibaba.excel.metadata;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import lombok.Data;
import lombok.NoArgsConstructor;
/** /**
* Write/read holder * Write/read holder
* *
* @author Jiaju Zhuang * @author Jiaju Zhuang
*/ */
@Data
@NoArgsConstructor
public abstract class AbstractHolder implements ConfigurationHolder { public abstract class AbstractHolder implements ConfigurationHolder {
/** /**
* Record whether it's new or from cache * Record whether it's new or from cache
@ -23,7 +27,7 @@ public abstract class AbstractHolder implements ConfigurationHolder {
/** /**
* You can only choose one of the {@link AbstractHolder#head} and {@link AbstractHolder#clazz} * You can only choose one of the {@link AbstractHolder#head} and {@link AbstractHolder#clazz}
*/ */
private Class clazz; private Class<?> clazz;
/** /**
* Some global variables * Some global variables
*/ */
@ -34,7 +38,7 @@ public abstract class AbstractHolder implements ConfigurationHolder {
* <p> * <p>
* Write key: * Write key:
*/ */
private Map<String, Converter> converterMap; private Map<String, Converter<?>> converterMap;
public AbstractHolder(BasicParameter basicParameter, AbstractHolder prentAbstractHolder) { public AbstractHolder(BasicParameter basicParameter, AbstractHolder prentAbstractHolder) {
this.newInitialization = Boolean.TRUE; this.newInitialization = Boolean.TRUE;
@ -50,69 +54,34 @@ public abstract class AbstractHolder implements ConfigurationHolder {
} }
this.globalConfiguration = new GlobalConfiguration(); this.globalConfiguration = new GlobalConfiguration();
if (basicParameter.getAutoTrim() == null) { if (basicParameter.getAutoTrim() == null) {
if (prentAbstractHolder == null) { if (prentAbstractHolder != null) {
globalConfiguration.setAutoTrim(Boolean.TRUE);
} else {
globalConfiguration.setAutoTrim(prentAbstractHolder.getGlobalConfiguration().getAutoTrim()); globalConfiguration.setAutoTrim(prentAbstractHolder.getGlobalConfiguration().getAutoTrim());
} }
} else { } else {
globalConfiguration.setAutoTrim(basicParameter.getAutoTrim()); globalConfiguration.setAutoTrim(basicParameter.getAutoTrim());
} }
if (basicParameter.getLocale() == null) { if (basicParameter.getUse1904windowing() == null) {
if (prentAbstractHolder == null) { if (prentAbstractHolder != null) {
globalConfiguration.setLocale(Locale.getDefault()); globalConfiguration.setUse1904windowing(
} else { prentAbstractHolder.getGlobalConfiguration().getUse1904windowing());
globalConfiguration.setLocale(prentAbstractHolder.getGlobalConfiguration().getLocale());
} }
} else { } else {
globalConfiguration.setLocale(basicParameter.getLocale()); globalConfiguration.setUse1904windowing(basicParameter.getUse1904windowing());
}
}
public Boolean getNewInitialization() {
return newInitialization;
}
public void setNewInitialization(Boolean newInitialization) {
this.newInitialization = newInitialization;
}
public List<List<String>> getHead() {
return head;
} }
public void setHead(List<List<String>> head) { if (basicParameter.getLocale() == null) {
this.head = head; if (prentAbstractHolder != null) {
} globalConfiguration.setLocale(prentAbstractHolder.getGlobalConfiguration().getLocale());
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;
} }
} else {
public Map<String, Converter> getConverterMap() { globalConfiguration.setLocale(basicParameter.getLocale());
return converterMap;
} }
public void setConverterMap(Map<String, Converter> converterMap) {
this.converterMap = converterMap;
} }
@Override @Override
public Map<String, Converter> converterMap() { public Map<String, Converter<?>> converterMap() {
return getConverterMap(); return getConverterMap();
} }

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

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

40
src/main/java/com/alibaba/excel/metadata/BaseRowModel.java

@ -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<Integer, CellStyle> cellStyleMap = new HashMap<Integer, CellStyle>();
public void addStyle(Integer row, CellStyle cellStyle) {
cellStyleMap.put(row, cellStyle);
}
public CellStyle getStyle(Integer row) {
return cellStyleMap.get(row);
}
public Map<Integer, CellStyle> getCellStyleMap() {
return cellStyleMap;
}
public void setCellStyleMap(Map<Integer, CellStyle> cellStyleMap) {
this.cellStyleMap = cellStyleMap;
}
}

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

@ -5,11 +5,14 @@ import java.util.Locale;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
import lombok.Data;
/** /**
* Basic parameter * Basic parameter
* *
* @author Jiaju Zhuang * @author Jiaju Zhuang
**/ **/
@Data
public class BasicParameter { public class BasicParameter {
/** /**
* You can only choose one of the {@link BasicParameter#head} and {@link BasicParameter#clazz} * 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} * 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 * Custom type conversions override the default
*/ */
private List<Converter> customConverterList; private List<Converter<?>> customConverterList;
/** /**
* Automatic trim includes sheet name and content * Automatic trim includes sheet name and content
*/ */
@ -47,60 +50,4 @@ public class BasicParameter {
* default is false * default is false
*/ */
private Boolean useScientificFormat; private Boolean useScientificFormat;
public List<List<String>> getHead() {
return head;
}
public void setHead(List<List<String>> head) {
this.head = head;
}
public Class getClazz() {
return clazz;
}
public void setClazz(Class clazz) {
this.clazz = clazz;
}
public List<Converter> getCustomConverterList() {
return customConverterList;
}
public void setCustomConverterList(List<Converter> 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;
}
} }

286
src/main/java/com/alibaba/excel/metadata/CellData.java

@ -1,286 +0,0 @@
package com.alibaba.excel.metadata;
import java.math.BigDecimal;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.util.StringUtils;
/**
* Excel internal cell data.
*
* <p>
*
* @author Jiaju Zhuang
*/
public class CellData<T> 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;
private Boolean formula;
private String formulaValue;
private byte[] imageValue;
/**
* The number formatting.Currently only supported when reading
*/
private Integer dataFormat;
/**
* The string of number formatting.Currently only supported when reading
*/
private String dataFormatString;
/**
* The resulting converted data.
*/
private T data;
public CellData(CellData<T> 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.dataFormat = other.dataFormat;
this.dataFormatString = other.dataFormatString;
this.data = other.data;
}
public CellData() {}
public CellData(T data) {
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);
}
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;
this.formula = Boolean.FALSE;
}
public CellData(BigDecimal numberValue) {
if (numberValue == null) {
throw new IllegalArgumentException("DoubleValue can not be null");
}
this.type = CellDataTypeEnum.NUMBER;
this.numberValue = numberValue;
this.formula = Boolean.FALSE;
}
public CellData(byte[] imageValue) {
if (imageValue == null) {
throw new IllegalArgumentException("ImageValue can not be null");
}
this.type = CellDataTypeEnum.IMAGE;
this.imageValue = imageValue;
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;
this.formula = Boolean.FALSE;
}
public CellData(CellDataTypeEnum type) {
if (type == null) {
throw new IllegalArgumentException("Type can not be null");
}
this.type = type;
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
*/
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;
}
@Override
public String toString() {
if (type == null) {
return StringUtils.EMPTY;
}
switch (type) {
case NUMBER:
return numberValue.toString();
case BOOLEAN:
return booleanValue.toString();
case DIRECT_STRING:
case STRING:
case ERROR:
return stringValue;
case IMAGE:
return "image[" + imageValue.length + "]";
default:
return StringUtils.EMPTY;
}
}
}

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

@ -32,5 +32,5 @@ public interface ConfigurationHolder extends Holder {
* *
* @return Converter * @return Converter
*/ */
Map<String, Converter> converterMap(); Map<String, Converter<?>> converterMap();
} }

38
src/main/java/com/alibaba/excel/metadata/GlobalConfiguration.java

@ -2,11 +2,14 @@ package com.alibaba.excel.metadata;
import java.util.Locale; import java.util.Locale;
import lombok.Data;
/** /**
* Global configuration * Global configuration
* *
* @author Jiaju Zhuang * @author Jiaju Zhuang
*/ */
@Data
public class GlobalConfiguration { public class GlobalConfiguration {
/** /**
* Automatic trim includes sheet name and content * Automatic trim includes sheet name and content
@ -32,35 +35,10 @@ public class GlobalConfiguration {
*/ */
private Boolean useScientificFormat; private Boolean useScientificFormat;
public Boolean getUse1904windowing() { public GlobalConfiguration() {
return use1904windowing; this.autoTrim = Boolean.TRUE;
} this.use1904windowing = Boolean.FALSE;
this.locale = Locale.getDefault();
public void setUse1904windowing(Boolean use1904windowing) { this.useScientificFormat = Boolean.FALSE;
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;
} }
} }

9
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 {
}

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

@ -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<? extends BaseRowModel> clazz;
/**
*/
private List<List<String>> head;
/**
*
*/
private TableStyle tableStyle;
/**
* column with
*/
private Map<Integer, Integer> columnWidthMap = new HashMap<Integer, Integer>();
/**
*
*/
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<? extends BaseRowModel> clazz) {
this.sheetNo = sheetNo;
this.headLineMun = headLineMun;
this.clazz = clazz;
}
public Sheet(int sheetNo, int headLineMun, Class<? extends BaseRowModel> clazz, String sheetName,
List<List<String>> head) {
this.sheetNo = sheetNo;
this.clazz = clazz;
this.headLineMun = headLineMun;
this.sheetName = sheetName;
this.head = head;
}
public List<List<String>> getHead() {
return head;
}
public void setHead(List<List<String>> head) {
this.head = head;
}
public Class<? extends BaseRowModel> getClazz() {
return clazz;
}
public void setClazz(Class<? extends BaseRowModel> 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<Integer, Integer> getColumnWidthMap() {
return columnWidthMap;
}
public void setColumnWidthMap(Map<Integer, Integer> 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;
}
}

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

@ -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<? extends BaseRowModel> clazz;
/**
*/
private List<List<String>> 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<? extends BaseRowModel> getClazz() {
return clazz;
}
public void setClazz(Class<? extends BaseRowModel> clazz) {
this.clazz = clazz;
}
public List<List<String>> getHead() {
return head;
}
public void setHead(List<List<String>> head) {
this.head = head;
}
public int getTableNo() {
return tableNo;
}
public void setTableNo(int tableNo) {
this.tableNo = tableNo;
}
}

65
src/main/java/com/alibaba/excel/metadata/TableStyle.java

@ -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;
}
}

354
src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java

@ -0,0 +1,354 @@
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.enums.NumericCellTypeEnum;
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;
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
*/
@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;
/**
* numeric cell type
*/
private NumericCellTypeEnum numericCellType;
/**
* workbook
*/
private final CsvWorkbook csvWorkbook;
/**
* sheet
*/
private final CsvSheet csvSheet;
/**
* 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(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;
if (this.cellType == null) {
this.cellType = CellType._NONE;
}
}
@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;
this.cellType = CellType.FORMULA;
}
@Override
protected void removeFormulaImpl() {
this.formulaData = null;
}
@Override
protected void setCellValueImpl(double value) {
numberValue = BigDecimal.valueOf(value);
this.cellType = CellType.NUMERIC;
}
@Override
protected void setCellValueImpl(Date value) {
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.dateValue = value;
this.cellType = CellType.NUMERIC;
this.numericCellType = NumericCellTypeEnum.DATE;
}
@Override
protected void setCellValueImpl(Calendar value) {
if (value == null) {
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
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;
}
@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;
this.cellType = CellType.BOOLEAN;
}
@Override
public void setCellErrorValue(byte value) {
this.numberValue = BigDecimal.valueOf(value);
this.cellType = CellType.ERROR;
}
@Override
public boolean getBooleanCellValue() {
if (booleanValue == null) {
return false;
}
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;
}
}

333
src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java

@ -0,0 +1,333 @@
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;
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;
/**
* csv cell style
*
* @author Jiaju Zhuang
*/
@Data
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 index;
}
@Override
public void setDataFormat(short fmt) {
initDataFormatData();
dataFormatData.setIndex(fmt);
}
private void initDataFormatData() {
if (dataFormatData == null) {
dataFormatData = new DataFormatData();
}
}
@Override
public short getDataFormat() {
if (dataFormatData == null) {
return 0;
}
return dataFormatData.getIndex();
}
@Override
public String getDataFormatString() {
if (dataFormatData == null) {
return null;
}
return dataFormatData.getFormat();
}
@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;
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save