Browse Source

Merge branch 'developing' into VerticalCellStrategy02TestCase

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

50
README.md

@ -4,21 +4,40 @@ EasyExcel
[![Maven central](https://maven-badges.herokuapp.com/maven-central/com.alibaba/easyexcel/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.alibaba/easyexcel)
[![License](http://img.shields.io/:license-apache-brightgreen.svg)](http://www.apache.org/licenses/LICENSE-2.0.html)
[QQ群: 662022184](//shang.qq.com/wpa/qunwpa?idkey=53d9d821b0833e3c14670f007488a61e300f00ff4f1b81fd950590d90dd80f80)
[钉钉群: 21960511](https://qr.dingtalk.com/action/joingroup?code=v1,k1,cchz6k12ci9B08NNqhNRFGXocNVHrZtW0kaOtTKg/Rk=&_dt_no_comment=1&origin=11)
[官方网站: https://yuque.com/easyexcel](https://www.yuque.com/easyexcel/doc/easyexcel)
[QQ1群(已满): 662022184](https://jq.qq.com/?_wv=1027&k=1T21jJxh)
[QQ2群(已满): 1097936804](https://jq.qq.com/?_wv=1027&k=j5zEy6Xl)
[QQ3群: 453928496](https://qm.qq.com/cgi-bin/qm/qr?k=e2ULsA5A0GldhV2CXJ8sIbAyu9I6qqs7&jump_from=webapi)
[钉钉1群(已满): 21960511](https://qr.dingtalk.com/action/joingroup?code=v1,k1,cchz6k12ci9B08NNqhNRFGXocNVHrZtW0kaOtTKg/Rk=&_dt_no_comment=1&origin=11)
[钉钉2群(已满): 32796397](https://qr.dingtalk.com/action/joingroup?code=v1,k1,jyU9GtEuNU5S0QTyklqYcYJ8qDZtUuTPMM7uPZTS8Hs=&_dt_no_comment=1&origin=11)
[钉钉3群(已满): 33797247](https://qr.dingtalk.com/action/joingroup?code=v1,k1,3UGlEScTGQaHpW2cIRo+gkxJ9EVZ5fz26M6nW3uFP30=&_dt_no_comment=1&origin=11)
[钉钉4群(已满): 33491624](https://qr.dingtalk.com/action/joingroup?code=v1,k1,V14Pb65Too70rQkEaJ9ohb6lZBZbtp6jIL/q9EWh9vA=&_dt_no_comment=1&origin=11)
[钉钉5群: 32134498](https://h5.dingtalk.com/circle/healthCheckin.html?dtaction=os&corpId=dingb9fa1325d9dccc3ecac589edd02f1650&5233a=71a83&cbdbhh=qwertyuiop)
[官方网站: https://yuque.com/easyexcel](https://www.yuque.com/easyexcel/doc/easyexcel)
[常见问题](https://www.yuque.com/easyexcel/faq)
#### 因为公司不方便用QQ,所以建议加钉钉群
# JAVA解析Excel工具EasyExcel
Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,能够原本一个3M的excel用POI sax依然需要100M左右内存降低到几M,并且再大的excel不会出现内存溢出,03版依赖POI的sax模式。在上层做了模型转换的封装,让使用者更加简单方便
Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,改用easyexcel可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便
## 64M内存1分钟内读取75M(46W行25列)的Excel
当然还有速模式能更快,但是内存占用会在100M多一点
当然还有速模式能更快,但是内存占用会在100M多一点
![img](img/readme/large.png)
## 版本支持
* 2+ 版本支持 Java7和Java6
* 3+ 版本至少 Java8
## 人员招募
由于工作较忙,有意愿做开源的同学可以报名,主要负责群里回答&issue处理,当然也可以做一些PR.
由于开源没有任何物质回报,然后现在的维护同学也是课余时间维护的,所以想加入的同学需要持之以恒,而不是一时兴起.
要求如下:
* 有一定java编码能力 & 良好的编码习惯
* 了解easyexcel 读&写的原理
* 热爱开源项目
* 能长期坚持的去做
* 相对工作没那么忙
## 相关文档
* [快速开始](https://www.yuque.com/easyexcel/doc/easyexcel)
* [关于软件](/abouteasyexcel.md)
@ -26,7 +45,7 @@ Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都
* [贡献代码](https://www.yuque.com/easyexcel/doc/contribute)
## 维护者
玉霄、庄家钜、怀宇
姬朋飞(玉霄)、庄家钜、怀宇
## 快速开始
### 读Excel
DEMO代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/demo/read/ReadTest.java](/src/test/java/com/alibaba/easyexcel/test/demo/read/ReadTest.java)
@ -66,20 +85,23 @@ DEMO代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/ja
### web上传、下载
DEMO代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java](/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java)
```java
/**
/**
* 文件下载(失败了会返回一个有部分数据的Excel)
* <p>1. 创建excel对应的实体对象 参照{@link DownloadData}
* <p>2. 设置返回的 参数
* <p>3. 直接写,这里注意,finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
* <p>
* 1. 创建excel对应的实体对象 参照{@link DownloadData}
* <p>
* 2. 设置返回的 参数
* <p>
* 3. 直接写,这里注意,finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
*/
@GetMapping("download")
public void download(HttpServletResponse response) throws IOException {
// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
response.setContentType("application/vnd.ms-excel");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("测试", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data());
}

2
lombok.config

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

56
pom.xml

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.3</version>
<version>3.0.0-beta1</version>
<packaging>jar</packaging>
<name>easyexcel</name>
@ -16,7 +16,7 @@
<properties>
<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>
<maven.javadoc.skip>true</maven.javadoc.skip>
</properties>
@ -60,22 +60,27 @@
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<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>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
@ -85,8 +90,15 @@
<dependency>
<groupId>org.ehcache</groupId>
<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>
<!--test-->
<dependency>
<groupId>ch.qos.logback</groupId>
@ -97,13 +109,7 @@
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<version>1.2.71</version>
<scope>test</scope>
</dependency>
<dependency>
@ -121,7 +127,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>
@ -162,6 +168,9 @@
<exclude>com/alibaba/excel/event/AnalysisEventListener.java</exclude>
<exclude>com/alibaba/excel/metadata/DataFormatter.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/ExcelGeneralNumberFormat.java</exclude>
</excludes>
</configuration>
<executions>
@ -185,8 +194,8 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
@ -230,6 +239,19 @@
</execution>
</executions>
</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>
</build>
</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.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.event.WriteHandler;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterTableBuilder;
@ -39,138 +32,6 @@ import com.alibaba.excel.write.builder.ExcelWriterTableBuilder;
*/
public class EasyExcelFactory {
/**
* Quickly read small 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

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

@ -1,25 +1,17 @@
package com.alibaba.excel;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.analysis.ExcelAnalyser;
import com.alibaba.excel.analysis.ExcelAnalyserImpl;
import com.alibaba.excel.analysis.ExcelReadExecutor;
import com.alibaba.excel.cache.MapCache;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.parameter.AnalysisParam;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Excel readers are all read in event mode.
@ -34,113 +26,6 @@ public class ExcelReader {
*/
private ExcelAnalyser excelAnalyser;
/**
* Create new reader
*
* @param in
* the POI filesystem that contains the Workbook stream
* @param excelTypeEnum
* 03 or 07
* @param customContent
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener
* Callback method after each row is parsed.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/
@Deprecated
public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent,
AnalysisEventListener eventListener) {
this(in, excelTypeEnum, customContent, eventListener, true);
}
/**
* Create new reader
*
* @param in
* the POI filesystem that contains the Workbook stream
* @param customContent
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener
* Callback method after each row is parsed
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/
@Deprecated
public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener) {
this(in, customContent, eventListener, true);
}
/**
* Create new reader
*
* @param param
* old param Deprecated
* @param eventListener
* Callback method after each row is parsed.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/
@Deprecated
public ExcelReader(AnalysisParam param, AnalysisEventListener eventListener) {
this(param.getIn(), param.getExcelTypeEnum(), param.getCustomContent(), eventListener, true);
}
/**
* Create new reader
*
* @param in
* @param customContent
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener
* @param trim
* The content of the form is empty and needs to be empty. The purpose is to be fault-tolerant, because
* there are often table contents with spaces that can not be converted into custom types. For example:
* '1234 ' contain a space cannot be converted to int.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/
@Deprecated
public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener, boolean trim) {
this(in, null, customContent, eventListener, trim);
}
/**
* Create new reader
*
* @param in
* the POI filesystem that contains the Workbook stream
* @param excelTypeEnum
* 03 or 07
* @param customContent
* {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener
* Callback method after each row is parsed.
* @param trim
* The content of the form is empty and needs to be empty. The purpose is to be fault-tolerant, because
* there are often table contents with spaces that can not be converted into custom types. For example:
* '1234 ' contain a space cannot be converted to int.
* @deprecated please use {@link EasyExcelFactory#read()} build 'ExcelReader'
*/
@Deprecated
public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent,
AnalysisEventListener eventListener, boolean trim) {
ReadWorkbook readWorkbook = new ReadWorkbook();
readWorkbook.setInputStream(in);
readWorkbook.setExcelType(excelTypeEnum);
readWorkbook.setCustomObject(customContent);
if (eventListener != null) {
List<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) {
excelAnalyser = new ExcelAnalyserImpl(readWorkbook);
}
@ -183,44 +68,6 @@ public class ExcelReader {
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
@ -240,28 +87,6 @@ public class ExcelReader {
return excelAnalyser.excelExecutor();
}
/**
* Parse the workBook get all sheets
*
* @return workBook all sheets
*
* @deprecated please use {@link #excelExecutor()}
*/
@Deprecated
public List<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

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

@ -1,27 +1,18 @@
package com.alibaba.excel;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.parameter.GenerateParam;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.ExcelBuilder;
import com.alibaba.excel.write.ExcelBuilderImpl;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.WriteWorkbook;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Excel Writer This tool is used to write value out to Excel via POI. This object can perform the following two
* functions.
@ -47,92 +38,6 @@ public class ExcelWriter {
excelBuilder = new ExcelBuilderImpl(writeWorkbook);
}
/**
* Create new writer
*
* @param outputStream
* the java OutputStream you wish to write the value to
* @param typeEnum
* 03 or 07
* @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter
*/
@Deprecated
public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum) {
this(outputStream, typeEnum, true);
}
/**
*
* Create new writer
*
* @param outputStream
* the java OutputStream you wish to write the value to
* @param typeEnum
* 03 or 07
* @param needHead
* Do you need to write the header to the file?
* @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter
*/
@Deprecated
public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) {
this(null, outputStream, typeEnum, needHead, null);
}
/**
* Create new writer
*
* @param templateInputStream
* Append value after a POI file ,Can be 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
*
@ -142,7 +47,7 @@ public class ExcelWriter {
* Write to this sheet
* @return this current writer
*/
public ExcelWriter write(List data, WriteSheet writeSheet) {
public ExcelWriter write(Collection<?> data, WriteSheet writeSheet) {
return write(data, writeSheet, null);
}
@ -157,7 +62,7 @@ public class ExcelWriter {
* Write to this table
* @return this
*/
public ExcelWriter write(List data, WriteSheet writeSheet, WriteTable writeTable) {
public ExcelWriter write(Collection<?> data, WriteSheet writeSheet, WriteTable writeTable) {
excelBuilder.addContent(data, writeSheet, writeTable);
return this;
}
@ -186,141 +91,6 @@ public class ExcelWriter {
return this;
}
/**
* Write data to a sheet
*
* @param data
* Data to be written
* @param sheet
* Write to this sheet
* @return this current writer
* @deprecated please use {@link ExcelWriter#write(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
*/

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.util.List;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.filesystem.DocumentFactoryHelper;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.analysis.csv.CsvExcelReadExecutor;
import com.alibaba.excel.analysis.v03.XlsSaxAnalyser;
import com.alibaba.excel.analysis.v07.XlsxSaxAnalyser;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.context.csv.CsvReadContext;
import com.alibaba.excel.context.csv.DefaultCsvReadContext;
import com.alibaba.excel.context.xls.DefaultXlsReadContext;
import com.alibaba.excel.context.xls.XlsReadContext;
import com.alibaba.excel.context.xlsx.DefaultXlsxReadContext;
@ -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.xlsx.XlsxReadWorkbookHolder;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.NumberDataFormatterUtils;
import com.alibaba.excel.util.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.filesystem.DocumentFactoryHelper;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jipengfei
*/
@ -98,6 +101,11 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
analysisContext = xlsxReadContext;
excelReadExecutor = new XlsxSaxAnalyser(xlsxReadContext, null);
break;
case CSV:
CsvReadContext csvReadContext = new DefaultCsvReadContext(readWorkbook, ExcelTypeEnum.CSV);
analysisContext = csvReadContext;
excelReadExecutor = new CsvExcelReadExecutor(csvReadContext);
break;
default:
break;
}

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

8
src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java

@ -70,12 +70,12 @@ import com.alibaba.excel.read.metadata.holder.xls.XlsReadWorkbookHolder;
* <p>
* * To turn an excel file into a CSV or similar, then see * the XLS2CSVmra example *
* </p>
* * * @see <a href=
* "http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java">XLS2CSVmra</a>
* * * @see <a href= "http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java">XLS2CSVmra</a>
*
* @author jipengfei
*/
public class XlsSaxAnalyser implements HSSFListener, ExcelReadExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(XlsSaxAnalyser.class);
private static final short DUMMY_RECORD_SID = -1;
private XlsReadContext xlsReadContext;
@ -146,8 +146,8 @@ public class XlsSaxAnalyser implements HSSFListener, ExcelReadExecutor {
if (handler == null) {
return;
}
boolean ignoreRecord = (handler instanceof IgnorableXlsRecordHandler)
&& xlsReadContext.xlsReadSheetHolder() != null && xlsReadContext.xlsReadSheetHolder().getIgnoreRecord();
boolean ignoreRecord =
(handler instanceof IgnorableXlsRecordHandler) && xlsReadContext.xlsReadWorkbookHolder().getIgnoreRecord();
if (ignoreRecord) {
// No need to read the current sheet
return;

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

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

13
src/main/java/com/alibaba/excel/analysis/v03/handlers/BofRecordHandler.java

@ -22,10 +22,11 @@ public class BofRecordHandler extends AbstractXlsRecordHandler {
@Override
public void processRecord(XlsReadContext xlsReadContext, Record record) {
BOFRecord br = (BOFRecord)record;
BOFRecord br = (BOFRecord) record;
XlsReadWorkbookHolder xlsReadWorkbookHolder = xlsReadContext.xlsReadWorkbookHolder();
if (br.getType() == BOFRecord.TYPE_WORKBOOK) {
xlsReadWorkbookHolder.setReadSheetIndex(null);
xlsReadWorkbookHolder.setIgnoreRecord(Boolean.FALSE);
return;
}
if (br.getType() != BOFRecord.TYPE_WORKSHEET) {
@ -38,15 +39,15 @@ public class BofRecordHandler extends AbstractXlsRecordHandler {
readSheetIndex = 0;
xlsReadWorkbookHolder.setReadSheetIndex(readSheetIndex);
}
ReadSheet readSheet = xlsReadWorkbookHolder.getActualSheetDataList().get(readSheetIndex);
assert readSheet != null : "Can't find the sheet.";
ReadSheet actualReadSheet = xlsReadWorkbookHolder.getActualSheetDataList().get(readSheetIndex);
assert actualReadSheet != null : "Can't find the sheet.";
// Copy the parameter to the current sheet
readSheet = SheetUtils.match(readSheet, xlsReadContext);
ReadSheet readSheet = SheetUtils.match(actualReadSheet, xlsReadContext);
if (readSheet != null) {
xlsReadContext.currentSheet(readSheet);
xlsReadContext.xlsReadSheetHolder().setIgnoreRecord(Boolean.FALSE);
xlsReadContext.xlsReadWorkbookHolder().setIgnoreRecord(Boolean.FALSE);
} else {
xlsReadContext.xlsReadSheetHolder().setIgnoreRecord(Boolean.TRUE);
xlsReadContext.xlsReadWorkbookHolder().setIgnoreRecord(Boolean.TRUE);
}
// Go read the next one
xlsReadWorkbookHolder.setReadSheetIndex(xlsReadWorkbookHolder.getReadSheetIndex() + 1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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.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;
/**
@ -23,7 +23,7 @@ public class StringRecordHandler extends AbstractXlsRecordHandler implements Ign
// String for formula
StringRecord srec = (StringRecord)record;
XlsReadSheetHolder xlsReadSheetHolder = xlsReadContext.xlsReadSheetHolder();
CellData tempCellData = xlsReadSheetHolder.getTempCellData();
CellData<?>tempCellData = xlsReadSheetHolder.getTempCellData();
if (tempCellData == null) {
LOGGER.warn("String type formula but no value found.");
return;

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

@ -5,13 +5,31 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.alibaba.excel.analysis.ExcelReadExecutor;
import com.alibaba.excel.analysis.v07.handlers.sax.SharedStringsTableHandler;
import com.alibaba.excel.analysis.v07.handlers.sax.XlsxRowHandler;
import com.alibaba.excel.cache.ReadCache;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadWorkbookHolder;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.SheetUtils;
import com.alibaba.excel.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.openxml4j.opc.PackagePart;
@ -25,26 +43,13 @@ import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import com.alibaba.excel.analysis.ExcelReadExecutor;
import com.alibaba.excel.analysis.v07.handlers.sax.SharedStringsTableHandler;
import com.alibaba.excel.analysis.v07.handlers.sax.XlsxRowHandler;
import com.alibaba.excel.cache.ReadCache;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadWorkbookHolder;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.SheetUtils;
import com.alibaba.excel.util.StringUtils;
/**
* @author jipengfei
*/
@Slf4j
public class XlsxSaxAnalyser implements ExcelReadExecutor {
private XlsxReadContext xlsxReadContext;
@ -78,7 +83,9 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor {
XSSFReader xssfReader = new XSSFReader(pkg);
analysisUse1904WindowDate(xssfReader, xlsxReadWorkbookHolder);
xlsxReadWorkbookHolder.setStylesTable(xssfReader.getStylesTable());
// set style table
setStylesTable(xlsxReadWorkbookHolder, xssfReader);
sheetList = new ArrayList<ReadSheet>();
sheetMap = new HashMap<Integer, InputStream>();
commentsTableMap = new HashMap<Integer, CommentsTable>();
@ -101,6 +108,17 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor {
}
}
private void setStylesTable(XlsxReadWorkbookHolder xlsxReadWorkbookHolder, XSSFReader xssfReader) {
try {
xlsxReadWorkbookHolder.setStylesTable(xssfReader.getStylesTable());
} catch (Exception e) {
log.warn(
"Currently excel cannot get style information, but it doesn't affect the data analysis.You can try to"
+ " save the file with office again or ignore the current error.",
e);
}
}
private void defaultReadCache(XlsxReadWorkbookHolder xlsxReadWorkbookHolder,
PackagePart sharedStringsTablePackagePart) {
ReadCache readCache = xlsxReadWorkbookHolder.getReadCacheSelector().readCache(sharedStringsTablePackagePart);
@ -147,9 +165,10 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor {
xlsxReadWorkbookHolder.setTempFile(readTempFile);
File tempFile = new File(readTempFile.getPath(), UUID.randomUUID().toString() + ".xlsx");
if (decryptedStream != null) {
FileUtils.writeToFile(tempFile, decryptedStream);
FileUtils.writeToFile(tempFile, decryptedStream, false);
} else {
FileUtils.writeToFile(tempFile, xlsxReadWorkbookHolder.getInputStream());
FileUtils.writeToFile(tempFile, xlsxReadWorkbookHolder.getInputStream(),
xlsxReadWorkbookHolder.getAutoCloseStream());
}
return OPCPackage.open(tempFile, PackageAccess.READ);
}
@ -177,9 +196,7 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor {
xmlReader.setContentHandler(handler);
xmlReader.parse(inputSource);
inputStream.close();
} catch (ExcelAnalysisException e) {
throw e;
} catch (Exception e) {
} catch (IOException | ParserConfigurationException | SAXException e) {
throw new ExcelAnalysisException(e);
} finally {
if (inputStream != null) {
@ -215,10 +232,12 @@ public class XlsxSaxAnalyser implements ExcelReadExecutor {
if (commentsTable == null) {
return;
}
Map<CellAddress, XSSFComment> cellComments = commentsTable.getCellComments();
for (XSSFComment xssfComment : cellComments.values()) {
CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.COMMENT, xssfComment.getString().toString(),
xssfComment.getRow(), xssfComment.getColumn());
Iterator<CellAddress> cellAddresses = commentsTable.getCellAddresses();
while (cellAddresses.hasNext()) {
CellAddress cellAddress = cellAddresses.next();
XSSFComment cellComment = commentsTable.findCellComment(cellAddress);
CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.COMMENT, cellComment.getString().toString(),
cellAddress.getRow(), cellAddress.getColumn());
xlsxReadContext.readSheetHolder().setCellExtra(cellExtra);
xlsxReadContext.analysisEventProcessor().extra(xlsxReadContext);
}

26
src/main/java/com/alibaba/excel/analysis/v07/handlers/AbstractCellValueTagHandler.java

@ -4,9 +4,10 @@ import java.math.BigDecimal;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.util.StringUtils;
/**
* Cell Value Handler
@ -18,8 +19,9 @@ public abstract class AbstractCellValueTagHandler extends AbstractXlsxTagHandler
@Override
public void endElement(XlsxReadContext xlsxReadContext, String name) {
XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder();
CellData tempCellData = xlsxReadSheetHolder.getTempCellData();
ReadCellData<?> tempCellData = xlsxReadSheetHolder.getTempCellData();
StringBuilder tempData = xlsxReadSheetHolder.getTempData();
String tempDataString = tempData.toString();
CellDataTypeEnum oldType = tempCellData.getType();
switch (oldType) {
case DIRECT_STRING:
@ -28,12 +30,26 @@ public abstract class AbstractCellValueTagHandler extends AbstractXlsxTagHandler
tempCellData.setStringValue(tempData.toString());
break;
case BOOLEAN:
if (StringUtils.isEmpty(tempDataString)) {
tempCellData.setType(CellDataTypeEnum.EMPTY);
break;
}
tempCellData.setBooleanValue(BooleanUtils.valueOf(tempData.toString()));
break;
case NUMBER:
case EMPTY:
tempCellData.setType(CellDataTypeEnum.NUMBER);
tempCellData.setNumberValue(new BigDecimal(tempData.toString()));
if (StringUtils.isEmpty(tempDataString)) {
tempCellData.setType(CellDataTypeEnum.EMPTY);
break;
}
// fix https://github.com/alibaba/easyexcel/issues/1595
if (StringUtils.isNumeric(tempDataString)) {
tempCellData.setType(CellDataTypeEnum.NUMBER);
tempCellData.setNumberValue(BigDecimal.valueOf(Double.parseDouble(tempDataString)));
} else {
tempCellData.setType(CellDataTypeEnum.STRING);
tempCellData.setStringValue(tempData.toString());
}
break;
default:
throw new IllegalStateException("Cannot set values now");
@ -44,7 +60,7 @@ public abstract class AbstractCellValueTagHandler extends AbstractXlsxTagHandler
if (tempCellData.getStringValue() != null
&& xlsxReadContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
tempCellData.setStringValue(tempCellData.getStringValue());
tempCellData.setStringValue(tempCellData.getStringValue().trim());
}
tempCellData.checkEmpty();

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

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

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

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

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

@ -1,17 +1,19 @@
package com.alibaba.excel.analysis.v07.handlers;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.xml.sax.Attributes;
import com.alibaba.excel.constant.BuiltinFormats;
import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.data.DataFormatData;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder;
import com.alibaba.excel.util.PositionUtils;
import com.alibaba.excel.util.StringUtils;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.xml.sax.Attributes;
/**
* Cell Handler
*
@ -27,15 +29,15 @@ public class CellTagHandler extends AbstractXlsxTagHandler {
xlsxReadSheetHolder.setColumnIndex(PositionUtils.getCol(attributes.getValue(ExcelXmlConstants.ATTRIBUTE_R),
xlsxReadSheetHolder.getColumnIndex()));
// t="s" ,it's means String
// t="str" ,it's means String,but does not need to be read in the 'sharedStrings.xml'
// t="inlineStr" ,it's means String
// t="b" ,it's means Boolean
// t="e" ,it's means Error
// t="n" ,it's means Number
// t is null ,it's means Empty or Number
// t="s" ,it means String
// t="str" ,it means String,but does not need to be read in the 'sharedStrings.xml'
// t="inlineStr" ,it means String
// t="b" ,it means Boolean
// t="e" ,it means Error
// t="n" ,it means Number
// t is null ,it means Empty or Number
CellDataTypeEnum type = CellDataTypeEnum.buildFromCellType(attributes.getValue(ExcelXmlConstants.ATTRIBUTE_T));
xlsxReadSheetHolder.setTempCellData(new CellData(type));
xlsxReadSheetHolder.setTempCellData(new ReadCellData<>(type));
xlsxReadSheetHolder.setTempData(new StringBuilder());
// Put in data transformation information
@ -46,12 +48,17 @@ public class CellTagHandler extends AbstractXlsxTagHandler {
} else {
dateFormatIndexInteger = Integer.parseInt(dateFormatIndex);
}
XSSFCellStyle xssfCellStyle =
xlsxReadContext.xlsxReadWorkbookHolder().getStylesTable().getStyleAt(dateFormatIndexInteger);
int dataFormat = xssfCellStyle.getDataFormat();
xlsxReadSheetHolder.getTempCellData().setDataFormat(dataFormat);
xlsxReadSheetHolder.getTempCellData().setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormat,
StylesTable stylesTable = xlsxReadContext.xlsxReadWorkbookHolder().getStylesTable();
if (stylesTable == null) {
return;
}
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()));
xlsxReadSheetHolder.getTempCellData().setDataFormatData(dataFormatData);
}
}

7
src/main/java/com/alibaba/excel/analysis/v07/handlers/CellValueTagHandler.java

@ -2,7 +2,8 @@ package com.alibaba.excel.analysis.v07.handlers;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.util.StringUtils;
/**
* Cell Value Handler
@ -17,6 +18,10 @@ public class CellValueTagHandler extends AbstractCellValueTagHandler {
CellData tempCellData = xlsxReadContext.xlsxReadSheetHolder().getTempCellData();
switch (tempCellData.getType()) {
case STRING:
// In some cases, although cell type is a string, it may be an empty tag
if(StringUtils.isEmpty(tempCellData.getStringValue())){
break;
}
String stringValue = xlsxReadContext.readWorkbookHolder().getReadCache()
.get(Integer.valueOf(tempCellData.getStringValue()));
if (stringValue != null && xlsxReadContext.currentReadHolder().globalConfiguration().getAutoTrim()) {

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

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

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

@ -23,7 +23,7 @@ public @interface ExcelProperty {
* <p>
* write: It automatically merges when you have more than one head
* <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
*/
@ -32,12 +32,23 @@ public @interface ExcelProperty {
/**
* Index of column
*
* Read or write it on the index of column,If it's equal to -1, it's sorted by Java class
* Read or write it on the index of column, If it's equal to -1, it's sorted by Java class.
*
* priority: index &gt; order &gt; default sort
*
* @return Index of column
*/
int index() default -1;
/**
* Defines the sort order for an column.
*
* priority: index &gt; order &gt; default sort
*
* @return Order of column
*/
int order() default Integer.MAX_VALUE;
/**
* Force the current field to use this converter.
*

2
src/main/java/com/alibaba/excel/annotation/write/style/ContentFontStyle.java

@ -52,7 +52,7 @@ public @interface ContentFontStyle {
short color() default -1;
/**
* Set normal,super or subscript.
* Set normal, super or subscript.
*
* @see Font#SS_NONE
* @see Font#SS_SUPER

2
src/main/java/com/alibaba/excel/annotation/write/style/HeadFontStyle.java

@ -52,7 +52,7 @@ public @interface HeadFontStyle {
short color() default -1;
/**
* Set normal,super or subscript.
* Set normal, super or subscript.
*
* @see Font#SS_NONE
* @see Font#SS_SUPER

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

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

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

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

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

@ -1,6 +1,9 @@
package com.alibaba.excel.constant;
import java.util.Locale;
import java.util.Map;
import com.alibaba.excel.util.MapUtils;
/**
* Excel's built-in format conversion.Currently only supports Chinese.
@ -17,7 +20,9 @@ import java.util.Locale;
**/
public class BuiltinFormats {
private static final String[] BUILTIN_FORMATS_CN = {
public static short GENERAL = 0;
public static final String[] BUILTIN_FORMATS_CN = {
// 0
"General",
// 1
@ -189,7 +194,7 @@ public class BuiltinFormats {
// end
};
private static final String[] BUILTIN_FORMATS_US = {
public static final String[] BUILTIN_FORMATS_US = {
// 0
"General",
// 1
@ -361,7 +366,11 @@ public class BuiltinFormats {
// 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);
if (index == null || index < 0 || index >= builtinFormat.length) {
return defaultFormat;
@ -369,11 +378,26 @@ public class BuiltinFormats {
return builtinFormat[index];
}
private static String[] switchBuiltinFormats(Locale locale) {
public static String[] switchBuiltinFormats(Locale locale) {
if (locale != null && Locale.US.getCountry().equals(locale.getCountry())) {
return BUILTIN_FORMATS_US;
}
return BUILTIN_FORMATS_CN;
}
public static Map<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 com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.ReadHolder;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
@ -92,15 +91,6 @@ public interface AnalysisContext {
*/
void readSheetList(List<ReadSheet> readSheetList);
/**
* get current sheet
*
* @return current analysis sheet
* @deprecated please use {@link #readSheetHolder()}
*/
@Deprecated
Sheet getCurrentSheet();
/**
*
* 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.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.read.metadata.holder.ReadHolder;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.ReadSheetHolder;
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder;
import com.alibaba.excel.read.metadata.holder.csv.CsvReadSheetHolder;
import com.alibaba.excel.read.metadata.holder.csv.CsvReadWorkbookHolder;
import com.alibaba.excel.read.metadata.holder.xls.XlsReadSheetHolder;
import com.alibaba.excel.read.metadata.holder.xls.XlsReadWorkbookHolder;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder;
@ -22,12 +20,13 @@ import com.alibaba.excel.read.processor.AnalysisEventProcessor;
import com.alibaba.excel.read.processor.DefaultAnalysisEventProcessor;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
/**
*
* @author jipengfei
*/
@Slf4j
public class AnalysisContextImpl implements AnalysisContext {
private static final Logger LOGGER = LoggerFactory.getLogger(AnalysisContextImpl.class);
/**
* The Workbook currently written
*/
@ -60,13 +59,16 @@ public class AnalysisContextImpl implements AnalysisContext {
case XLSX:
readWorkbookHolder = new XlsxReadWorkbookHolder(readWorkbook);
break;
case CSV:
readWorkbookHolder = new CsvReadWorkbookHolder(readWorkbook);
break;
default:
break;
}
currentReadHolder = readWorkbookHolder;
analysisEventProcessor = new DefaultAnalysisEventProcessor();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Initialization 'AnalysisContextImpl' complete");
if (log.isDebugEnabled()) {
log.debug("Initialization 'AnalysisContextImpl' complete");
}
}
@ -79,6 +81,9 @@ public class AnalysisContextImpl implements AnalysisContext {
case XLSX:
readSheetHolder = new XlsxReadSheetHolder(readSheet, readWorkbookHolder);
break;
case CSV:
readSheetHolder = new CsvReadSheetHolder(readSheet, readWorkbookHolder);
break;
default:
break;
}
@ -87,8 +92,8 @@ public class AnalysisContextImpl implements AnalysisContext {
throw new ExcelAnalysisException("Cannot read sheet repeatedly.");
}
readWorkbookHolder.getHasReadSheet().add(readSheetHolder.getSheetNo());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Began to read:{}", readSheetHolder);
if (log.isDebugEnabled()) {
log.debug("Began to read:{}", readSheetHolder);
}
}
@ -137,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
public ExcelTypeEnum getExcelType() {
return readWorkbookHolder.getExcelType();

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

@ -6,26 +6,10 @@ import java.io.OutputStream;
import java.util.Map;
import java.util.UUID;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.enums.WriteTypeEnum;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.FileUtils;
@ -42,6 +26,22 @@ import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.property.ExcelWriteHeadProperty;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A context is the main anchorage point of a excel writer.
*
@ -50,6 +50,7 @@ import com.alibaba.excel.write.property.ExcelWriteHeadProperty;
public class WriteContextImpl implements WriteContext {
private static final Logger LOGGER = LoggerFactory.getLogger(WriteContextImpl.class);
private static final String NO_SHEETS = "no sheets";
/**
* The Workbook currently written
@ -112,7 +113,6 @@ public class WriteContextImpl implements WriteContext {
return;
}
initCurrentSheetHolder(writeSheet);
// Workbook handler need to supplementary execution
@ -125,8 +125,12 @@ public class WriteContextImpl implements WriteContext {
private boolean selectSheetFromCache(WriteSheet writeSheet) {
writeSheetHolder = null;
if (writeSheet.getSheetNo() != null) {
writeSheetHolder = writeWorkbookHolder.getHasBeenInitializedSheetIndexMap().get(writeSheet.getSheetNo());
Integer sheetNo = writeSheet.getSheetNo();
if (sheetNo == null && StringUtils.isEmpty(writeSheet.getSheetName())) {
sheetNo = 0;
}
if (sheetNo != null) {
writeSheetHolder = writeWorkbookHolder.getHasBeenInitializedSheetIndexMap().get(sheetNo);
}
if (writeSheetHolder == null && !StringUtils.isEmpty(writeSheet.getSheetName())) {
writeSheetHolder = writeWorkbookHolder.getHasBeenInitializedSheetNameMap().get(writeSheet.getSheetName());
@ -160,17 +164,27 @@ public class WriteContextImpl implements WriteContext {
Sheet currentSheet;
try {
if (writeSheetHolder.getSheetNo() != null) {
currentSheet = writeWorkbookHolder.getWorkbook().getSheetAt(writeSheetHolder.getSheetNo());
writeSheetHolder
.setCachedSheet(writeWorkbookHolder.getCachedWorkbook().getSheetAt(writeSheetHolder.getSheetNo()));
// When the add default sort order of appearance
if (WriteTypeEnum.ADD.equals(writeType) && writeWorkbookHolder.getTempTemplateInputStream() == null) {
currentSheet = createSheet();
} else {
currentSheet = writeWorkbookHolder.getWorkbook().getSheetAt(writeSheetHolder.getSheetNo());
writeSheetHolder
.setCachedSheet(
writeWorkbookHolder.getCachedWorkbook().getSheetAt(writeSheetHolder.getSheetNo()));
}
} else {
// sheet name must not null
currentSheet = writeWorkbookHolder.getWorkbook().getSheet(writeSheetHolder.getSheetName());
writeSheetHolder
.setCachedSheet(writeWorkbookHolder.getCachedWorkbook().getSheet(writeSheetHolder.getSheetName()));
}
} catch (Exception e) {
currentSheet = createSheet();
} catch (IllegalArgumentException e) {
if (e.getMessage() != null && e.getMessage().contains(NO_SHEETS)) {
currentSheet = createSheet();
} else {
throw e;
}
}
if (currentSheet == null) {
currentSheet = createSheet();
@ -231,10 +245,16 @@ public class WriteContextImpl implements WriteContext {
Head head = entry.getValue();
int columnIndex = entry.getKey();
WriteHandlerUtils.beforeCellCreate(this, row, head, columnIndex, relativeRowIndex, Boolean.TRUE);
Cell cell = row.createCell(columnIndex);
WriteHandlerUtils.afterCellCreate(this, cell, head, relativeRowIndex, Boolean.TRUE);
cell.setCellValue(head.getHeadNameList().get(relativeRowIndex));
WriteHandlerUtils.afterCellDispose(this, (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);
}
}
@ -271,7 +291,7 @@ public class WriteContextImpl implements WriteContext {
}
private void initCurrentTableHolder(WriteTable writeTable) {
writeTableHolder = new WriteTableHolder(writeTable, writeSheetHolder, writeWorkbookHolder);
writeTableHolder = new WriteTableHolder(writeTable, writeSheetHolder);
writeSheetHolder.getHasBeenInitializedTable().put(writeTable.getTableNo(), writeTableHolder);
currentWriteHolder = writeTableHolder;
if (LOGGER.isDebugEnabled()) {
@ -337,7 +357,7 @@ public class WriteContextImpl implements WriteContext {
try {
Workbook workbook = writeWorkbookHolder.getWorkbook();
if (workbook instanceof SXSSFWorkbook) {
((SXSSFWorkbook) workbook).dispose();
((SXSSFWorkbook)workbook).dispose();
}
} catch (Throwable t) {
throwable = t;
@ -417,7 +437,7 @@ public class WriteContextImpl implements WriteContext {
if (writeWorkbookHolder.getFile() != null) {
return false;
}
File tempXlsx = FileUtils.createTmpFile(UUID.randomUUID().toString() + ".xlsx");
File tempXlsx = FileUtils.createTmpFile(UUID.randomUUID() + ".xlsx");
FileOutputStream tempFileOutputStream = new FileOutputStream(tempXlsx);
try {
writeWorkbookHolder.getWorkbook().write(tempFileOutputStream);
@ -432,14 +452,9 @@ public class WriteContextImpl implements WriteContext {
throw e;
}
}
POIFSFileSystem fileSystem = null;
try {
fileSystem = openFileSystemAndEncrypt(tempXlsx);
try (POIFSFileSystem fileSystem = openFileSystemAndEncrypt(tempXlsx)) {
fileSystem.writeFilesystem(writeWorkbookHolder.getOutputStream());
} finally {
if (fileSystem != null) {
fileSystem.close();
}
if (!tempXlsx.delete()) {
throw new ExcelGenerateException("Can not delete temp File!");
}
@ -458,19 +473,9 @@ public class WriteContextImpl implements WriteContext {
if (writeWorkbookHolder.getFile() == null) {
return;
}
FileOutputStream fileOutputStream = null;
POIFSFileSystem fileSystem = null;
try {
fileSystem = openFileSystemAndEncrypt(writeWorkbookHolder.getFile());
fileOutputStream = new FileOutputStream(writeWorkbookHolder.getFile());
try (POIFSFileSystem fileSystem = openFileSystemAndEncrypt(writeWorkbookHolder.getFile());
FileOutputStream fileOutputStream = new FileOutputStream(writeWorkbookHolder.getFile())) {
fileSystem.writeFilesystem(fileOutputStream);
} finally {
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (fileSystem != null) {
fileSystem.close();
}
}
}
@ -478,15 +483,9 @@ public class WriteContextImpl implements WriteContext {
POIFSFileSystem fileSystem = new POIFSFileSystem();
Encryptor encryptor = new EncryptionInfo(EncryptionMode.standard).getEncryptor();
encryptor.confirmPassword(writeWorkbookHolder.getPassword());
OPCPackage opcPackage = null;
try {
opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE);
OutputStream outputStream = encryptor.getDataStream(fileSystem);
try (OPCPackage opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE);
OutputStream outputStream = encryptor.getDataStream(fileSystem)) {
opcPackage.save(outputStream);
} finally {
if (opcPackage != null) {
opcPackage.close();
}
}
return fileSystem;
}

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;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
* An empty converter.It's automatically converted by type.
*
* @author Jiaju Zhuang
*/
public class AutoConverter implements Converter {
@Override
public Class supportJavaTypeKey() {
return null;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return null;
}
@Override
public Object convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return null;
}
@Override
public CellData convertToExcelData(Object value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return null;
}
public class AutoConverter implements Converter<Object> {
}

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

@ -1,15 +1,16 @@
package com.alibaba.excel.converters;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
* Convert between Java objects and excel objects
*
* @author Dan Zheng
* @param <T>
* @author Dan Zheng
*/
public interface Converter<T> {
@ -18,44 +19,68 @@ public interface Converter<T> {
*
* @return Support for Java class
*/
Class supportJavaTypeKey();
default Class<?> supportJavaTypeKey() {
throw new UnsupportedOperationException("The current operation is not supported by the current converter.");
}
/**
* Back to object enum in excel
*
* @return Support for {@link CellDataTypeEnum}
*/
CellDataTypeEnum supportExcelTypeKey();
default CellDataTypeEnum supportExcelTypeKey() {
throw new UnsupportedOperationException("The current operation is not supported by the current converter.");
}
/**
* Convert excel objects to Java objects
*
* @param cellData Excel cell data.NotNull.
* @param contentProperty Content property.Nullable.
* @param globalConfiguration Global configuration.NotNull.
* @return Data to put into a Java object
* @throws Exception Exception.
*/
default T convertToJavaData(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
*
* @param cellData
* Excel cell data.NotNull.
* @param contentProperty
* Content property.Nullable.
* @param globalConfiguration
* Global configuration.NotNull.
* @param context read converter context
* @return Data to put into a Java object
* @throws Exception
* Exception.
* @throws 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,
GlobalConfiguration globalConfiguration) throws Exception;
default WriteCellData<?> convertToExcelData(T value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws Exception {
throw new UnsupportedOperationException("The current operation is not supported by the current converter.");
}
/**
* Convert Java objects to excel objects
*
* @param value
* Java Data.NotNull.
* @param contentProperty
* Content property.Nullable.
* @param globalConfiguration
* Global configuration.NotNull.
* @param context write context
* @return Data to put into a Excel
* @throws Exception
* Exception.
* @throws Exception Exception.
*/
CellData convertToExcelData(T value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration)
throws Exception;
default WriteCellData<?> convertToExcelData(WriteConverterContext<T> context) 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;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.util.MapUtils;
/**
* Converter unique key.Consider that you can just use class as the key.
@ -12,7 +12,7 @@ import com.alibaba.excel.enums.CellDataTypeEnum;
*/
public class ConverterKeyBuild {
private static final Map<String, String> BOXING_MAP = new HashMap<String, String>(16);
private static final Map<String, String> BOXING_MAP = MapUtils.newHashMap();
static {
BOXING_MAP.put(int.class.getName(), Integer.class.getName());
@ -25,7 +25,7 @@ public class ConverterKeyBuild {
BOXING_MAP.put(boolean.class.getName(), Boolean.class.getName());
}
public static String buildKey(Class clazz) {
public static String buildKey(Class<?> clazz) {
String className = clazz.getName();
String boxingClassName = BOXING_MAP.get(clazz.getName());
if (boxingClassName == null) {
@ -34,7 +34,11 @@ public class ConverterKeyBuild {
return boxingClassName;
}
public static String buildKey(Class clazz, CellDataTypeEnum cellDataTypeEnum) {
return buildKey(clazz) + "-" + cellDataTypeEnum.toString();
public static String buildKey(Class<?> clazz, CellDataTypeEnum cellDataTypeEnum) {
String key = buildKey(clazz);
if (cellDataTypeEnum == null) {
return key;
}
return key + "-" + cellDataTypeEnum;
}
}

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

@ -1,11 +1,11 @@
package com.alibaba.excel.converters;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.excel.converters.bigdecimal.BigDecimalBooleanConverter;
import com.alibaba.excel.converters.bigdecimal.BigDecimalNumberConverter;
import com.alibaba.excel.converters.bigdecimal.BigDecimalStringConverter;
import com.alibaba.excel.converters.biginteger.BigIntegerStringConverter;
import com.alibaba.excel.converters.booleanconverter.BooleanBooleanConverter;
import com.alibaba.excel.converters.booleanconverter.BooleanNumberConverter;
import com.alibaba.excel.converters.booleanconverter.BooleanStringConverter;
@ -14,6 +14,7 @@ import com.alibaba.excel.converters.bytearray.ByteArrayImageConverter;
import com.alibaba.excel.converters.byteconverter.ByteBooleanConverter;
import com.alibaba.excel.converters.byteconverter.ByteNumberConverter;
import com.alibaba.excel.converters.byteconverter.ByteStringConverter;
import com.alibaba.excel.converters.date.DateDateConverter;
import com.alibaba.excel.converters.date.DateNumberConverter;
import com.alibaba.excel.converters.date.DateStringConverter;
import com.alibaba.excel.converters.doubleconverter.DoubleBooleanConverter;
@ -38,6 +39,7 @@ import com.alibaba.excel.converters.string.StringErrorConverter;
import com.alibaba.excel.converters.string.StringNumberConverter;
import com.alibaba.excel.converters.string.StringStringConverter;
import com.alibaba.excel.converters.url.UrlImageConverter;
import com.alibaba.excel.util.MapUtils;
/**
* Load default handler
@ -45,8 +47,8 @@ import com.alibaba.excel.converters.url.UrlImageConverter;
* @author Jiaju Zhuang
*/
public class DefaultConverterLoader {
private static Map<String, Converter> defaultWriteConverter;
private static Map<String, Converter> allConverter;
private static Map<String, Converter<?>> defaultWriteConverter;
private static Map<String, Converter<?>> allConverter;
static {
initDefaultWriteConverter();
@ -54,7 +56,7 @@ public class DefaultConverterLoader {
}
private static void initAllConverter() {
allConverter = new HashMap<String, Converter>(64);
allConverter = MapUtils.newHashMapWithExpectedSize(40);
putAllConverter(new BigDecimalBooleanConverter());
putAllConverter(new BigDecimalNumberConverter());
putAllConverter(new BigDecimalStringConverter());
@ -94,14 +96,16 @@ public class DefaultConverterLoader {
putAllConverter(new StringNumberConverter());
putAllConverter(new StringStringConverter());
putAllConverter(new StringErrorConverter());
putAllConverter(new BigIntegerStringConverter());
}
private static void initDefaultWriteConverter() {
defaultWriteConverter = new HashMap<String, Converter>(32);
defaultWriteConverter = MapUtils.newHashMapWithExpectedSize(40);
putWriteConverter(new BigDecimalNumberConverter());
putWriteConverter(new BooleanBooleanConverter());
putWriteConverter(new ByteNumberConverter());
putWriteConverter(new DateStringConverter());
putWriteConverter(new DateDateConverter());
putWriteConverter(new DoubleNumberConverter());
putWriteConverter(new FloatNumberConverter());
putWriteConverter(new IntegerNumberConverter());
@ -113,6 +117,19 @@ public class DefaultConverterLoader {
putWriteConverter(new ByteArrayImageConverter());
putWriteConverter(new BoxingByteArrayImageConverter());
putWriteConverter(new UrlImageConverter());
// In some cases, it must be converted to string
putWriteStringConverter(new BigDecimalStringConverter());
putWriteStringConverter(new BooleanStringConverter());
putWriteStringConverter(new ByteStringConverter());
putWriteStringConverter(new DateStringConverter());
putWriteStringConverter(new DoubleStringConverter());
putWriteStringConverter(new FloatStringConverter());
putWriteStringConverter(new IntegerStringConverter());
putWriteStringConverter(new LongStringConverter());
putWriteStringConverter(new ShortStringConverter());
putWriteStringConverter(new StringStringConverter());
putWriteStringConverter(new BigIntegerStringConverter());
}
/**
@ -120,20 +137,25 @@ public class DefaultConverterLoader {
*
* @return
*/
public static Map<String, Converter> loadDefaultWriteConverter() {
public static Map<String, Converter<?>> loadDefaultWriteConverter() {
return defaultWriteConverter;
}
private static void putWriteConverter(Converter converter) {
private static void putWriteConverter(Converter<?> 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
*
* @return
*/
public static Map<String, Converter> loadDefaultReadConverter() {
public static Map<String, Converter<?>> loadDefaultReadConverter() {
return loadAllConverter();
}
@ -142,11 +164,11 @@ public class DefaultConverterLoader {
*
* @return
*/
public static Map<String, Converter> loadAllConverter() {
public static Map<String, Converter<?>> loadAllConverter() {
return allConverter;
}
private static void putAllConverter(Converter converter) {
private static void putAllConverter(Converter<?> converter) {
allConverter.put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey(), converter.supportExcelTypeKey()),
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.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
@ -16,7 +17,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class BigDecimalBooleanConverter implements Converter<BigDecimal> {
@Override
public Class supportJavaTypeKey() {
public Class<BigDecimal> supportJavaTypeKey() {
return BigDecimal.class;
}
@ -26,7 +27,7 @@ public class BigDecimalBooleanConverter implements Converter<BigDecimal> {
}
@Override
public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
public BigDecimal convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (cellData.getBooleanValue()) {
return BigDecimal.ONE;
@ -35,12 +36,12 @@ public class BigDecimalBooleanConverter implements Converter<BigDecimal> {
}
@Override
public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (BigDecimal.ONE.equals(value)) {
return new CellData(Boolean.TRUE);
return new WriteCellData<>(Boolean.TRUE);
}
return new CellData(Boolean.FALSE);
return new WriteCellData<>(Boolean.FALSE);
}
}

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

42
src/main/java/com/alibaba/excel/converters/biginteger/BigIntegerStringConverter.java

@ -0,0 +1,42 @@
package com.alibaba.excel.converters.biginteger;
import java.math.BigInteger;
import java.text.ParseException;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
/**
* BigDecimal and string converter
*
* @author Jiaju Zhuang
*/
public class BigIntegerStringConverter implements Converter<BigInteger> {
@Override
public Class<BigInteger> supportJavaTypeKey() {
return BigInteger.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public BigInteger convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseBigDecimal(cellData.getStringValue(), contentProperty).toBigInteger();
}
@Override
public WriteCellData<?> convertToExcelData(BigInteger value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return NumberUtils.formatToCellData(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.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
@ -14,7 +15,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class BooleanBooleanConverter implements Converter<Boolean> {
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return Boolean.class;
}
@ -24,15 +25,15 @@ public class BooleanBooleanConverter implements Converter<Boolean> {
}
@Override
public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
public Boolean convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return cellData.getBooleanValue();
}
@Override
public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(Boolean value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return new CellData(value);
return new WriteCellData<>(value);
}
}

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

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

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

@ -1,9 +1,8 @@
package com.alibaba.excel.converters.bytearray;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
@ -13,29 +12,18 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
*/
public class BoxingByteArrayImageConverter implements Converter<Byte[]> {
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return Byte[].class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.IMAGE;
}
@Override
public Byte[] convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
throw new UnsupportedOperationException("Cannot convert images to byte arrays");
}
@Override
public CellData convertToExcelData(Byte[] value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(Byte[] value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
byte[] byteValue = new byte[value.length];
for (int i = 0; i < value.length; i++) {
byteValue[i] = value[i];
}
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;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
@ -12,26 +11,16 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
* @author Jiaju Zhuang
*/
public class ByteArrayImageConverter implements Converter<byte[]> {
@Override
public Class supportJavaTypeKey() {
return byte[].class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.IMAGE;
}
@Override
public byte[] convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
throw new UnsupportedOperationException("Cannot convert images to byte arrays");
public Class<byte[]> supportJavaTypeKey() {
return byte[].class;
}
@Override
public CellData convertToExcelData(byte[] value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(byte[] value, ExcelContentProperty contentProperty,
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.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
@ -16,7 +17,7 @@ public class ByteBooleanConverter implements Converter<Byte> {
private static final Byte ZERO = (byte)0;
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return Byte.class;
}
@ -26,7 +27,7 @@ public class ByteBooleanConverter implements Converter<Byte> {
}
@Override
public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
public Byte convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (cellData.getBooleanValue()) {
return ONE;
@ -35,12 +36,12 @@ public class ByteBooleanConverter implements Converter<Byte> {
}
@Override
public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(Byte value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (ONE.equals(value)) {
return new CellData(Boolean.TRUE);
return new WriteCellData<>(Boolean.TRUE);
}
return new CellData(Boolean.FALSE);
return new WriteCellData<>(Boolean.FALSE);
}
}

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

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

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

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

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

@ -1,12 +1,12 @@
package com.alibaba.excel.converters.doubleconverter;
import java.math.BigDecimal;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
/**
* Double and number converter
@ -16,7 +16,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class DoubleNumberConverter implements Converter<Double> {
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return Double.class;
}
@ -26,15 +26,14 @@ public class DoubleNumberConverter implements Converter<Double> {
}
@Override
public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
public Double convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return cellData.getNumberValue().doubleValue();
}
@Override
public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(Double value, ExcelContentProperty contentProperty,
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.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
@ -17,7 +18,7 @@ import com.alibaba.excel.util.NumberUtils;
public class DoubleStringConverter implements Converter<Double> {
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return Double.class;
}
@ -27,14 +28,14 @@ public class DoubleStringConverter implements Converter<Double> {
}
@Override
public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
public Double convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseDouble(cellData.getStringValue(), contentProperty);
}
@Override
public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(Double value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return NumberUtils.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 com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.FileUtils;
@ -17,25 +16,13 @@ import com.alibaba.excel.util.FileUtils;
*/
public class FileImageConverter implements Converter<File> {
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return File.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.IMAGE;
}
@Override
public File convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
throw new UnsupportedOperationException("Cannot convert images to file");
}
@Override
public CellData convertToExcelData(File value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(File value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws IOException {
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.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
@ -16,7 +17,7 @@ public class FloatBooleanConverter implements Converter<Float> {
private static final Float ZERO = (float)0.0;
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return Float.class;
}
@ -26,7 +27,7 @@ public class FloatBooleanConverter implements Converter<Float> {
}
@Override
public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
public Float convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (cellData.getBooleanValue()) {
return ONE;
@ -35,12 +36,12 @@ public class FloatBooleanConverter implements Converter<Float> {
}
@Override
public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(Float value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (ONE.equals(value)) {
return new CellData(Boolean.TRUE);
return new WriteCellData<>(Boolean.TRUE);
}
return new CellData(Boolean.FALSE);
return new WriteCellData<>(Boolean.FALSE);
}
}

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

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

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.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
@ -17,7 +18,7 @@ import com.alibaba.excel.util.NumberUtils;
public class FloatStringConverter implements Converter<Float> {
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return Float.class;
}
@ -27,14 +28,14 @@ public class FloatStringConverter implements Converter<Float> {
}
@Override
public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
public Float convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseFloat(cellData.getStringValue(), contentProperty);
}
@Override
public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(Float value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return NumberUtils.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 com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.IoUtils;
@ -17,25 +16,14 @@ import com.alibaba.excel.util.IoUtils;
*/
public class InputStreamImageConverter implements Converter<InputStream> {
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return InputStream.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.IMAGE;
}
@Override
public InputStream convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
throw new UnsupportedOperationException("Cannot convert images to input stream");
}
@Override
public CellData convertToExcelData(InputStream value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(InputStream value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws IOException {
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.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
@ -16,7 +17,7 @@ public class IntegerBooleanConverter implements Converter<Integer> {
private static final Integer ZERO = 0;
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return Integer.class;
}
@ -26,7 +27,7 @@ public class IntegerBooleanConverter implements Converter<Integer> {
}
@Override
public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (cellData.getBooleanValue()) {
return ONE;
@ -35,12 +36,12 @@ public class IntegerBooleanConverter implements Converter<Integer> {
}
@Override
public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (ONE.equals(value)) {
return new CellData(Boolean.TRUE);
return new WriteCellData<>(Boolean.TRUE);
}
return new CellData(Boolean.FALSE);
return new WriteCellData<>(Boolean.FALSE);
}
}

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

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

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

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

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

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

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

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

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.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;
@ -17,7 +18,7 @@ import com.alibaba.excel.util.NumberUtils;
public class ShortStringConverter implements Converter<Short> {
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return Short.class;
}
@ -27,14 +28,14 @@ public class ShortStringConverter implements Converter<Short> {
}
@Override
public Short convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
public Short convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseShort(cellData.getStringValue(), contentProperty);
}
@Override
public CellData convertToExcelData(Short value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(Short value, ExcelContentProperty contentProperty,
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.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
/**
@ -14,7 +15,7 @@ import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class StringBooleanConverter implements Converter<String> {
@Override
public Class supportJavaTypeKey() {
public Class<?> supportJavaTypeKey() {
return String.class;
}
@ -24,15 +25,15 @@ public class StringBooleanConverter implements Converter<String> {
}
@Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return cellData.getBooleanValue().toString();
}
@Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return new CellData(Boolean.valueOf(value));
return new WriteCellData<>(Boolean.valueOf(value));
}
}

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

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

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

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

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

@ -3,45 +3,40 @@ package com.alibaba.excel.converters.url;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.IoUtils;
/**
* Url and image converter
*
* @since 2.1.1
* @author Jiaju Zhuang
* @since 2.1.1
*/
public class UrlImageConverter implements Converter<URL> {
@Override
public Class supportJavaTypeKey() {
return URL.class;
}
public static int urlConnectTimeout = 1000;
public static int urlReadTimeout = 5000;
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.IMAGE;
}
@Override
public URL convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
throw new UnsupportedOperationException("Cannot convert images to url.");
public Class<?> supportJavaTypeKey() {
return URL.class;
}
@Override
public CellData convertToExcelData(URL value, ExcelContentProperty contentProperty,
public WriteCellData<?> convertToExcelData(URL value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws IOException {
InputStream inputStream = null;
try {
inputStream = value.openStream();
URLConnection urlConnection = value.openConnection();
urlConnection.setConnectTimeout(urlConnectTimeout);
urlConnection.setReadTimeout(urlReadTimeout);
inputStream = urlConnection.getInputStream();
byte[] bytes = IoUtils.toByteArray(inputStream);
return new CellData(bytes);
return new WriteCellData<>(bytes);
} finally {
if (inputStream != null) {
inputStream.close();

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

@ -37,11 +37,17 @@ public enum CellDataTypeEnum {
*/
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);
static {
TYPE_ROUTING_MAP.put("s", 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
*
* @author jipengfei
* @deprecated Use directly {@link ReadListener}
*/
@Deprecated
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
*
* @param extra
* extra information
* @param context
* analysis context
* @param extra extra information
* @param context analysis context
*/
@Override
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 com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ConverterUtils;
@ -16,7 +16,7 @@ import com.alibaba.excel.util.ConverterUtils;
public abstract class AnalysisEventListener<T> implements ReadListener<T> {
@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);
}

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

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

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;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import lombok.Data;
/**
* Data convert exception
*
* @author Jiaju Zhuang
*/
@Data
public class ExcelDataConvertException extends RuntimeException {
/**
* NotNull.
@ -21,7 +24,7 @@ public class ExcelDataConvertException extends RuntimeException {
/**
* NotNull.
*/
private CellData cellData;
private CellData<?> cellData;
/**
* Nullable.Only when the header is configured and when the class header is used is not null.
*
@ -47,35 +50,4 @@ public class ExcelDataConvertException extends RuntimeException {
this.excelContentProperty = excelContentProperty;
}
public Integer getRowIndex() {
return rowIndex;
}
public void setRowIndex(Integer rowIndex) {
this.rowIndex = rowIndex;
}
public Integer getColumnIndex() {
return columnIndex;
}
public void setColumnIndex(Integer columnIndex) {
this.columnIndex = columnIndex;
}
public ExcelContentProperty getExcelContentProperty() {
return excelContentProperty;
}
public void setExcelContentProperty(ExcelContentProperty excelContentProperty) {
this.excelContentProperty = excelContentProperty;
}
public CellData getCellData() {
return cellData;
}
public void setCellData(CellData cellData) {
this.cellData = cellData;
}
}

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

@ -1,10 +1,13 @@
package com.alibaba.excel.metadata;
import lombok.Data;
/**
* cell
*
* @author Jiaju Zhuang
**/
@Data
public class AbstractCell implements Cell {
/**
* Row index
@ -14,20 +17,4 @@ public class AbstractCell implements Cell {
* Column index
*/
private Integer columnIndex;
public Integer getRowIndex() {
return rowIndex;
}
public void setRowIndex(Integer rowIndex) {
this.rowIndex = rowIndex;
}
public Integer getColumnIndex() {
return columnIndex;
}
public void setColumnIndex(Integer columnIndex) {
this.columnIndex = columnIndex;
}
}

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

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

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

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

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

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

@ -5,11 +5,14 @@ import java.util.Locale;
import com.alibaba.excel.converters.Converter;
import lombok.Data;
/**
* Basic parameter
*
* @author Jiaju Zhuang
**/
@Data
public class BasicParameter {
/**
* You can only choose one of the {@link BasicParameter#head} and {@link BasicParameter#clazz}
@ -18,11 +21,11 @@ public class BasicParameter {
/**
* You can only choose one of the {@link BasicParameter#head} and {@link BasicParameter#clazz}
*/
private Class clazz;
private Class<?> clazz;
/**
* Custom type conversions override the default
*/
private List<Converter> customConverterList;
private List<Converter<?>> customConverterList;
/**
* Automatic trim includes sheet name and content
*/
@ -41,51 +44,10 @@ public class BasicParameter {
*/
private Locale locale;
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;
}
/**
* Whether to use scientific Format.
*
* default is false
*/
private Boolean 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;
}
}
}

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

@ -20,19 +20,19 @@ public class CellExtra extends AbstractCell {
*/
private String text;
/**
* First row index,if this object is an interval
* First row index, if this object is an interval
*/
private Integer firstRowIndex;
/**
* Last row index,if this object is an interval
* Last row index, if this object is an interval
*/
private Integer lastRowIndex;
/**
* First column index,if this object is an interval
* First column index, if this object is an interval
*/
private Integer firstColumnIndex;
/**
* Last column index,if this object is an interval
* Last column index, if this object is an interval
*/
private Integer lastColumnIndex;

35
src/main/java/com/alibaba/excel/metadata/CellRange.java

@ -1,8 +1,11 @@
package com.alibaba.excel.metadata;
import lombok.Data;
/**
* @author jipengfei
*/
@Data
public class CellRange {
private int firstRow;
@ -16,36 +19,4 @@ public class CellRange {
this.firstCol = firstCol;
this.lastCol = lastCol;
}
public int getFirstRow() {
return firstRow;
}
public void setFirstRow(int firstRow) {
this.firstRow = firstRow;
}
public int getLastRow() {
return lastRow;
}
public void setLastRow(int lastRow) {
this.lastRow = lastRow;
}
public int getFirstCol() {
return firstCol;
}
public void setFirstCol(int firstCol) {
this.firstCol = firstCol;
}
public int getLastCol() {
return lastCol;
}
public void setLastCol(int lastCol) {
this.lastCol = lastCol;
}
}

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

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

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

Loading…
Cancel
Save