未验证 提交 a0a08ca9 编写于 作者: 庄家钜's avatar 庄家钜 提交者: GitHub

Merge pull request #2077 from alibaba/developing

Developing
......@@ -3,6 +3,7 @@
## 提前沟通
尽量把自己的想法和实现思路提前沟通,可以通过issue,钉钉,QQ都可以,可能很多问题我们内部已经讨论过,由于各种原因后续不会支持,但是您这边又开发好了,这样容易浪费您的时间。
## 代码规范
请先安装阿里巴巴代码规约插件!!!https://plugins.jetbrains.com/plugin/10046-alibaba-java-coding-guidelines
目前代码规范已经集成了自动校验,然后源代码尽量不要有中文注释。在新增功能的时候,尽量注意补充junit。core代表每次travis-ci都会跑的测试案例,然后demo用于对外看到,temp里面随便写。
## 提交分支
建议提交到最新的版本号.x上面,比如 3.x之类的版本,为了方便其他同学阅读源代码,所以目前的思路是master和maven center的最新版本代码保持一致,然后您提交过来的代码我们可能会稍微做一些修改。所以提交到开发分支会比较好。fork也可以直接fork该分支。
......@@ -18,12 +18,32 @@ EasyExcel
#### 因为公司不方便用QQ,所以建议加钉钉群
# JAVA解析Excel工具EasyExcel
Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,能够原本一个3M的excel用POI sax依然需要100M左右内存降低到几M,并且再大的excel不会出现内存溢出,03版依赖POI的sax模式。在上层做了模型转换的封装,让使用者更加简单方便
Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,改用easyexcel可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便
## 64M内存1分钟内读取75M(46W行25列)的Excel
当然还有速模式能更快,但是内存占用会在100M多一点
当然还有速模式能更快,但是内存占用会在100M多一点
![img](img/readme/large.png)
## 版本支持
* 2+ 版本支持 Java7和Java6
* 3+ 版本至少 Java8
### 关于版本升级
* 不建议夸大版本升级 尤其夸2个大版本
* 2+ 升级到 3+
* 使用了自定义拦截器去修改样式的会出问题
* 读的时候`invoke`里面抛出异常,不会再额外封装一层`ExcelAnalysisException`
* 大版本升级后建议相关内容重新测试下
## 人员招募
由于工作较忙,有意愿做开源的同学可以报名,主要负责群里回答&issue处理,当然也可以做一些PR.
由于开源没有任何物质回报,然后现在的维护同学也是课余时间维护的,所以想加入的同学需要持之以恒,而不是一时兴起.
要求如下:
* 有一定java编码能力 & 良好的编码习惯
* 了解easyexcel 读&写的原理
* 热爱开源项目
* 能长期坚持的去做
* 相对工作没那么忙
## 相关文档
* [快速开始](https://www.yuque.com/easyexcel/doc/easyexcel)
* [关于软件](/abouteasyexcel.md)
......@@ -83,7 +103,7 @@ DEMO代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/ja
@GetMapping("download")
public void download(HttpServletResponse response) throws IOException {
// 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
response.setContentType("application/vnd.ms-excel");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
......
lombok.toString.callSuper = CALL
lombok.equalsAndHashCode.callSuper= CALL
\ No newline at end of file
......@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.11</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,68 +60,74 @@
<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>
<artifactId>slf4j-api</artifactId>
<version>1.7.26</version>
<version>1.7.32</version>
</dependency>
<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>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.71</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<version>1.2.78</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>1.5.21.RELEASE</version>
<version>2.5.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.21.RELEASE</version>
<version>2.5.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
......@@ -162,8 +168,11 @@
<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>
<exclude>com/alibaba/excel/metadata/csv/CsvDataFormat.java</exclude>
<exclude>com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java</exclude>
</excludes>
</configuration>
<executions>
......@@ -186,14 +195,16 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1</version>
<version>3.2.1</version>
<configuration>
<attach>true</attach>
</configuration>
......@@ -232,6 +243,30 @@
</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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<includes>
<include>com/alibaba/easyexcel/test/core/**/*.java</include>
</includes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</project>
......@@ -3,17 +3,10 @@ package com.alibaba.excel;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.event.WriteHandler;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterTableBuilder;
......@@ -39,138 +32,6 @@ import com.alibaba.excel.write.builder.ExcelWriterTableBuilder;
*/
public class EasyExcelFactory {
/**
* Quickly read small files,no more than 10,000 lines.
*
* @param in
* the POI filesystem that contains the Workbook stream.
* @param sheet
* read sheet.
* @return analysis result.
* @deprecated please use 'EasyExcel.read(in).sheet(sheetNo).doReadSync();'
*/
@Deprecated
public static List<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 null(the template POI filesystem that contains the Workbook
* stream)
* @param outputStream
* the java OutputStream you wish to write the value to
* @param typeEnum
* 03 or 07
* @param needHead
* Whether a write header is required
* @return new ExcelWriter
* @deprecated please use {@link EasyExcel#write()}
*/
@Deprecated
public static ExcelWriter getWriterWithTemp(InputStream temp, OutputStream outputStream, ExcelTypeEnum typeEnum,
boolean needHead) {
return write().withTemplate(temp).file(outputStream).excelType(typeEnum).needHead(needHead)
.autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build();
}
/**
* Get ExcelWriter with a template file
*
* @param temp
* Append value after a POI file , Can be null(the template POI filesystem that contains the Workbook
* stream)
* @param outputStream
* the java OutputStream you wish to write the value to
* @param typeEnum
* 03 or 07
* @param needHead
* Whether a write header is required
* @param handler
* User-defined callback
* @return new ExcelWriter
* @deprecated please use {@link EasyExcel#write()}
*/
@Deprecated
public static ExcelWriter getWriterWithTempAndHandler(InputStream temp, OutputStream outputStream,
ExcelTypeEnum typeEnum, boolean needHead, WriteHandler handler) {
return write().withTemplate(temp).file(outputStream).excelType(typeEnum).needHead(needHead)
.registerWriteHandler(handler).autoCloseStream(Boolean.FALSE).convertAllFiled(Boolean.FALSE).build();
}
/**
* Build excel the write
......
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 sheet,SheetNo start from 1
*
* @param sheet
* Read sheet
* @deprecated please us {@link #read(ReadSheet...)}
*/
@Deprecated
public void read(Sheet sheet) {
ReadSheet readSheet = null;
if (sheet != null) {
readSheet = new ReadSheet();
readSheet.setSheetNo(sheet.getSheetNo() - 1);
readSheet.setSheetName(sheet.getSheetName());
readSheet.setClazz(sheet.getClazz());
readSheet.setHead(sheet.getHead());
readSheet.setHeadRowNumber(sheet.getHeadLineMun());
}
read(readSheet);
}
/**
* Parse the specified sheet
*
* @param sheet
* Read sheet
* @param clazz
* object parsed into each row of value
*
* @deprecated Set the class in the sheet before read
*/
@Deprecated
public void read(Sheet sheet, Class clazz) {
if (sheet != null) {
sheet.setClazz(clazz);
}
read(sheet);
}
/**
* Context for the entire execution process
......@@ -240,28 +87,6 @@ public class ExcelReader {
return excelAnalyser.excelExecutor();
}
/**
* Parse the workBook get all sheets
*
* @return workBook all sheets
*
* @deprecated please use {@link #excelExecutor()}
*/
@Deprecated
public List<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
......
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 java.util.function.Supplier;
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.
......@@ -48,117 +40,50 @@ public class ExcelWriter {
}
/**
* 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
* Write data to a sheet
*
* @param templateInputStream
* Append value after a POI file ,Can be null(the template POI filesystem that contains the Workbook
* stream)
* @param outputStream
* the java OutputStream you wish to write the value to
* @param typeEnum
* 03 or 07
* @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter
* @param data Data to be written
* @param writeSheet Write to this sheet
* @return this current writer
*/
@Deprecated
public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum,
Boolean needHead) {
this(templateInputStream, outputStream, typeEnum, needHead, null);
public ExcelWriter write(Collection<?> data, WriteSheet writeSheet) {
return write(data, writeSheet, null);
}
/**
* Create new writer
* Write data to a sheet
*
* @param templateInputStream
* Append value after a POI file ,Can be null(the template POI filesystem that contains the Workbook
* stream)
* @param outputStream
* the java OutputStream you wish to write the value to
* @param typeEnum
* 03 or 07
* @param writeHandler
* User-defined callback
* @deprecated please use {@link com.alibaba.excel.write.builder.ExcelWriterBuilder} build ExcelWriter
*/
@Deprecated
public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum,
Boolean needHead, WriteHandler writeHandler) {
List<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
* @param supplier Data to be written
* @param writeSheet Write to this sheet
* @return this current writer
*/
@Deprecated
public ExcelWriter(GenerateParam generateParam) {
this(generateParam.getOutputStream(), generateParam.getType(), true);
public ExcelWriter write(Supplier<Collection<?>> supplier, WriteSheet writeSheet) {
return write(supplier.get(), writeSheet, null);
}
/**
* Write data to a sheet
* Write value to a sheet
*
* @param data
* Data to be written
* @param writeSheet
* Write to this sheet
* @return this current writer
* @param data Data to be written
* @param writeSheet Write to this sheet
* @param writeTable Write to this table
* @return this
*/
public ExcelWriter write(List data, WriteSheet writeSheet) {
return write(data, writeSheet, null);
public ExcelWriter write(Collection<?> data, WriteSheet writeSheet, WriteTable writeTable) {
excelBuilder.addContent(data, writeSheet, writeTable);
return this;
}
/**
* Write value to a sheet
*
* @param data
* Data to be written
* @param writeSheet
* Write to this sheet
* @param writeTable
* Write to this table
* @param supplier Data to be written
* @param writeSheet Write to this sheet
* @param writeTable Write to this table
* @return this
*/
public ExcelWriter write(List data, WriteSheet writeSheet, WriteTable writeTable) {
excelBuilder.addContent(data, writeSheet, writeTable);
public ExcelWriter write(Supplier<Collection<?>> supplier, WriteSheet writeSheet, WriteTable writeTable) {
excelBuilder.addContent(supplier.get(), writeSheet, writeTable);
return this;
}
......@@ -187,137 +112,26 @@ public class ExcelWriter {
}
/**
* 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
* Fill 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)}
* @param supplier
* @param writeSheet
* @return
*/
@Deprecated
public ExcelWriter write1(List data, Sheet sheet, Table table) {
return write(data, sheet, table);
public ExcelWriter fill(Supplier<Object> supplier, WriteSheet writeSheet) {
return fill(supplier.get(), null, writeSheet);
}
/**
* Merge Cells,Indexes are zero-based.
* Fill value to a sheet
*
* @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}
* @param supplier
* @param fillConfig
* @param writeSheet
* @return
*/
@Deprecated
public ExcelWriter merge(int firstRow, int lastRow, int firstCol, int lastCol) {
excelBuilder.merge(firstRow, lastRow, firstCol, lastCol);
public ExcelWriter fill(Supplier<Object> supplier, FillConfig fillConfig, WriteSheet writeSheet) {
excelBuilder.fill(supplier.get(), fillConfig, writeSheet);
return this;
}
......@@ -332,7 +146,6 @@ public class ExcelWriter {
/**
* Prevents calls to {@link #finish} from freeing the cache
*
*/
@Override
protected void finalize() {
......
......@@ -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;
}
......
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);
}
}
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()));
}
}
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);
}
}
......@@ -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()));
}
}
}
......@@ -3,36 +3,36 @@ package com.alibaba.excel.analysis.v03.handlers;
import java.math.BigDecimal;
import java.util.Map;
import com.alibaba.excel.enums.RowTypeEnum;
import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.ss.usermodel.CellType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.analysis.v03.IgnorableXlsRecordHandler;
import com.alibaba.excel.constant.BuiltinFormats;
import com.alibaba.excel.context.xls.XlsReadContext;
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());
......@@ -41,10 +41,11 @@ public class FormulaRecordHandler extends AbstractXlsRecordHandler implements Ig
formulaValue = HSSFFormulaParser.toFormulaString(xlsReadContext.xlsReadWorkbookHolder().getHssfWorkbook(),
frec.getParsedExpression());
} catch (Exception e) {
LOGGER.debug("Get formula value error.", e);
log.debug("Get formula value error.", e);
}
tempCellData.setFormula(Boolean.TRUE);
tempCellData.setFormulaValue(formulaValue);
FormulaData formulaData = new FormulaData();
formulaData.setFormulaValue(formulaValue);
tempCellData.setFormulaData(formulaData);
xlsReadContext.xlsReadSheetHolder().setTempRowType(RowTypeEnum.DATA);
switch (cellType) {
case STRING:
......@@ -56,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);
......
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);
}
}
......@@ -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);
}
}
......@@ -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);
}
......
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()));
}
}
......@@ -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;
......
......@@ -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);
}
......
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
......
......@@ -6,12 +6,14 @@ 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.BooleanUtils;
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;
......@@ -30,37 +32,42 @@ 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,but does not need to be read in the 'sharedStrings.xml'
// 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
String dateFormatIndex = attributes.getValue(ExcelXmlConstants.ATTRIBUTE_S);
Integer dateFormatIndexInteger;
int dateFormatIndexInteger;
if (StringUtils.isEmpty(dateFormatIndex)) {
dateFormatIndexInteger = DEFAULT_FORMAT_INDEX;
} 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);
}
@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();
......@@ -101,7 +108,7 @@ public class CellTagHandler extends AbstractXlsxTagHandler {
if (tempCellData.getStringValue() != null
&& xlsxReadContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
tempCellData.setStringValue(tempCellData.getStringValue());
tempCellData.setStringValue(tempCellData.getStringValue().trim());
}
tempCellData.checkEmpty();
......
package com.alibaba.excel.analysis.v07.handlers;
import org.xml.sax.Attributes;
import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.util.PositionUtils;
import org.xml.sax.Attributes;
/**
* Cell Handler
......@@ -15,9 +16,8 @@ public class CountTagHandler extends AbstractXlsxTagHandler {
@Override
public void startElement(XlsxReadContext xlsxReadContext, String name, Attributes attributes) {
String d = attributes.getValue(ExcelXmlConstants.ATTRIBUTE_REF);
String totalStr = d.substring(d.indexOf(":") + 1, d.length());
String c = totalStr.toUpperCase().replaceAll("[A-Z]", "");
xlsxReadContext.readSheetHolder().setApproximateTotalRowNumber(Integer.parseInt(c));
String totalStr = d.substring(d.indexOf(":") + 1);
xlsxReadContext.readSheetHolder().setApproximateTotalRowNumber(PositionUtils.getRow(totalStr) + 1);
}
}
......@@ -2,17 +2,17 @@ package com.alibaba.excel.analysis.v07.handlers;
import java.util.LinkedHashMap;
import org.xml.sax.Attributes;
import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.RowTypeEnum;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadSheetHolder;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.PositionUtils;
import org.apache.commons.collections4.MapUtils;
import org.xml.sax.Attributes;
/**
* Cell Handler
*
......@@ -40,13 +40,12 @@ public class RowTagHandler extends AbstractXlsxTagHandler {
@Override
public void endElement(XlsxReadContext xlsxReadContext, String name) {
XlsxReadSheetHolder xlsxReadSheetHolder = xlsxReadContext.xlsxReadSheetHolder();
RowTypeEnum rowType =
CollectionUtils.isEmpty(xlsxReadSheetHolder.getCellMap()) ? RowTypeEnum.EMPTY : RowTypeEnum.DATA;
RowTypeEnum rowType = MapUtils.isEmpty(xlsxReadSheetHolder.getCellMap()) ? RowTypeEnum.EMPTY : RowTypeEnum.DATA;
xlsxReadContext.readRowHolder(new ReadRowHolder(xlsxReadSheetHolder.getRowIndex(), rowType,
xlsxReadSheetHolder.getGlobalConfiguration(), xlsxReadSheetHolder.getCellMap()));
xlsxReadContext.analysisEventProcessor().endRow(xlsxReadContext);
xlsxReadSheetHolder.setColumnIndex(null);
xlsxReadSheetHolder.setCellMap(new LinkedHashMap<Integer, Cell>());
xlsxReadSheetHolder.setCellMap(new LinkedHashMap<>());
}
}
......@@ -3,10 +3,6 @@ package com.alibaba.excel.analysis.v07.handlers.sax;
import java.util.HashMap;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.alibaba.excel.analysis.v07.handlers.CellFormulaTagHandler;
import com.alibaba.excel.analysis.v07.handlers.CellInlineStringValueTagHandler;
import com.alibaba.excel.analysis.v07.handlers.CellTagHandler;
......@@ -19,9 +15,15 @@ import com.alibaba.excel.analysis.v07.handlers.XlsxTagHandler;
import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import lombok.extern.slf4j.Slf4j;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* @author jipengfei
*/
@Slf4j
public class XlsxRowHandler extends DefaultHandler {
private XlsxReadContext xlsxReadContext;
private static final Map<String, XlsxTagHandler> XLSX_CELL_HANDLER_MAP = new HashMap<String, XlsxTagHandler>(32);
......
......@@ -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,7 +32,7 @@ public @interface ExcelProperty {
/**
* Index of column
*
* Read or write it on the index of column,If it's equal to -1, it's sorted by Java class.
* Read or write it on the index of column, If it's equal to -1, it's sorted by Java class.
*
* priority: index &gt; order &gt; default sort
*
......
......@@ -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
......
......@@ -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
......
......@@ -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;
......
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);
}
}
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
......
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;
}
}
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;
}
......@@ -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
......
......@@ -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();
......
......@@ -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
......@@ -138,7 +139,7 @@ public class WriteContextImpl implements WriteContext {
return false;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sheet:{} is already existed", writeSheet.getSheetNo());
LOGGER.debug("Sheet:{},{} is already existed", writeSheet.getSheetNo(), writeSheet.getSheetName());
}
writeSheetHolder.setNewInitialization(Boolean.FALSE);
writeTableHolder = null;
......@@ -178,8 +179,12 @@ public class WriteContextImpl implements WriteContext {
writeSheetHolder
.setCachedSheet(writeWorkbookHolder.getCachedWorkbook().getSheet(writeSheetHolder.getSheetName()));
}
} catch (Exception e) {
currentSheet = createSheet();
} catch (IllegalArgumentException e) {
if (e.getMessage() != null && e.getMessage().contains(NO_SHEETS)) {
currentSheet = createSheet();
} else {
throw e;
}
}
if (currentSheet == null) {
currentSheet = createSheet();
......@@ -240,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);
}
}
......@@ -280,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()) {
......@@ -346,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;
......@@ -426,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);
......@@ -441,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!");
}
......@@ -467,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();
}
}
}
......@@ -487,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;
}
......
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();
}
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();
}
}
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> {
}
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());
}
}
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;
}
}
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.BigIntegerBooleanConverter;
import com.alibaba.excel.converters.biginteger.BigIntegerNumberConverter;
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 +16,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;
......@@ -27,6 +30,9 @@ import com.alibaba.excel.converters.inputstream.InputStreamImageConverter;
import com.alibaba.excel.converters.integer.IntegerBooleanConverter;
import com.alibaba.excel.converters.integer.IntegerNumberConverter;
import com.alibaba.excel.converters.integer.IntegerStringConverter;
import com.alibaba.excel.converters.localdatetime.LocalDateNumberConverter;
import com.alibaba.excel.converters.localdatetime.LocalDateTimeDateConverter;
import com.alibaba.excel.converters.localdatetime.LocalDateTimeStringConverter;
import com.alibaba.excel.converters.longconverter.LongBooleanConverter;
import com.alibaba.excel.converters.longconverter.LongNumberConverter;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
......@@ -38,6 +44,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 +52,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,11 +61,15 @@ 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());
putAllConverter(new BigIntegerBooleanConverter());
putAllConverter(new BigIntegerNumberConverter());
putAllConverter(new BigIntegerStringConverter());
putAllConverter(new BooleanBooleanConverter());
putAllConverter(new BooleanNumberConverter());
putAllConverter(new BooleanStringConverter());
......@@ -70,6 +81,9 @@ public class DefaultConverterLoader {
putAllConverter(new DateNumberConverter());
putAllConverter(new DateStringConverter());
putAllConverter(new LocalDateNumberConverter());
putAllConverter(new LocalDateTimeStringConverter());
putAllConverter(new DoubleBooleanConverter());
putAllConverter(new DoubleNumberConverter());
putAllConverter(new DoubleStringConverter());
......@@ -94,14 +108,18 @@ 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 BigIntegerNumberConverter());
putWriteConverter(new BooleanBooleanConverter());
putWriteConverter(new ByteNumberConverter());
putWriteConverter(new DateStringConverter());
putWriteConverter(new DateDateConverter());
putWriteConverter(new LocalDateTimeDateConverter());
putWriteConverter(new DoubleNumberConverter());
putWriteConverter(new FloatNumberConverter());
putWriteConverter(new IntegerNumberConverter());
......@@ -113,6 +131,21 @@ 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 BigIntegerStringConverter());
putWriteStringConverter(new BooleanStringConverter());
putWriteStringConverter(new ByteStringConverter());
putWriteStringConverter(new DateStringConverter());
putWriteStringConverter(new LocalDateTimeStringConverter());
putWriteStringConverter(new DoubleStringConverter());
putWriteStringConverter(new FloatStringConverter());
putWriteStringConverter(new IntegerStringConverter());
putWriteStringConverter(new LongStringConverter());
putWriteStringConverter(new ShortStringConverter());
putWriteStringConverter(new StringStringConverter());
putWriteStringConverter(new BigIntegerStringConverter());
}
/**
......@@ -120,20 +153,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 +180,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);
}
......
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> {
}
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;
}
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;
}
......@@ -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);
}
}
......@@ -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);
}
}
......@@ -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);
}
}
package com.alibaba.excel.converters.biginteger;
import java.math.BigInteger;
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;
/**
* BigInteger and boolean converter
*
* @author Jiaju Zhuang
*/
public class BigIntegerBooleanConverter implements Converter<BigInteger> {
@Override
public Class<BigInteger> supportJavaTypeKey() {
return BigInteger.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.BOOLEAN;
}
@Override
public BigInteger convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (cellData.getBooleanValue()) {
return BigInteger.ONE;
}
return BigInteger.ZERO;
}
@Override
public WriteCellData<?> convertToExcelData(BigInteger value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (BigInteger.ONE.equals(value)) {
return new WriteCellData<>(Boolean.TRUE);
}
return new WriteCellData<>(Boolean.FALSE);
}
}
package com.alibaba.excel.converters.biginteger;
import java.math.BigInteger;
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;
/**
* BigInteger and number converter
*
* @author Jiaju Zhuang
*/
public class BigIntegerNumberConverter implements Converter<BigInteger> {
@Override
public Class<BigInteger> supportJavaTypeKey() {
return BigInteger.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.NUMBER;
}
@Override
public BigInteger convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return cellData.getNumberValue().toBigInteger();
}
@Override
public WriteCellData<?> convertToExcelData(BigInteger value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return NumberUtils.formatToCellData(value, contentProperty);
}
}
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);
}
}
......@@ -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);
}
}
......@@ -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);
}
}
......@@ -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());
}
}
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);
}
}
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);
}
}
......@@ -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);
}
}
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);
}
}
......@@ -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);
}
}
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;
}
}
......@@ -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())));
}
}
......
......@@ -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()));
}
}
}
......@@ -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);
}
}
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);
}
}
......@@ -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);
}
}
......@@ -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));
}
}
......@@ -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);
}
}
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());
}
}
......@@ -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);
}
}
......@@ -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));
}
}
......@@ -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);
}
}
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());
}
}
......@@ -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);
}
}
package com.alibaba.excel.converters.localdatetime;
import java.math.BigDecimal;
import java.time.LocalDateTime;
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 org.apache.poi.ss.usermodel.DateUtil;
/**
* LocalDateTime and number converter
*
* @author Jiaju Zhuang
*/
public class LocalDateNumberConverter implements Converter<LocalDateTime> {
@Override
public Class<?> supportJavaTypeKey() {
return LocalDateTime.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.NUMBER;
}
@Override
public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
return DateUtil.getLocalDateTime(cellData.getNumberValue().doubleValue(),
globalConfiguration.getUse1904windowing());
} else {
return DateUtil.getLocalDateTime(cellData.getNumberValue().doubleValue(),
contentProperty.getDateTimeFormatProperty().getUse1904windowing());
}
}
@Override
public WriteCellData<?> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
return new WriteCellData<>(
BigDecimal.valueOf(DateUtil.getExcelDate(value, globalConfiguration.getUse1904windowing())));
} else {
return new WriteCellData<>(BigDecimal.valueOf(
DateUtil.getExcelDate(value, contentProperty.getDateTimeFormatProperty().getUse1904windowing())));
}
}
}
package com.alibaba.excel.converters.localdatetime;
import java.time.LocalDateTime;
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 LocalDateTimeDateConverter implements Converter<LocalDateTime> {
@Override
public Class<LocalDateTime> supportJavaTypeKey() {
return LocalDateTime.class;
}
@Override
public WriteCellData<?> convertToExcelData(LocalDateTime 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;
}
}
package com.alibaba.excel.converters.localdatetime;
import java.text.ParseException;
import java.time.LocalDateTime;
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.DateUtils;
/**
* LocalDateTime and string converter
*
* @author Jiaju Zhuang
*/
public class LocalDateTimeStringConverter implements Converter<LocalDateTime> {
@Override
public Class<?> supportJavaTypeKey() {
return LocalDateTime.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) throws ParseException {
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
return DateUtils.parseLocalDateTime(cellData.getStringValue(), null, globalConfiguration.getLocale());
} else {
return DateUtils.parseLocalDateTime(cellData.getStringValue(),
contentProperty.getDateTimeFormatProperty().getFormat(), globalConfiguration.getLocale());
}
}
@Override
public WriteCellData<?> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
return new WriteCellData<>(DateUtils.format(value, null, globalConfiguration.getLocale()));
} else {
return new WriteCellData<>(
DateUtils.format(value, contentProperty.getDateTimeFormatProperty().getFormat(),
globalConfiguration.getLocale()));
}
}
}
......@@ -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);
}
}
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());
}
}
......@@ -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);
}
}
......@@ -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);
}
}
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());
}
}
......@@ -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);
}
}
......@@ -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));
}
}
......@@ -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);
}
}
......@@ -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)));
}
}
......@@ -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(), 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));
}
}
......@@ -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);
}
}
......@@ -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();
......
......@@ -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);
......
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,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) {}
......
......@@ -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);
}
......
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;
}
}
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);
}
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;
}
}
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;
}
}
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,19 +54,24 @@ 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 {
......@@ -71,48 +80,8 @@ public abstract class AbstractHolder implements ConfigurationHolder {
}
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();
}
......
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();
......
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;
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册