@ -0,0 +1,15 @@
|
||||
root = true |
||||
|
||||
[*.{groovy, java, kt, xml}] |
||||
#缩进风格:空格 |
||||
indent_style = space |
||||
#缩进大小 |
||||
indent_size = 4 |
||||
#换行符lf |
||||
end_of_line = lf |
||||
#字符集utf-8 |
||||
charset = utf-8 |
||||
#是否删除行尾的空格 |
||||
trim_trailing_whitespace = true |
||||
#是否在文件的最后插入一个空行 |
||||
insert_final_newline = true |
@ -0,0 +1,2 @@
|
||||
distributionUrl=https://mirrors.tuna.tsinghua.edu.cn/apache/maven/maven-3/3.5.4/binaries/apache-maven-3.5.4-bin.zip |
||||
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.3/maven-wrapper-0.5.3.jar |
@ -0,0 +1,10 @@
|
||||
language: java |
||||
jdk: openjdk8 |
||||
cache: |
||||
directories: |
||||
- $HOME/.m2 |
||||
before_install: |
||||
- chmod +x mvnw |
||||
install: |
||||
- ./mvnw install -Dgpg.skip -B -V -Dmaven.test.skip=true |
||||
- ./mvnw javadoc:javadoc |
@ -1,150 +1,89 @@
|
||||
easyexcel |
||||
====================== |
||||
[![Build Status](https://travis-ci.org/alibaba/easyexcel.svg?branch=master)](https://travis-ci.org/alibaba/easyexcel) |
||||
[![Maven central](https://maven-badges.herokuapp.com/maven-central/com.alibaba/easyexcel/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.alibaba/easyexcel) |
||||
[![License](http://img.shields.io/:license-apache-brightgreen.svg)](http://www.apache.org/licenses/LICENSE-2.0.html) |
||||
|
||||
[QQ群:662022184](//shang.qq.com/wpa/qunwpa?idkey=53d9d821b0833e3c14670f007488a61e300f00ff4f1b81fd950590d90dd80f80) |
||||
|
||||
# JAVA解析Excel工具easyexcel |
||||
Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,能够原本一个3M的excel用POI sax依然需要100M左右内存降低到KB级别,并且再大的excel不会出现内存溢出,03版依赖POI的sax模式。在上层做了模型转换的封装,让使用者更加简单方便 |
||||
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模式。在上层做了模型转换的封装,让使用者更加简单方便 |
||||
## 相关文档 |
||||
* [关于软件](/abouteasyexcel.md) |
||||
* [快速使用](/quickstart.md) |
||||
* [关于软件](/abouteasyexcel.md) |
||||
* [常见问题](/problem.md) |
||||
* [更新记事](/update.md) |
||||
* [English-README](/easyexcel_en.md) |
||||
## 二方包 |
||||
|
||||
<dependency> |
||||
<groupId>com.alibaba</groupId> |
||||
<artifactId>easyexcel</artifactId> |
||||
<version>{latestVersion}</version> |
||||
</dependency> |
||||
|
||||
## 最新版本:1.1.2-beta4 |
||||
## 维护者 |
||||
姬朋飞(玉霄) |
||||
## 快速开始 |
||||
### 读Excel |
||||
测试代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/test/ReadTest.java](/src/test/java/com/alibaba/easyexcel/test/ReadTest.java) |
||||
DEMO代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/demo/read/ReadTest.java](/src/test/java/com/alibaba/easyexcel/test/demo/read/ReadTest.java) |
||||
|
||||
读07版小于1000行数据返回List<List<String>> |
||||
``` |
||||
List<Object> data = EasyExcelFactory.read(inputStream, new Sheet(1, 0)); |
||||
``` |
||||
读07版小于1000行数据返回List<? extend BaseRowModel> |
||||
``` |
||||
List<Object> data = EasyExcelFactory.read(inputStream, new Sheet(2, 1,JavaModel.class)); |
||||
``` |
||||
读07版大于1000行数据返回List<List<String>> |
||||
``` |
||||
ExcelListener excelListener = new ExcelListener(); |
||||
EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1), excelListener); |
||||
```java |
||||
/** |
||||
* 最简单的读 |
||||
* <p>1. 创建excel对应的实体对象 参照{@link DemoData} |
||||
* <p>2. 由于默认异步读取excel,所以需要创建excel一行一行的回调监听器,参照{@link DemoDataListener} |
||||
* <p>3. 直接读即可 |
||||
*/ |
||||
@Test |
||||
public void simpleRead() { |
||||
String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; |
||||
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭 |
||||
EasyExcel.read(fileName, DemoData.class, new DemoDataListener()).sheet().doRead(); |
||||
} |
||||
``` |
||||
|
||||
读07版大于1000行数据返回List<? extend BaseRowModel> |
||||
``` |
||||
ExcelListener excelListener = new ExcelListener(); |
||||
EasyExcelFactory.readBySax(inputStream, new Sheet(2, 1,JavaModel.class), excelListener); |
||||
``` |
||||
读03版方法同上 |
||||
### 写Excel |
||||
测试代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/test/WriteTest.java](/src/test/java/com/alibaba/easyexcel/test/WriteTest.java) |
||||
没有模板 |
||||
```OutputStream out = new FileOutputStream("/Users/jipengfei/2007.xlsx"); |
||||
ExcelWriter writer = EasyExcelFactory.getWriter(out); |
||||
|
||||
//写第一个sheet, sheet1 数据全是List<String> 无模型映射关系 |
||||
Sheet sheet1 = new Sheet(1, 3); |
||||
sheet1.setSheetName("第一个sheet"); |
||||
//设置列宽 设置每列的宽度 |
||||
Map columnWidth = new HashMap(); |
||||
columnWidth.put(0,10000);columnWidth.put(1,40000);columnWidth.put(2,10000);columnWidth.put(3,10000); |
||||
sheet1.setColumnWidthMap(columnWidth); |
||||
sheet1.setHead(createTestListStringHead()); |
||||
//or 设置自适应宽度 |
||||
//sheet1.setAutoWidth(Boolean.TRUE); |
||||
writer.write1(createTestListObject(), sheet1); |
||||
|
||||
//写第二个sheet sheet2 模型上打有表头的注解,合并单元格 |
||||
Sheet sheet2 = new Sheet(2, 3, JavaModel1.class, "第二个sheet", null); |
||||
sheet2.setTableStyle(createTableStyle()); |
||||
writer.write(createTestListJavaMode(), sheet2); |
||||
|
||||
//写第三个sheet包含多个table情况 |
||||
Sheet sheet3 = new Sheet(3, 0); |
||||
sheet3.setSheetName("第三个sheet"); |
||||
Table table1 = new Table(1); |
||||
table1.setHead(createTestListStringHead()); |
||||
writer.write1(createTestListObject(), sheet3, table1); |
||||
|
||||
//写sheet2 模型上打有表头的注解 |
||||
Table table2 = new Table(2); |
||||
table2.setTableStyle(createTableStyle()); |
||||
table2.setClazz(JavaModel1.class); |
||||
writer.write(createTestListJavaMode(), sheet3, table2); |
||||
|
||||
//关闭资源 |
||||
writer.finish(); |
||||
out.close(); |
||||
``` |
||||
有模板 |
||||
```InputStream inputStream = new BufferedInputStream(new FileInputStream("/Users/jipengfei/temp.xlsx")); |
||||
OutputStream out = new FileOutputStream("/Users/jipengfei/2007.xlsx"); |
||||
ExcelWriter writer = EasyExcelFactory.getWriterWithTemp(inputStream,out,ExcelTypeEnum.XLSX,true); |
||||
|
||||
//写第一个sheet, sheet1 数据全是List<String> 无模型映射关系 |
||||
Sheet sheet1 = new Sheet(1, 3); |
||||
sheet1.setSheetName("第一个sheet"); |
||||
//设置列宽 设置每列的宽度 |
||||
Map columnWidth = new HashMap(); |
||||
columnWidth.put(0,10000);columnWidth.put(1,40000);columnWidth.put(2,10000);columnWidth.put(3,10000); |
||||
sheet1.setColumnWidthMap(columnWidth); |
||||
sheet1.setHead(createTestListStringHead()); |
||||
//or 设置自适应宽度 |
||||
//sheet1.setAutoWidth(Boolean.TRUE); |
||||
writer.write1(createTestListObject(), sheet1); |
||||
|
||||
//写第二个sheet sheet2 模型上打有表头的注解,合并单元格 |
||||
Sheet sheet2 = new Sheet(2, 3, JavaModel1.class, "第二个sheet", null); |
||||
sheet2.setTableStyle(createTableStyle()); |
||||
writer.write(createTestListJavaMode(), sheet2); |
||||
|
||||
//写第三个sheet包含多个table情况 |
||||
Sheet sheet3 = new Sheet(3, 0); |
||||
sheet3.setSheetName("第三个sheet"); |
||||
Table table1 = new Table(1); |
||||
table1.setHead(createTestListStringHead()); |
||||
writer.write1(createTestListObject(), sheet3, table1); |
||||
|
||||
//写sheet2 模型上打有表头的注解 |
||||
Table table2 = new Table(2); |
||||
table2.setTableStyle(createTableStyle()); |
||||
table2.setClazz(JavaModel1.class); |
||||
writer.write(createTestListJavaMode(), sheet3, table2); |
||||
|
||||
//关闭资源 |
||||
writer.finish(); |
||||
out.close(); |
||||
DEMO代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java](/src/test/java/com/alibaba/easyexcel/test/demo/write/WriteTest.java) |
||||
```java |
||||
/** |
||||
* 最简单的写 |
||||
* <p>1. 创建excel对应的实体对象 参照{@link com.alibaba.easyexcel.test.demo.write.DemoData} |
||||
* <p>2. 直接写即可 |
||||
*/ |
||||
@Test |
||||
public void simpleWrite() { |
||||
String fileName = TestFileUtil.getPath() + "write" + System.currentTimeMillis() + ".xlsx"; |
||||
// 这里 需要指定写用哪个class去读,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 |
||||
// 如果这里想使用03 则 传入excelType参数即可 |
||||
EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data()); |
||||
} |
||||
``` |
||||
|
||||
### web下载实例写法 |
||||
``` |
||||
public class Down { |
||||
@GetMapping("/a.htm") |
||||
public void cooperation(HttpServletRequest request, HttpServletResponse response) { |
||||
ServletOutputStream out = response.getOutputStream(); |
||||
response.setContentType("multipart/form-data"); |
||||
### web上传、下载 |
||||
DEMO代码地址:[https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java](/src/test/java/com/alibaba/easyexcel/test/demo/web/WebTest.java) |
||||
```java |
||||
/** |
||||
* 文件下载 |
||||
* <p>1. 创建excel对应的实体对象 参照{@link DownloadData} |
||||
* <p>2. 设置返回的 参数 |
||||
* <p>3. 直接写,这里注意,finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大 |
||||
*/ |
||||
@GetMapping("download") |
||||
public void download(HttpServletResponse response) throws IOException { |
||||
response.setContentType("application/vnd.ms-excel"); |
||||
response.setCharacterEncoding("utf-8"); |
||||
response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx"); |
||||
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true); |
||||
String fileName = new String(("UserInfo " + new SimpleDateFormat("yyyy-MM-dd").format(new Date())) |
||||
.getBytes(), "UTF-8"); |
||||
Sheet sheet1 = new Sheet(1, 0); |
||||
sheet1.setSheetName("第一个sheet"); |
||||
writer.write0(getListString(), sheet1); |
||||
writer.finish(); |
||||
|
||||
out.flush(); |
||||
} |
||||
response.setHeader("Content-disposition", "attachment;filename=demo.xlsx"); |
||||
EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data()); |
||||
} |
||||
|
||||
/** |
||||
* 文件上传 |
||||
* <p>1. 创建excel对应的实体对象 参照{@link UploadData} |
||||
* <p>2. 由于默认异步读取excel,所以需要创建excel一行一行的回调监听器,参照{@link UploadDataListener} |
||||
* <p>3. 直接读即可 |
||||
*/ |
||||
@PostMapping("upload") |
||||
@ResponseBody |
||||
public String upload(MultipartFile file) throws IOException { |
||||
EasyExcel.read(file.getInputStream(), UploadData.class, new UploadDataListener()).sheet().doRead(); |
||||
return "success"; |
||||
} |
||||
} |
||||
``` |
||||
### 联系我们 |
||||
有问题阿里同事可以通过钉钉找到我,阿里外同学可以通过git留言。其他技术非技术相关的也欢迎一起探讨。 |
||||
### 招聘&交流 |
||||
阿里巴巴新零售事业部--诚招JAVA资深开发、技术专家。有意向可以微信联系,简历可以发我邮箱jipengfei.jpf@alibaba-inc.com |
||||
或者加QQ群: 662022184 |
||||
阿里巴巴新零售事业部--诚招JAVA资深开发、技术专家。有意向可以微信联系,简历可以发我邮箱jipengfei.jpf@alibaba-inc.com |
Before Width: | Height: | Size: 149 KiB |
After Width: | Height: | Size: 2.7 KiB |
After Width: | Height: | Size: 4.3 KiB |
After Width: | Height: | Size: 5.4 KiB |
After Width: | Height: | Size: 4.2 KiB |
After Width: | Height: | Size: 4.5 KiB |
After Width: | Height: | Size: 8.8 KiB |
After Width: | Height: | Size: 5.0 KiB |
After Width: | Height: | Size: 6.5 KiB |
After Width: | Height: | Size: 4.0 KiB |
After Width: | Height: | Size: 5.4 KiB |
After Width: | Height: | Size: 3.4 KiB |
After Width: | Height: | Size: 4.5 KiB |
After Width: | Height: | Size: 6.6 KiB |
After Width: | Height: | Size: 6.7 KiB |
After Width: | Height: | Size: 4.7 KiB |
After Width: | Height: | Size: 66 KiB |
After Width: | Height: | Size: 56 KiB |
After Width: | Height: | Size: 14 KiB |
After Width: | Height: | Size: 30 KiB |
After Width: | Height: | Size: 23 KiB |
@ -0,0 +1,305 @@
|
||||
#!/bin/sh |
||||
# ---------------------------------------------------------------------------- |
||||
# Licensed to the Apache Software Foundation (ASF) under one |
||||
# or more contributor license agreements. See the NOTICE file |
||||
# distributed with this work for additional information |
||||
# regarding copyright ownership. The ASF licenses this file |
||||
# to you under the Apache License, Version 2.0 (the |
||||
# "License"); you may not use this file except in compliance |
||||
# with the License. You may obtain a copy of the License at |
||||
# |
||||
# https://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, |
||||
# software distributed under the License is distributed on an |
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
||||
# KIND, either express or implied. See the License for the |
||||
# specific language governing permissions and limitations |
||||
# under the License. |
||||
# ---------------------------------------------------------------------------- |
||||
|
||||
# ---------------------------------------------------------------------------- |
||||
# Maven2 Start Up Batch script |
||||
# |
||||
# Required ENV vars: |
||||
# ------------------ |
||||
# JAVA_HOME - location of a JDK home dir |
||||
# |
||||
# Optional ENV vars |
||||
# ----------------- |
||||
# M2_HOME - location of maven2's installed home dir |
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven |
||||
# e.g. to debug Maven itself, use |
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 |
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files |
||||
# ---------------------------------------------------------------------------- |
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then |
||||
|
||||
if [ -f /etc/mavenrc ] ; then |
||||
. /etc/mavenrc |
||||
fi |
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then |
||||
. "$HOME/.mavenrc" |
||||
fi |
||||
|
||||
fi |
||||
|
||||
# OS specific support. $var _must_ be set to either true or false. |
||||
cygwin=false; |
||||
darwin=false; |
||||
mingw=false |
||||
case "`uname`" in |
||||
CYGWIN*) cygwin=true ;; |
||||
MINGW*) mingw=true;; |
||||
Darwin*) darwin=true |
||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home |
||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html |
||||
if [ -z "$JAVA_HOME" ]; then |
||||
if [ -x "/usr/libexec/java_home" ]; then |
||||
export JAVA_HOME="`/usr/libexec/java_home`" |
||||
else |
||||
export JAVA_HOME="/Library/Java/Home" |
||||
fi |
||||
fi |
||||
;; |
||||
esac |
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then |
||||
if [ -r /etc/gentoo-release ] ; then |
||||
JAVA_HOME=`java-config --jre-home` |
||||
fi |
||||
fi |
||||
|
||||
if [ -z "$M2_HOME" ] ; then |
||||
## resolve links - $0 may be a link to maven's home |
||||
PRG="$0" |
||||
|
||||
# need this for relative symlinks |
||||
while [ -h "$PRG" ] ; do |
||||
ls=`ls -ld "$PRG"` |
||||
link=`expr "$ls" : '.*-> \(.*\)$'` |
||||
if expr "$link" : '/.*' > /dev/null; then |
||||
PRG="$link" |
||||
else |
||||
PRG="`dirname "$PRG"`/$link" |
||||
fi |
||||
done |
||||
|
||||
saveddir=`pwd` |
||||
|
||||
M2_HOME=`dirname "$PRG"`/.. |
||||
|
||||
# make it fully qualified |
||||
M2_HOME=`cd "$M2_HOME" && pwd` |
||||
|
||||
cd "$saveddir" |
||||
# echo Using m2 at $M2_HOME |
||||
fi |
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched |
||||
if $cygwin ; then |
||||
[ -n "$M2_HOME" ] && |
||||
M2_HOME=`cygpath --unix "$M2_HOME"` |
||||
[ -n "$JAVA_HOME" ] && |
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"` |
||||
[ -n "$CLASSPATH" ] && |
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"` |
||||
fi |
||||
|
||||
# For Mingw, ensure paths are in UNIX format before anything is touched |
||||
if $mingw ; then |
||||
[ -n "$M2_HOME" ] && |
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`" |
||||
[ -n "$JAVA_HOME" ] && |
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" |
||||
fi |
||||
|
||||
if [ -z "$JAVA_HOME" ]; then |
||||
javaExecutable="`which javac`" |
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then |
||||
# readlink(1) is not available as standard on Solaris 10. |
||||
readLink=`which readlink` |
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then |
||||
if $darwin ; then |
||||
javaHome="`dirname \"$javaExecutable\"`" |
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" |
||||
else |
||||
javaExecutable="`readlink -f \"$javaExecutable\"`" |
||||
fi |
||||
javaHome="`dirname \"$javaExecutable\"`" |
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'` |
||||
JAVA_HOME="$javaHome" |
||||
export JAVA_HOME |
||||
fi |
||||
fi |
||||
fi |
||||
|
||||
if [ -z "$JAVACMD" ] ; then |
||||
if [ -n "$JAVA_HOME" ] ; then |
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then |
||||
# IBM's JDK on AIX uses strange locations for the executables |
||||
JAVACMD="$JAVA_HOME/jre/sh/java" |
||||
else |
||||
JAVACMD="$JAVA_HOME/bin/java" |
||||
fi |
||||
else |
||||
JAVACMD="`which java`" |
||||
fi |
||||
fi |
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then |
||||
echo "Error: JAVA_HOME is not defined correctly." >&2 |
||||
echo " We cannot execute $JAVACMD" >&2 |
||||
exit 1 |
||||
fi |
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then |
||||
echo "Warning: JAVA_HOME environment variable is not set." |
||||
fi |
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher |
||||
|
||||
# traverses directory structure from process work directory to filesystem root |
||||
# first directory with .mvn subdirectory is considered project base directory |
||||
find_maven_basedir() { |
||||
|
||||
if [ -z "$1" ] |
||||
then |
||||
echo "Path not specified to find_maven_basedir" |
||||
return 1 |
||||
fi |
||||
|
||||
basedir="$1" |
||||
wdir="$1" |
||||
while [ "$wdir" != '/' ] ; do |
||||
if [ -d "$wdir"/.mvn ] ; then |
||||
basedir=$wdir |
||||
break |
||||
fi |
||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc) |
||||
if [ -d "${wdir}" ]; then |
||||
wdir=`cd "$wdir/.."; pwd` |
||||
fi |
||||
# end of workaround |
||||
done |
||||
echo "${basedir}" |
||||
} |
||||
|
||||
# concatenates all lines of a file |
||||
concat_lines() { |
||||
if [ -f "$1" ]; then |
||||
echo "$(tr -s '\n' ' ' < "$1")" |
||||
fi |
||||
} |
||||
|
||||
BASE_DIR=`find_maven_basedir "$(pwd)"` |
||||
if [ -z "$BASE_DIR" ]; then |
||||
exit 1; |
||||
fi |
||||
|
||||
########################################################################################## |
||||
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central |
||||
# This allows using the maven wrapper in projects that prohibit checking in binary data. |
||||
########################################################################################## |
||||
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then |
||||
if [ "$MVNW_VERBOSE" = true ]; then |
||||
echo "Found .mvn/wrapper/maven-wrapper.jar" |
||||
fi |
||||
else |
||||
if [ "$MVNW_VERBOSE" = true ]; then |
||||
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." |
||||
fi |
||||
if [ -n "$MVNW_REPOURL" ]; then |
||||
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.3/maven-wrapper-0.5.3.jar" |
||||
else |
||||
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.3/maven-wrapper-0.5.3.jar" |
||||
fi |
||||
while IFS="=" read key value; do |
||||
case "$key" in (wrapperUrl) jarUrl="$value"; break ;; |
||||
esac |
||||
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" |
||||
if [ "$MVNW_VERBOSE" = true ]; then |
||||
echo "Downloading from: $jarUrl" |
||||
fi |
||||
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" |
||||
if $cygwin; then |
||||
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` |
||||
fi |
||||
|
||||
if command -v wget > /dev/null; then |
||||
if [ "$MVNW_VERBOSE" = true ]; then |
||||
echo "Found wget ... using wget" |
||||
fi |
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then |
||||
wget "$jarUrl" -O "$wrapperJarPath" |
||||
else |
||||
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" |
||||
fi |
||||
elif command -v curl > /dev/null; then |
||||
if [ "$MVNW_VERBOSE" = true ]; then |
||||
echo "Found curl ... using curl" |
||||
fi |
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then |
||||
curl -o "$wrapperJarPath" "$jarUrl" -f |
||||
else |
||||
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f |
||||
fi |
||||
|
||||
else |
||||
if [ "$MVNW_VERBOSE" = true ]; then |
||||
echo "Falling back to using Java to download" |
||||
fi |
||||
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" |
||||
# For Cygwin, switch paths to Windows format before running javac |
||||
if $cygwin; then |
||||
javaClass=`cygpath --path --windows "$javaClass"` |
||||
fi |
||||
if [ -e "$javaClass" ]; then |
||||
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then |
||||
if [ "$MVNW_VERBOSE" = true ]; then |
||||
echo " - Compiling MavenWrapperDownloader.java ..." |
||||
fi |
||||
# Compiling the Java class |
||||
("$JAVA_HOME/bin/javac" "$javaClass") |
||||
fi |
||||
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then |
||||
# Running the downloader |
||||
if [ "$MVNW_VERBOSE" = true ]; then |
||||
echo " - Running MavenWrapperDownloader.java ..." |
||||
fi |
||||
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") |
||||
fi |
||||
fi |
||||
fi |
||||
fi |
||||
########################################################################################## |
||||
# End of extension |
||||
########################################################################################## |
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} |
||||
if [ "$MVNW_VERBOSE" = true ]; then |
||||
echo $MAVEN_PROJECTBASEDIR |
||||
fi |
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" |
||||
|
||||
# For Cygwin, switch paths to Windows format before running java |
||||
if $cygwin; then |
||||
[ -n "$M2_HOME" ] && |
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"` |
||||
[ -n "$JAVA_HOME" ] && |
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` |
||||
[ -n "$CLASSPATH" ] && |
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"` |
||||
[ -n "$MAVEN_PROJECTBASEDIR" ] && |
||||
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` |
||||
fi |
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain |
||||
|
||||
exec "$JAVACMD" \ |
||||
$MAVEN_OPTS \ |
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ |
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ |
||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" |
@ -0,0 +1,172 @@
|
||||
@REM ---------------------------------------------------------------------------- |
||||
@REM Licensed to the Apache Software Foundation (ASF) under one |
||||
@REM or more contributor license agreements. See the NOTICE file |
||||
@REM distributed with this work for additional information |
||||
@REM regarding copyright ownership. The ASF licenses this file |
||||
@REM to you under the Apache License, Version 2.0 (the |
||||
@REM "License"); you may not use this file except in compliance |
||||
@REM with the License. You may obtain a copy of the License at |
||||
@REM |
||||
@REM https://www.apache.org/licenses/LICENSE-2.0 |
||||
@REM |
||||
@REM Unless required by applicable law or agreed to in writing, |
||||
@REM software distributed under the License is distributed on an |
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
||||
@REM KIND, either express or implied. See the License for the |
||||
@REM specific language governing permissions and limitations |
||||
@REM under the License. |
||||
@REM ---------------------------------------------------------------------------- |
||||
|
||||
@REM ---------------------------------------------------------------------------- |
||||
@REM Maven2 Start Up Batch script |
||||
@REM |
||||
@REM Required ENV vars: |
||||
@REM JAVA_HOME - location of a JDK home dir |
||||
@REM |
||||
@REM Optional ENV vars |
||||
@REM M2_HOME - location of maven2's installed home dir |
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands |
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending |
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven |
||||
@REM e.g. to debug Maven itself, use |
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 |
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files |
||||
@REM ---------------------------------------------------------------------------- |
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' |
||||
@echo off |
||||
@REM set title of command window |
||||
title %0 |
||||
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' |
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% |
||||
|
||||
@REM set %HOME% to equivalent of $HOME |
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") |
||||
|
||||
@REM Execute a user defined script before this one |
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre |
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending |
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" |
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" |
||||
:skipRcPre |
||||
|
||||
@setlocal |
||||
|
||||
set ERROR_CODE=0 |
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal |
||||
@setlocal |
||||
|
||||
@REM ==== START VALIDATION ==== |
||||
if not "%JAVA_HOME%" == "" goto OkJHome |
||||
|
||||
echo. |
||||
echo Error: JAVA_HOME not found in your environment. >&2 |
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2 |
||||
echo location of your Java installation. >&2 |
||||
echo. |
||||
goto error |
||||
|
||||
:OkJHome |
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init |
||||
|
||||
echo. |
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2 |
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2 |
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2 |
||||
echo location of your Java installation. >&2 |
||||
echo. |
||||
goto error |
||||
|
||||
@REM ==== END VALIDATION ==== |
||||
|
||||
:init |
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". |
||||
@REM Fallback to current working directory if not found. |
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% |
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir |
||||
|
||||
set EXEC_DIR=%CD% |
||||
set WDIR=%EXEC_DIR% |
||||
:findBaseDir |
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound |
||||
cd .. |
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound |
||||
set WDIR=%CD% |
||||
goto findBaseDir |
||||
|
||||
:baseDirFound |
||||
set MAVEN_PROJECTBASEDIR=%WDIR% |
||||
cd "%EXEC_DIR%" |
||||
goto endDetectBaseDir |
||||
|
||||
:baseDirNotFound |
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR% |
||||
cd "%EXEC_DIR%" |
||||
|
||||
:endDetectBaseDir |
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig |
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion |
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a |
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% |
||||
|
||||
:endReadAdditionalConfig |
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" |
||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" |
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain |
||||
|
||||
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.3/maven-wrapper-0.5.3.jar" |
||||
|
||||
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( |
||||
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B |
||||
) |
||||
|
||||
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central |
||||
@REM This allows using the maven wrapper in projects that prohibit checking in binary data. |
||||
if exist %WRAPPER_JAR% ( |
||||
echo Found %WRAPPER_JAR% |
||||
) else ( |
||||
if not "%MVNW_REPOURL%" == "" ( |
||||
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.3/maven-wrapper-0.5.3.jar" |
||||
) |
||||
echo Couldn't find %WRAPPER_JAR%, downloading it ... |
||||
echo Downloading from: %DOWNLOAD_URL% |
||||
|
||||
powershell -Command "&{"^ |
||||
"$webclient = new-object System.Net.WebClient;"^ |
||||
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ |
||||
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ |
||||
"}"^ |
||||
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ |
||||
"}" |
||||
echo Finished downloading %WRAPPER_JAR% |
||||
) |
||||
@REM End of extension |
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* |
||||
if ERRORLEVEL 1 goto error |
||||
goto end |
||||
|
||||
:error |
||||
set ERROR_CODE=1 |
||||
|
||||
:end |
||||
@endlocal & set ERROR_CODE=%ERROR_CODE% |
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost |
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending |
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" |
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" |
||||
:skipRcPost |
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' |
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause |
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% |
||||
|
||||
exit /B %ERROR_CODE% |
@ -0,0 +1,8 @@
|
||||
package com.alibaba.excel; |
||||
|
||||
/** |
||||
* This is actually {@link EasyExcelFactory}, and short names look better. |
||||
* |
||||
* @author jipengfei |
||||
*/ |
||||
public class EasyExcel extends EasyExcelFactory {} |
@ -1,87 +0,0 @@
|
||||
package com.alibaba.excel.analysis; |
||||
|
||||
import com.alibaba.excel.context.AnalysisContext; |
||||
import com.alibaba.excel.event.AnalysisEventListener; |
||||
import com.alibaba.excel.event.AnalysisEventRegisterCenter; |
||||
import com.alibaba.excel.event.OneRowAnalysisFinishEvent; |
||||
import com.alibaba.excel.metadata.Sheet; |
||||
import com.alibaba.excel.util.TypeUtil; |
||||
|
||||
import java.util.ArrayList; |
||||
import java.util.LinkedHashMap; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* @author jipengfei |
||||
*/ |
||||
public abstract class BaseSaxAnalyser implements AnalysisEventRegisterCenter, ExcelAnalyser { |
||||
|
||||
protected AnalysisContext analysisContext; |
||||
|
||||
private LinkedHashMap<String, AnalysisEventListener> listeners = new LinkedHashMap<String, AnalysisEventListener>(); |
||||
|
||||
/** |
||||
* execute method |
||||
*/ |
||||
protected abstract void execute(); |
||||
|
||||
|
||||
@Override |
||||
public void appendLister(String name, AnalysisEventListener listener) { |
||||
if (!listeners.containsKey(name)) { |
||||
listeners.put(name, listener); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void analysis(Sheet sheetParam) { |
||||
execute(); |
||||
} |
||||
|
||||
@Override |
||||
public void analysis() { |
||||
execute(); |
||||
} |
||||
|
||||
/** |
||||
*/ |
||||
@Override |
||||
public void cleanAllListeners() { |
||||
listeners = new LinkedHashMap<String, AnalysisEventListener>(); |
||||
} |
||||
|
||||
@Override |
||||
public void notifyListeners(OneRowAnalysisFinishEvent event) { |
||||
analysisContext.setCurrentRowAnalysisResult(event.getData()); |
||||
/** Parsing header content **/ |
||||
if (analysisContext.getCurrentRowNum() < analysisContext.getCurrentSheet().getHeadLineMun()) { |
||||
if (analysisContext.getCurrentRowNum() <= analysisContext.getCurrentSheet().getHeadLineMun() - 1) { |
||||
analysisContext.buildExcelHeadProperty(null, |
||||
(List<String>)analysisContext.getCurrentRowAnalysisResult()); |
||||
} |
||||
} else { |
||||
List<String> content = converter((List<String>)event.getData()); |
||||
/** Parsing Analyze the body content **/ |
||||
analysisContext.setCurrentRowAnalysisResult(content); |
||||
if (listeners.size() == 1) { |
||||
analysisContext.setCurrentRowAnalysisResult(content); |
||||
} |
||||
/** notify all event listeners **/ |
||||
for (Map.Entry<String, AnalysisEventListener> entry : listeners.entrySet()) { |
||||
entry.getValue().invoke(analysisContext.getCurrentRowAnalysisResult(), analysisContext); |
||||
} |
||||
} |
||||
} |
||||
|
||||
private List<String> converter(List<String> data) { |
||||
List<String> list = new ArrayList<String>(); |
||||
if (data != null) { |
||||
for (String str : data) { |
||||
list.add(TypeUtil.formatFloat(str)); |
||||
} |
||||
} |
||||
return list; |
||||
} |
||||
|
||||
} |
@ -1,95 +1,145 @@
|
||||
package com.alibaba.excel.analysis; |
||||
|
||||
import java.io.InputStream; |
||||
|
||||
import org.apache.poi.poifs.crypt.Decryptor; |
||||
import org.apache.poi.poifs.filesystem.DocumentFactoryHelper; |
||||
import org.apache.poi.poifs.filesystem.POIFSFileSystem; |
||||
import org.apache.poi.util.IOUtils; |
||||
import org.slf4j.Logger; |
||||
import org.slf4j.LoggerFactory; |
||||
|
||||
import com.alibaba.excel.analysis.v03.XlsSaxAnalyser; |
||||
import com.alibaba.excel.analysis.v07.XlsxSaxAnalyser; |
||||
import com.alibaba.excel.context.AnalysisContext; |
||||
import com.alibaba.excel.context.AnalysisContextImpl; |
||||
import com.alibaba.excel.event.AnalysisEventListener; |
||||
import com.alibaba.excel.exception.ExcelAnalysisException; |
||||
import com.alibaba.excel.metadata.Sheet; |
||||
import com.alibaba.excel.modelbuild.ModelBuildEventListener; |
||||
import com.alibaba.excel.exception.ExcelAnalysisStopException; |
||||
import com.alibaba.excel.read.metadata.ReadSheet; |
||||
import com.alibaba.excel.read.metadata.ReadWorkbook; |
||||
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder; |
||||
import com.alibaba.excel.support.ExcelTypeEnum; |
||||
|
||||
import java.io.InputStream; |
||||
import java.util.List; |
||||
import com.alibaba.excel.util.FileUtils; |
||||
|
||||
/** |
||||
* @author jipengfei |
||||
*/ |
||||
public class ExcelAnalyserImpl implements ExcelAnalyser { |
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ExcelAnalyserImpl.class); |
||||
|
||||
private AnalysisContext analysisContext; |
||||
|
||||
private BaseSaxAnalyser saxAnalyser; |
||||
private ExcelExecutor excelExecutor; |
||||
|
||||
public ExcelAnalyserImpl(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Object custom, |
||||
AnalysisEventListener eventListener, boolean trim) { |
||||
analysisContext = new AnalysisContextImpl(inputStream, excelTypeEnum, custom, |
||||
eventListener, trim); |
||||
public ExcelAnalyserImpl(ReadWorkbook readWorkbook) { |
||||
try { |
||||
analysisContext = new AnalysisContextImpl(readWorkbook); |
||||
choiceExcelExecutor(); |
||||
} catch (RuntimeException e) { |
||||
finish(); |
||||
throw e; |
||||
} catch (Throwable e) { |
||||
finish(); |
||||
throw new ExcelAnalysisException(e); |
||||
} |
||||
} |
||||
|
||||
private BaseSaxAnalyser getSaxAnalyser() { |
||||
if (saxAnalyser != null) { |
||||
return this.saxAnalyser; |
||||
private void choiceExcelExecutor() throws Exception { |
||||
ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder(); |
||||
ExcelTypeEnum excelType = readWorkbookHolder.getExcelType(); |
||||
if (excelType == null) { |
||||
excelExecutor = new XlsxSaxAnalyser(analysisContext, null); |
||||
return; |
||||
} |
||||
try { |
||||
if (analysisContext.getExcelType() != null) { |
||||
switch (analysisContext.getExcelType()) { |
||||
case XLS: |
||||
this.saxAnalyser = new XlsSaxAnalyser(analysisContext); |
||||
break; |
||||
case XLSX: |
||||
this.saxAnalyser = new XlsxSaxAnalyser(analysisContext); |
||||
break; |
||||
switch (excelType) { |
||||
case XLS: |
||||
POIFSFileSystem poifsFileSystem = null; |
||||
if (readWorkbookHolder.getFile() != null) { |
||||
poifsFileSystem = new POIFSFileSystem(readWorkbookHolder.getFile()); |
||||
} else { |
||||
poifsFileSystem = new POIFSFileSystem(readWorkbookHolder.getInputStream()); |
||||
} |
||||
} else { |
||||
try { |
||||
this.saxAnalyser = new XlsxSaxAnalyser(analysisContext); |
||||
} catch (Exception e) { |
||||
if (!analysisContext.getInputStream().markSupported()) { |
||||
throw new ExcelAnalysisException( |
||||
"Xls must be available markSupported,you can do like this <code> new " |
||||
+ "BufferedInputStream(new FileInputStream(\"/xxxx\"))</code> "); |
||||
// So in encrypted excel, it looks like XLS but it's actually XLSX
|
||||
if (poifsFileSystem.getRoot().hasEntry(Decryptor.DEFAULT_POIFS_ENTRY)) { |
||||
InputStream decryptedStream = null; |
||||
try { |
||||
decryptedStream = DocumentFactoryHelper.getDecryptedStream(poifsFileSystem.getRoot(), null); |
||||
excelExecutor = new XlsxSaxAnalyser(analysisContext, decryptedStream); |
||||
return; |
||||
} finally { |
||||
IOUtils.closeQuietly(decryptedStream); |
||||
// as we processed the full stream already, we can close the filesystem here
|
||||
// otherwise file handles are leaked
|
||||
poifsFileSystem.close(); |
||||
} |
||||
this.saxAnalyser = new XlsSaxAnalyser(analysisContext); |
||||
} |
||||
} |
||||
} catch (Exception e) { |
||||
throw new ExcelAnalysisException("File type error,io must be available markSupported,you can do like " |
||||
+ "this <code> new BufferedInputStream(new FileInputStream(\\\"/xxxx\\\"))</code> \"", e); |
||||
excelExecutor = new XlsSaxAnalyser(analysisContext, poifsFileSystem); |
||||
break; |
||||
case XLSX: |
||||
excelExecutor = new XlsxSaxAnalyser(analysisContext, null); |
||||
break; |
||||
default: |
||||
} |
||||
return this.saxAnalyser; |
||||
} |
||||
|
||||
@Override |
||||
public void analysis(Sheet sheetParam) { |
||||
analysisContext.setCurrentSheet(sheetParam); |
||||
analysis(); |
||||
public void analysis(ReadSheet readSheet) { |
||||
try { |
||||
analysisContext.currentSheet(excelExecutor, readSheet); |
||||
try { |
||||
excelExecutor.execute(); |
||||
} catch (ExcelAnalysisStopException e) { |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("Custom stop!"); |
||||
} |
||||
} |
||||
analysisContext.readSheetHolder().notifyAfterAllAnalysed(analysisContext); |
||||
} catch (RuntimeException e) { |
||||
finish(); |
||||
throw e; |
||||
} catch (Throwable e) { |
||||
finish(); |
||||
throw new ExcelAnalysisException(e); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void analysis() { |
||||
BaseSaxAnalyser saxAnalyser = getSaxAnalyser(); |
||||
appendListeners(saxAnalyser); |
||||
saxAnalyser.execute(); |
||||
analysisContext.getEventListener().doAfterAllAnalysed(analysisContext); |
||||
public void finish() { |
||||
if (analysisContext == null || analysisContext.readWorkbookHolder() == null) { |
||||
return; |
||||
} |
||||
ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder(); |
||||
try { |
||||
if (readWorkbookHolder.getReadCache() != null) { |
||||
readWorkbookHolder.getReadCache().destroy(); |
||||
} |
||||
} catch (Throwable e) { |
||||
throw new ExcelAnalysisException("Can not close IO", e); |
||||
} |
||||
try { |
||||
if (analysisContext.readWorkbookHolder().getAutoCloseStream() |
||||
&& readWorkbookHolder.getInputStream() != null) { |
||||
readWorkbookHolder.getInputStream().close(); |
||||
} |
||||
} catch (Throwable e) { |
||||
throw new ExcelAnalysisException("Can not close IO", e); |
||||
} |
||||
try { |
||||
if (readWorkbookHolder.getTempFile() != null) { |
||||
FileUtils.delete(readWorkbookHolder.getTempFile()); |
||||
} |
||||
} catch (Throwable e) { |
||||
throw new ExcelAnalysisException("Can not close IO", e); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public List<Sheet> getSheets() { |
||||
BaseSaxAnalyser saxAnalyser = getSaxAnalyser(); |
||||
saxAnalyser.cleanAllListeners(); |
||||
return saxAnalyser.getSheets(); |
||||
public com.alibaba.excel.analysis.ExcelExecutor excelExecutor() { |
||||
return excelExecutor; |
||||
} |
||||
|
||||
private void appendListeners(BaseSaxAnalyser saxAnalyser) { |
||||
saxAnalyser.cleanAllListeners(); |
||||
if (analysisContext.getCurrentSheet() != null && analysisContext.getCurrentSheet().getClazz() != null) { |
||||
saxAnalyser.appendLister("model_build_listener", new ModelBuildEventListener()); |
||||
} |
||||
if (analysisContext.getEventListener() != null) { |
||||
saxAnalyser.appendLister("user_define_listener", analysisContext.getEventListener()); |
||||
} |
||||
@Override |
||||
public AnalysisContext analysisContext() { |
||||
return analysisContext; |
||||
} |
||||
|
||||
} |
||||
|
@ -0,0 +1,26 @@
|
||||
package com.alibaba.excel.analysis; |
||||
|
||||
import java.util.List; |
||||
|
||||
import com.alibaba.excel.read.metadata.ReadSheet; |
||||
|
||||
/** |
||||
* Excel file Executor |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public interface ExcelExecutor { |
||||
|
||||
/** |
||||
* Returns the actual sheet in excel |
||||
* |
||||
* @return Actual sheet in excel |
||||
*/ |
||||
List<ReadSheet> sheetList(); |
||||
|
||||
/** |
||||
* Read sheet |
||||
*/ |
||||
void execute(); |
||||
|
||||
} |
@ -0,0 +1,33 @@
|
||||
package com.alibaba.excel.analysis.v03; |
||||
|
||||
import com.alibaba.excel.metadata.CellData; |
||||
|
||||
/** |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public abstract class AbstractXlsRecordHandler implements XlsRecordHandler { |
||||
protected int row = -1; |
||||
protected int column = -1; |
||||
protected CellData cellData; |
||||
|
||||
@Override |
||||
public int getRow() { |
||||
return row; |
||||
} |
||||
|
||||
@Override |
||||
public int getColumn() { |
||||
return column; |
||||
} |
||||
|
||||
@Override |
||||
public CellData getCellData() { |
||||
return cellData; |
||||
} |
||||
|
||||
@Override |
||||
public int compareTo(XlsRecordHandler o) { |
||||
return this.getOrder() - o.getOrder(); |
||||
} |
||||
} |
@ -0,0 +1,61 @@
|
||||
package com.alibaba.excel.analysis.v03; |
||||
|
||||
import org.apache.poi.hssf.record.Record; |
||||
|
||||
import com.alibaba.excel.metadata.CellData; |
||||
|
||||
/** |
||||
* Intercepts handle xls reads. |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public interface XlsRecordHandler extends Comparable<XlsRecordHandler> { |
||||
/** |
||||
* Which tags are supported |
||||
* |
||||
* @param record |
||||
* Excel analysis record |
||||
* @return Which tags are supported |
||||
*/ |
||||
boolean support(Record record); |
||||
|
||||
/** |
||||
* Initialize |
||||
*/ |
||||
void init(); |
||||
|
||||
/** |
||||
* Processing record |
||||
* |
||||
* @param record |
||||
*/ |
||||
void processRecord(Record record); |
||||
|
||||
/** |
||||
* Get row |
||||
* |
||||
* @return Row index |
||||
*/ |
||||
int getRow(); |
||||
|
||||
/** |
||||
* Get column |
||||
* |
||||
* @return Column index |
||||
*/ |
||||
int getColumn(); |
||||
|
||||
/** |
||||
* Get value |
||||
* |
||||
* @return Excel internal cell data |
||||
*/ |
||||
CellData getCellData(); |
||||
|
||||
/** |
||||
* Get order |
||||
* |
||||
* @return Order |
||||
*/ |
||||
int getOrder(); |
||||
} |
@ -0,0 +1,47 @@
|
||||
package com.alibaba.excel.analysis.v03.handlers; |
||||
|
||||
import org.apache.poi.hssf.record.BlankRecord; |
||||
import org.apache.poi.hssf.record.BoolErrRecord; |
||||
import org.apache.poi.hssf.record.Record; |
||||
|
||||
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
|
||||
/** |
||||
* Record handler |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public class BlankOrErrorRecordHandler extends AbstractXlsRecordHandler { |
||||
|
||||
@Override |
||||
public boolean support(Record record) { |
||||
return BlankRecord.sid == record.getSid() || BoolErrRecord.sid == record.getSid(); |
||||
} |
||||
|
||||
@Override |
||||
public void processRecord(Record record) { |
||||
if (record.getSid() == BlankRecord.sid) { |
||||
BlankRecord br = (BlankRecord)record; |
||||
this.row = br.getRow(); |
||||
this.column = br.getColumn(); |
||||
this.cellData = new CellData(CellDataTypeEnum.EMPTY); |
||||
} else if (record.getSid() == BoolErrRecord.sid) { |
||||
BoolErrRecord ber = (BoolErrRecord)record; |
||||
this.row = ber.getRow(); |
||||
this.column = ber.getColumn(); |
||||
this.cellData = new CellData(ber.getBooleanValue()); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void init() { |
||||
|
||||
} |
||||
|
||||
@Override |
||||
public int getOrder() { |
||||
return 0; |
||||
} |
||||
} |
@ -0,0 +1,76 @@
|
||||
package com.alibaba.excel.analysis.v03.handlers; |
||||
|
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
|
||||
import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder; |
||||
import org.apache.poi.hssf.record.BOFRecord; |
||||
import org.apache.poi.hssf.record.BoundSheetRecord; |
||||
import org.apache.poi.hssf.record.Record; |
||||
|
||||
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; |
||||
import com.alibaba.excel.context.AnalysisContext; |
||||
import com.alibaba.excel.read.metadata.ReadSheet; |
||||
|
||||
/** |
||||
* Record handler |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public class BofRecordHandler extends AbstractXlsRecordHandler { |
||||
private List<BoundSheetRecord> boundSheetRecords = new ArrayList<BoundSheetRecord>(); |
||||
private BoundSheetRecord[] orderedBsrs; |
||||
private int sheetIndex; |
||||
private List<ReadSheet> sheets; |
||||
private AnalysisContext context; |
||||
private boolean analyAllSheet; |
||||
private EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener; |
||||
|
||||
public BofRecordHandler(EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener, |
||||
AnalysisContext context, List<ReadSheet> sheets) { |
||||
this.context = context; |
||||
this.workbookBuildingListener = workbookBuildingListener; |
||||
this.sheets = sheets; |
||||
} |
||||
|
||||
@Override |
||||
public boolean support(Record record) { |
||||
return BoundSheetRecord.sid == record.getSid() || BOFRecord.sid == record.getSid(); |
||||
} |
||||
|
||||
@Override |
||||
public void processRecord(Record record) { |
||||
if (record.getSid() == BoundSheetRecord.sid) { |
||||
boundSheetRecords.add((BoundSheetRecord)record); |
||||
} else if (record.getSid() == BOFRecord.sid) { |
||||
BOFRecord br = (BOFRecord)record; |
||||
if (br.getType() == BOFRecord.TYPE_WORKSHEET) { |
||||
if (orderedBsrs == null) { |
||||
orderedBsrs = BoundSheetRecord.orderByBofPosition(boundSheetRecords); |
||||
} |
||||
sheetIndex++; |
||||
ReadSheet readSheet = new ReadSheet(sheetIndex, orderedBsrs[sheetIndex - 1].getSheetname()); |
||||
sheets.add(readSheet); |
||||
if (this.analyAllSheet) { |
||||
context.currentSheet(null, readSheet); |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void init() { |
||||
if (context.readSheetHolder() == null) { |
||||
this.analyAllSheet = true; |
||||
} |
||||
sheetIndex = 0; |
||||
orderedBsrs = null; |
||||
boundSheetRecords.clear(); |
||||
sheets.clear(); |
||||
} |
||||
|
||||
@Override |
||||
public int getOrder() { |
||||
return 0; |
||||
} |
||||
} |
@ -0,0 +1,114 @@
|
||||
package com.alibaba.excel.analysis.v03.handlers; |
||||
|
||||
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener; |
||||
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.hssf.record.StringRecord; |
||||
import org.apache.poi.hssf.usermodel.HSSFWorkbook; |
||||
import org.apache.poi.ss.usermodel.CellType; |
||||
import org.slf4j.Logger; |
||||
import org.slf4j.LoggerFactory; |
||||
|
||||
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
|
||||
/** |
||||
* Record handler |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public class FormulaRecordHandler extends AbstractXlsRecordHandler { |
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FormulaRecordHandler.class); |
||||
|
||||
private static final String ERROR = "#VALUE!"; |
||||
private int nextRow; |
||||
private int nextColumn; |
||||
private boolean outputNextStringRecord; |
||||
private CellData tempCellData; |
||||
private FormatTrackingHSSFListener formatListener; |
||||
private HSSFWorkbook stubWorkbook; |
||||
|
||||
public FormulaRecordHandler(HSSFWorkbook stubWorkbook, FormatTrackingHSSFListener formatListener) { |
||||
this.stubWorkbook = stubWorkbook; |
||||
this.formatListener = formatListener; |
||||
} |
||||
|
||||
@Override |
||||
public boolean support(Record record) { |
||||
return FormulaRecord.sid == record.getSid() || StringRecord.sid == record.getSid(); |
||||
} |
||||
|
||||
@Override |
||||
public void processRecord(Record record) { |
||||
if (record.getSid() == FormulaRecord.sid) { |
||||
FormulaRecord frec = (FormulaRecord)record; |
||||
|
||||
this.row = frec.getRow(); |
||||
this.column = frec.getColumn(); |
||||
CellType cellType = CellType.forInt(frec.getCachedResultType()); |
||||
String formulaValue = null; |
||||
try { |
||||
formulaValue = HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()); |
||||
} catch (Exception e) { |
||||
LOGGER.warn("Get formula value error.{}", e.getMessage()); |
||||
} |
||||
switch (cellType) { |
||||
case STRING: |
||||
// Formula result is a string
|
||||
// This is stored in the next record
|
||||
outputNextStringRecord = true; |
||||
nextRow = frec.getRow(); |
||||
nextColumn = frec.getColumn(); |
||||
tempCellData = new CellData(CellDataTypeEnum.STRING); |
||||
tempCellData.setFormula(Boolean.TRUE); |
||||
tempCellData.setFormulaValue(formulaValue); |
||||
break; |
||||
case NUMERIC: |
||||
this.cellData = new CellData(frec.getValue()); |
||||
this.cellData.setFormula(Boolean.TRUE); |
||||
this.cellData.setFormulaValue(formulaValue); |
||||
break; |
||||
case ERROR: |
||||
this.cellData = new CellData(CellDataTypeEnum.ERROR); |
||||
this.cellData.setStringValue(ERROR); |
||||
this.cellData.setFormula(Boolean.TRUE); |
||||
this.cellData.setFormulaValue(formulaValue); |
||||
break; |
||||
case BOOLEAN: |
||||
this.cellData = new CellData(frec.getCachedBooleanValue()); |
||||
this.cellData.setFormula(Boolean.TRUE); |
||||
this.cellData.setFormulaValue(formulaValue); |
||||
break; |
||||
default: |
||||
this.cellData = new CellData(CellDataTypeEnum.EMPTY); |
||||
this.cellData.setFormula(Boolean.TRUE); |
||||
this.cellData.setFormulaValue(formulaValue); |
||||
break; |
||||
} |
||||
} else if (record.getSid() == StringRecord.sid) { |
||||
if (outputNextStringRecord) { |
||||
// String for formula
|
||||
StringRecord srec = (StringRecord)record; |
||||
this.cellData = tempCellData; |
||||
this.cellData.setStringValue(srec.getString()); |
||||
this.row = nextRow; |
||||
this.column = nextColumn; |
||||
outputNextStringRecord = false; |
||||
tempCellData = null; |
||||
} |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void init() { |
||||
this.nextRow = 0; |
||||
this.nextColumn = 0; |
||||
} |
||||
|
||||
@Override |
||||
public int getOrder() { |
||||
return 0; |
||||
} |
||||
} |
@ -0,0 +1,37 @@
|
||||
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.AbstractXlsRecordHandler; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
|
||||
/** |
||||
* Record handler |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public class LabelRecordHandler extends AbstractXlsRecordHandler { |
||||
@Override |
||||
public boolean support(Record record) { |
||||
return LabelRecord.sid == record.getSid(); |
||||
} |
||||
|
||||
@Override |
||||
public void processRecord(Record record) { |
||||
LabelRecord lrec = (LabelRecord)record; |
||||
this.row = lrec.getRow(); |
||||
this.column = lrec.getColumn(); |
||||
this.cellData = new CellData(lrec.getValue()); |
||||
} |
||||
|
||||
@Override |
||||
public void init() { |
||||
|
||||
} |
||||
|
||||
@Override |
||||
public int getOrder() { |
||||
return 0; |
||||
} |
||||
} |
@ -0,0 +1,38 @@
|
||||
package com.alibaba.excel.analysis.v03.handlers; |
||||
|
||||
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord; |
||||
import org.apache.poi.hssf.record.Record; |
||||
|
||||
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
|
||||
/** |
||||
* Record handler |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public class MissingCellDummyRecordHandler extends AbstractXlsRecordHandler { |
||||
@Override |
||||
public boolean support(Record record) { |
||||
return record instanceof MissingCellDummyRecord; |
||||
} |
||||
|
||||
@Override |
||||
public void init() { |
||||
|
||||
} |
||||
|
||||
@Override |
||||
public void processRecord(Record record) { |
||||
MissingCellDummyRecord mcdr = (MissingCellDummyRecord)record; |
||||
this.row = mcdr.getRow(); |
||||
this.column = mcdr.getColumn(); |
||||
this.cellData = new CellData(CellDataTypeEnum.EMPTY); |
||||
} |
||||
|
||||
@Override |
||||
public int getOrder() { |
||||
return 1; |
||||
} |
||||
} |
@ -0,0 +1,38 @@
|
||||
package com.alibaba.excel.analysis.v03.handlers; |
||||
|
||||
import org.apache.poi.hssf.record.NoteRecord; |
||||
import org.apache.poi.hssf.record.Record; |
||||
|
||||
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
|
||||
/** |
||||
* Record handler |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public class NoteRecordHandler extends AbstractXlsRecordHandler { |
||||
@Override |
||||
public boolean support(Record record) { |
||||
return NoteRecord.sid == record.getSid(); |
||||
} |
||||
|
||||
@Override |
||||
public void processRecord(Record record) { |
||||
NoteRecord nrec = (NoteRecord)record; |
||||
this.row = nrec.getRow(); |
||||
this.column = nrec.getColumn(); |
||||
this.cellData = new CellData(CellDataTypeEnum.EMPTY); |
||||
} |
||||
|
||||
@Override |
||||
public void init() { |
||||
|
||||
} |
||||
|
||||
@Override |
||||
public int getOrder() { |
||||
return 0; |
||||
} |
||||
} |
@ -0,0 +1,46 @@
|
||||
package com.alibaba.excel.analysis.v03.handlers; |
||||
|
||||
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener; |
||||
import org.apache.poi.hssf.record.NumberRecord; |
||||
import org.apache.poi.hssf.record.Record; |
||||
|
||||
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
|
||||
/** |
||||
* Record handler |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public class NumberRecordHandler extends AbstractXlsRecordHandler { |
||||
private FormatTrackingHSSFListener formatListener; |
||||
|
||||
public NumberRecordHandler(FormatTrackingHSSFListener formatListener) { |
||||
this.formatListener = formatListener; |
||||
} |
||||
|
||||
@Override |
||||
public boolean support(Record record) { |
||||
return NumberRecord.sid == record.getSid(); |
||||
} |
||||
|
||||
@Override |
||||
public void processRecord(Record record) { |
||||
NumberRecord numrec = (NumberRecord)record; |
||||
this.row = numrec.getRow(); |
||||
this.column = numrec.getColumn(); |
||||
this.cellData = new CellData(numrec.getValue()); |
||||
this.cellData.setDataFormat(formatListener.getFormatIndex(numrec)); |
||||
this.cellData.setDataFormatString(formatListener.getFormatString(numrec)); |
||||
} |
||||
|
||||
@Override |
||||
public void init() { |
||||
|
||||
} |
||||
|
||||
@Override |
||||
public int getOrder() { |
||||
return 0; |
||||
} |
||||
} |
@ -0,0 +1,39 @@
|
||||
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.AbstractXlsRecordHandler; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
|
||||
/** |
||||
* Record handler |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public class RkRecordHandler extends AbstractXlsRecordHandler { |
||||
@Override |
||||
public boolean support(Record record) { |
||||
return RKRecord.sid == record.getSid(); |
||||
} |
||||
|
||||
@Override |
||||
public void processRecord(Record record) { |
||||
RKRecord rkrec = (RKRecord)record; |
||||
|
||||
this.row = rkrec.getRow(); |
||||
this.row = rkrec.getColumn(); |
||||
this.cellData = new CellData(CellDataTypeEnum.EMPTY); |
||||
} |
||||
|
||||
@Override |
||||
public void init() { |
||||
|
||||
} |
||||
|
||||
@Override |
||||
public int getOrder() { |
||||
return 0; |
||||
} |
||||
} |
@ -0,0 +1,49 @@
|
||||
package com.alibaba.excel.analysis.v03.handlers; |
||||
|
||||
import org.apache.poi.hssf.record.LabelSSTRecord; |
||||
import org.apache.poi.hssf.record.Record; |
||||
import org.apache.poi.hssf.record.SSTRecord; |
||||
|
||||
import com.alibaba.excel.analysis.v03.AbstractXlsRecordHandler; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
|
||||
/** |
||||
* Record handler |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public class SstRecordHandler extends AbstractXlsRecordHandler { |
||||
private SSTRecord sstRecord; |
||||
|
||||
@Override |
||||
public boolean support(Record record) { |
||||
return SSTRecord.sid == record.getSid() || LabelSSTRecord.sid == record.getSid(); |
||||
} |
||||
|
||||
@Override |
||||
public void processRecord(Record record) { |
||||
if (record.getSid() == SSTRecord.sid) { |
||||
sstRecord = (SSTRecord)record; |
||||
} else if (record.getSid() == LabelSSTRecord.sid) { |
||||
LabelSSTRecord lsrec = (LabelSSTRecord)record; |
||||
this.row = lsrec.getRow(); |
||||
this.column = lsrec.getColumn(); |
||||
if (sstRecord == null) { |
||||
this.cellData = new CellData(CellDataTypeEnum.EMPTY); |
||||
} else { |
||||
this.cellData = new CellData(sstRecord.getString(lsrec.getSSTIndex()).toString()); |
||||
} |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void init() { |
||||
|
||||
} |
||||
|
||||
@Override |
||||
public int getOrder() { |
||||
return 0; |
||||
} |
||||
} |
@ -0,0 +1,51 @@
|
||||
package com.alibaba.excel.analysis.v07; |
||||
|
||||
import org.xml.sax.Attributes; |
||||
import org.xml.sax.helpers.DefaultHandler; |
||||
|
||||
import com.alibaba.excel.cache.ReadCache; |
||||
|
||||
/** |
||||
* Sax read sharedStringsTable.xml |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class SharedStringsTableHandler extends DefaultHandler { |
||||
private static final String T_TAG = "t"; |
||||
private static final String SI_TAG = "si"; |
||||
/** |
||||
* The final piece of data |
||||
*/ |
||||
private String currentData; |
||||
/** |
||||
* Current element data |
||||
*/ |
||||
private String currentElementData; |
||||
|
||||
private ReadCache readCache; |
||||
|
||||
public SharedStringsTableHandler(ReadCache readCache) { |
||||
this.readCache = readCache; |
||||
} |
||||
|
||||
@Override |
||||
public void startElement(String uri, String localName, String name, Attributes attributes) { |
||||
if (SI_TAG.equals(name)) { |
||||
currentData = ""; |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void endElement(String uri, String localName, String name) { |
||||
if (T_TAG.equals(name)) { |
||||
currentData += currentElementData; |
||||
} else if (SI_TAG.equals(name)) { |
||||
readCache.put(currentData); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void characters(char[] ch, int start, int length) { |
||||
currentElementData = new String(ch, start, length); |
||||
} |
||||
} |
@ -0,0 +1,37 @@
|
||||
package com.alibaba.excel.analysis.v07; |
||||
|
||||
import org.xml.sax.Attributes; |
||||
|
||||
/** |
||||
* Cell handler |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public interface XlsxCellHandler { |
||||
/** |
||||
* Which tags are supported |
||||
* |
||||
* @param name |
||||
* Tag name |
||||
* @return Support parsing or not |
||||
*/ |
||||
boolean support(String name); |
||||
|
||||
/** |
||||
* Start handle |
||||
* |
||||
* @param name |
||||
* Tag name |
||||
* @param attributes |
||||
* Tag attributes |
||||
*/ |
||||
void startHandle(String name, Attributes attributes); |
||||
|
||||
/** |
||||
* End handle |
||||
* |
||||
* @param name |
||||
* Tag name |
||||
*/ |
||||
void endHandle(String name); |
||||
} |
@ -0,0 +1,27 @@
|
||||
package com.alibaba.excel.analysis.v07; |
||||
|
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
|
||||
import org.apache.poi.xssf.model.StylesTable; |
||||
|
||||
import com.alibaba.excel.analysis.v07.handlers.CountRowCellHandler; |
||||
import com.alibaba.excel.analysis.v07.handlers.DefaultCellHandler; |
||||
import com.alibaba.excel.analysis.v07.handlers.ProcessResultCellHandler; |
||||
import com.alibaba.excel.context.AnalysisContext; |
||||
|
||||
/** |
||||
* Build handler |
||||
* |
||||
* @author Dan Zheng |
||||
*/ |
||||
public class XlsxHandlerFactory { |
||||
public static List<XlsxCellHandler> buildCellHandlers(AnalysisContext analysisContext, StylesTable stylesTable) { |
||||
List<XlsxCellHandler> result = new ArrayList<XlsxCellHandler>(); |
||||
result.add(new CountRowCellHandler(analysisContext)); |
||||
DefaultCellHandler defaultCellHandler = new DefaultCellHandler(analysisContext, stylesTable); |
||||
result.add(defaultCellHandler); |
||||
result.add(new ProcessResultCellHandler(analysisContext, defaultCellHandler)); |
||||
return result; |
||||
} |
||||
} |
@ -0,0 +1,31 @@
|
||||
package com.alibaba.excel.analysis.v07; |
||||
|
||||
import java.util.Map; |
||||
|
||||
import com.alibaba.excel.metadata.CellData; |
||||
|
||||
/** |
||||
* Result holder |
||||
* |
||||
* @author jipengfei |
||||
*/ |
||||
public interface XlsxRowResultHolder { |
||||
/** |
||||
* Clear Result |
||||
*/ |
||||
void clearResult(); |
||||
|
||||
/** |
||||
* Append current 'cellValue' |
||||
* |
||||
* @param currentCellValue |
||||
*/ |
||||
void appendCurrentCellValue(String currentCellValue); |
||||
|
||||
/** |
||||
* Get row content |
||||
* |
||||
* @return |
||||
*/ |
||||
Map<Integer, CellData> getCurRowContent(); |
||||
} |
@ -0,0 +1,42 @@
|
||||
package com.alibaba.excel.analysis.v07.handlers; |
||||
|
||||
import static com.alibaba.excel.constant.ExcelXmlConstants.DIMENSION; |
||||
import static com.alibaba.excel.constant.ExcelXmlConstants.DIMENSION_REF; |
||||
|
||||
import org.xml.sax.Attributes; |
||||
|
||||
import com.alibaba.excel.analysis.v07.XlsxCellHandler; |
||||
import com.alibaba.excel.context.AnalysisContext; |
||||
|
||||
/** |
||||
* Cell Handler |
||||
* |
||||
* @author jipengfei |
||||
*/ |
||||
public class CountRowCellHandler implements XlsxCellHandler { |
||||
|
||||
private final AnalysisContext analysisContext; |
||||
|
||||
public CountRowCellHandler(AnalysisContext analysisContext) { |
||||
this.analysisContext = analysisContext; |
||||
} |
||||
|
||||
@Override |
||||
public boolean support(String name) { |
||||
return DIMENSION.equals(name); |
||||
} |
||||
|
||||
@Override |
||||
public void startHandle(String name, Attributes attributes) { |
||||
String d = attributes.getValue(DIMENSION_REF); |
||||
String totalStr = d.substring(d.indexOf(":") + 1, d.length()); |
||||
String c = totalStr.toUpperCase().replaceAll("[A-Z]", ""); |
||||
analysisContext.readSheetHolder().setTotal(Integer.parseInt(c)); |
||||
} |
||||
|
||||
@Override |
||||
public void endHandle(String name) { |
||||
|
||||
} |
||||
|
||||
} |
@ -0,0 +1,182 @@
|
||||
package com.alibaba.excel.analysis.v07.handlers; |
||||
|
||||
import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_DATA_FORMAT_TAG; |
||||
import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_FORMULA_TAG; |
||||
import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_INLINE_STRING_VALUE_TAG; |
||||
import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_TAG; |
||||
import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_VALUE_TAG; |
||||
import static com.alibaba.excel.constant.ExcelXmlConstants.CELL_VALUE_TYPE_TAG; |
||||
|
||||
import java.util.Map; |
||||
import java.util.TreeMap; |
||||
|
||||
import org.apache.poi.ss.usermodel.BuiltinFormats; |
||||
import org.apache.poi.xssf.model.StylesTable; |
||||
import org.apache.poi.xssf.usermodel.XSSFCellStyle; |
||||
import org.apache.poi.xssf.usermodel.XSSFRichTextString; |
||||
import org.xml.sax.Attributes; |
||||
|
||||
import com.alibaba.excel.analysis.v07.XlsxCellHandler; |
||||
import com.alibaba.excel.analysis.v07.XlsxRowResultHolder; |
||||
import com.alibaba.excel.constant.ExcelXmlConstants; |
||||
import com.alibaba.excel.context.AnalysisContext; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
import com.alibaba.excel.read.metadata.holder.ReadRowHolder; |
||||
import com.alibaba.excel.util.BooleanUtils; |
||||
import com.alibaba.excel.util.PositionUtils; |
||||
import com.alibaba.excel.util.StringUtils; |
||||
|
||||
/** |
||||
* Cell Handler |
||||
* |
||||
* @author jipengfei |
||||
*/ |
||||
public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder { |
||||
private final AnalysisContext analysisContext; |
||||
private String currentTag; |
||||
private String currentCellIndex; |
||||
private int curRow; |
||||
private int curCol; |
||||
private Map<Integer, CellData> curRowContent = new TreeMap<Integer, CellData>(); |
||||
private CellData currentCellData; |
||||
/** |
||||
* Current style information |
||||
*/ |
||||
private StylesTable stylesTable; |
||||
|
||||
public DefaultCellHandler(AnalysisContext analysisContext, StylesTable stylesTable) { |
||||
this.analysisContext = analysisContext; |
||||
this.stylesTable = stylesTable; |
||||
} |
||||
|
||||
@Override |
||||
public void clearResult() { |
||||
curRowContent = new TreeMap<Integer, CellData>(); |
||||
} |
||||
|
||||
@Override |
||||
public boolean support(String name) { |
||||
return CELL_VALUE_TAG.equals(name) || CELL_FORMULA_TAG.equals(name) || CELL_INLINE_STRING_VALUE_TAG.equals(name) |
||||
|| CELL_TAG.equals(name); |
||||
} |
||||
|
||||
@Override |
||||
public void startHandle(String name, Attributes attributes) { |
||||
currentTag = name; |
||||
// start a cell
|
||||
if (CELL_TAG.equals(name)) { |
||||
currentCellIndex = attributes.getValue(ExcelXmlConstants.POSITION); |
||||
int nextRow = PositionUtils.getRow(currentCellIndex); |
||||
if (nextRow > curRow) { |
||||
curRow = nextRow; |
||||
} |
||||
analysisContext |
||||
.readRowHolder(new ReadRowHolder(curRow, analysisContext.readSheetHolder().getGlobalConfiguration())); |
||||
curCol = PositionUtils.getCol(currentCellIndex); |
||||
|
||||
// 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
|
||||
CellDataTypeEnum type = CellDataTypeEnum.buildFromCellType(attributes.getValue(CELL_VALUE_TYPE_TAG)); |
||||
currentCellData = new CellData(type); |
||||
|
||||
// Put in data transformation information
|
||||
String dateFormatIndex = attributes.getValue(CELL_DATA_FORMAT_TAG); |
||||
if (dateFormatIndex != null) { |
||||
int dateFormatIndexInteger = Integer.parseInt(dateFormatIndex); |
||||
XSSFCellStyle xssfCellStyle = stylesTable.getStyleAt(dateFormatIndexInteger); |
||||
int dataFormat = xssfCellStyle.getDataFormat(); |
||||
String dataFormatString = xssfCellStyle.getDataFormatString(); |
||||
currentCellData.setDataFormat(dataFormat); |
||||
if (dataFormatString == null) { |
||||
currentCellData.setDataFormatString(BuiltinFormats.getBuiltinFormat(dataFormat)); |
||||
} else { |
||||
currentCellData.setDataFormatString(dataFormatString); |
||||
} |
||||
} |
||||
} |
||||
// cell is formula
|
||||
if (CELL_FORMULA_TAG.equals(name)) { |
||||
currentCellData.setFormula(Boolean.TRUE); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void endHandle(String name) { |
||||
if (CELL_VALUE_TAG.equals(name)) { |
||||
// Have to go "sharedStrings.xml" and get it
|
||||
if (currentCellData.getType() == CellDataTypeEnum.STRING) { |
||||
String stringValue = analysisContext.readWorkbookHolder().getReadCache() |
||||
.get(Integer.valueOf(currentCellData.getStringValue())); |
||||
if (stringValue != null && analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()) { |
||||
stringValue = stringValue.trim(); |
||||
} |
||||
currentCellData.setStringValue(stringValue); |
||||
} else if (currentCellData.getType() == CellDataTypeEnum.DIRECT_STRING) { |
||||
currentCellData.setType(CellDataTypeEnum.STRING); |
||||
} |
||||
curRowContent.put(curCol, currentCellData); |
||||
} |
||||
// This is a special form of string
|
||||
if (CELL_INLINE_STRING_VALUE_TAG.equals(name)) { |
||||
XSSFRichTextString richTextString = new XSSFRichTextString(currentCellData.getStringValue()); |
||||
String stringValue = richTextString.toString(); |
||||
if (stringValue != null && analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()) { |
||||
stringValue = stringValue.trim(); |
||||
} |
||||
currentCellData.setStringValue(stringValue); |
||||
curRowContent.put(curCol, currentCellData); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void appendCurrentCellValue(String currentCellValue) { |
||||
if (StringUtils.isEmpty(currentCellValue)) { |
||||
return; |
||||
} |
||||
if (currentTag == null) { |
||||
return; |
||||
} |
||||
if (CELL_FORMULA_TAG.equals(currentTag)) { |
||||
currentCellData.setFormulaValue(currentCellValue); |
||||
return; |
||||
} |
||||
CellDataTypeEnum oldType = currentCellData.getType(); |
||||
switch (oldType) { |
||||
case DIRECT_STRING: |
||||
case STRING: |
||||
case ERROR: |
||||
if (currentCellData.getStringValue() == null) { |
||||
currentCellData.setStringValue(currentCellValue); |
||||
} else { |
||||
currentCellData.setStringValue(currentCellData.getStringValue() + currentCellValue); |
||||
} |
||||
break; |
||||
case BOOLEAN: |
||||
if (currentCellData.getBooleanValue() == null) { |
||||
currentCellData.setBooleanValue(BooleanUtils.valueOf(currentCellValue)); |
||||
} |
||||
break; |
||||
case NUMBER: |
||||
case EMPTY: |
||||
currentCellData.setType(CellDataTypeEnum.NUMBER); |
||||
if (currentCellData.getDoubleValue() == null) { |
||||
currentCellData.setDoubleValue(Double.valueOf(currentCellValue)); |
||||
} |
||||
break; |
||||
default: |
||||
throw new IllegalStateException("Cannot set values now"); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public Map<Integer, CellData> getCurRowContent() { |
||||
return curRowContent; |
||||
} |
||||
|
||||
} |
@ -0,0 +1,41 @@
|
||||
package com.alibaba.excel.analysis.v07.handlers; |
||||
|
||||
import static com.alibaba.excel.constant.ExcelXmlConstants.ROW_TAG; |
||||
|
||||
import org.xml.sax.Attributes; |
||||
|
||||
import com.alibaba.excel.analysis.v07.XlsxCellHandler; |
||||
import com.alibaba.excel.analysis.v07.XlsxRowResultHolder; |
||||
import com.alibaba.excel.context.AnalysisContext; |
||||
import com.alibaba.excel.read.listener.event.EachRowAnalysisFinishEvent; |
||||
|
||||
/** |
||||
* Cell Handler |
||||
* |
||||
* @author jipengfei |
||||
*/ |
||||
public class ProcessResultCellHandler implements XlsxCellHandler { |
||||
private AnalysisContext analysisContext; |
||||
private XlsxRowResultHolder rowResultHandler; |
||||
|
||||
public ProcessResultCellHandler(AnalysisContext analysisContext, XlsxRowResultHolder rowResultHandler) { |
||||
this.analysisContext = analysisContext; |
||||
this.rowResultHandler = rowResultHandler; |
||||
} |
||||
|
||||
@Override |
||||
public boolean support(String name) { |
||||
return ROW_TAG.equals(name); |
||||
} |
||||
|
||||
@Override |
||||
public void startHandle(String name, Attributes attributes) {} |
||||
|
||||
@Override |
||||
public void endHandle(String name) { |
||||
analysisContext.readSheetHolder() |
||||
.notifyEndOneRow(new EachRowAnalysisFinishEvent(rowResultHandler.getCurRowContent()), analysisContext); |
||||
rowResultHandler.clearResult(); |
||||
} |
||||
|
||||
} |
@ -1,34 +0,0 @@
|
||||
package com.alibaba.excel.annotation; |
||||
|
||||
import java.lang.annotation.ElementType; |
||||
import java.lang.annotation.Inherited; |
||||
import java.lang.annotation.Retention; |
||||
import java.lang.annotation.RetentionPolicy; |
||||
import java.lang.annotation.Target; |
||||
|
||||
/** |
||||
* Created by jipengfei on 17/3/19. |
||||
* Field column num at excel head |
||||
* |
||||
* @author jipengfei |
||||
*/ |
||||
@Target(ElementType.FIELD) |
||||
@Retention(RetentionPolicy.RUNTIME) |
||||
@Inherited |
||||
public @interface ExcelColumnNum { |
||||
|
||||
/** |
||||
* col num |
||||
* @return |
||||
*/ |
||||
int value(); |
||||
|
||||
/** |
||||
* |
||||
* Default @see com.alibaba.excel.util.TypeUtil |
||||
* if default is not meet you can set format |
||||
* |
||||
* @return |
||||
*/ |
||||
String format() default ""; |
||||
} |
@ -0,0 +1,17 @@
|
||||
package com.alibaba.excel.annotation; |
||||
|
||||
import java.lang.annotation.ElementType; |
||||
import java.lang.annotation.Inherited; |
||||
import java.lang.annotation.Retention; |
||||
import java.lang.annotation.RetentionPolicy; |
||||
import java.lang.annotation.Target; |
||||
|
||||
/** |
||||
* Ignore convert excel |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@Target(ElementType.FIELD) |
||||
@Retention(RetentionPolicy.RUNTIME) |
||||
@Inherited |
||||
public @interface ExcelIgnore {} |
@ -1,11 +0,0 @@
|
||||
package com.alibaba.excel.annotation; |
||||
|
||||
/** |
||||
* |
||||
* @author jipengfei |
||||
*/ |
||||
public enum FieldType { |
||||
|
||||
STRING, INT, LONG, DATE, BOOLEAN, DOUBLE,EMPTY; |
||||
|
||||
} |
@ -0,0 +1,38 @@
|
||||
package com.alibaba.excel.annotation.format; |
||||
|
||||
import java.lang.annotation.ElementType; |
||||
import java.lang.annotation.Inherited; |
||||
import java.lang.annotation.Retention; |
||||
import java.lang.annotation.RetentionPolicy; |
||||
import java.lang.annotation.Target; |
||||
|
||||
/** |
||||
* Convert date format. |
||||
* |
||||
* <p> |
||||
* write: It can be used on classes {@link java.util.Date} |
||||
* <p> |
||||
* read: It can be used on classes {@link String} |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@Target(ElementType.FIELD) |
||||
@Retention(RetentionPolicy.RUNTIME) |
||||
@Inherited |
||||
public @interface DateTimeFormat { |
||||
|
||||
/** |
||||
* |
||||
* Specific format reference {@link java.text.SimpleDateFormat} |
||||
* |
||||
* @return Format pattern |
||||
*/ |
||||
String value() default ""; |
||||
|
||||
/** |
||||
* True if date uses 1904 windowing, or false if using 1900 date windowing. |
||||
* |
||||
* @return True if date uses 1904 windowing, or false if using 1900 date windowing. |
||||
*/ |
||||
boolean use1904windowing() default false; |
||||
} |
@ -0,0 +1,39 @@
|
||||
package com.alibaba.excel.annotation.format; |
||||
|
||||
import java.lang.annotation.ElementType; |
||||
import java.lang.annotation.Inherited; |
||||
import java.lang.annotation.Retention; |
||||
import java.lang.annotation.RetentionPolicy; |
||||
import java.lang.annotation.Target; |
||||
import java.math.RoundingMode; |
||||
|
||||
/** |
||||
* Convert number format. |
||||
* |
||||
* <p> |
||||
* write: It can be used on classes that inherit {@link Number} |
||||
* <p> |
||||
* read: It can be used on classes {@link String} |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@Target(ElementType.FIELD) |
||||
@Retention(RetentionPolicy.RUNTIME) |
||||
@Inherited |
||||
public @interface NumberFormat { |
||||
|
||||
/** |
||||
* |
||||
* Specific format reference {@link org.apache.commons.math3.fraction.BigFractionFormat} |
||||
* |
||||
* @return Format pattern |
||||
*/ |
||||
String value() default ""; |
||||
|
||||
/** |
||||
* Rounded by default |
||||
* |
||||
* @return RoundingMode |
||||
*/ |
||||
RoundingMode roundingMode() default RoundingMode.HALF_UP; |
||||
} |
@ -0,0 +1,27 @@
|
||||
package com.alibaba.excel.annotation.write.style; |
||||
|
||||
import java.lang.annotation.ElementType; |
||||
import java.lang.annotation.Inherited; |
||||
import java.lang.annotation.Retention; |
||||
import java.lang.annotation.RetentionPolicy; |
||||
import java.lang.annotation.Target; |
||||
|
||||
/** |
||||
* Set the width of the table |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@Target({ElementType.FIELD, ElementType.TYPE}) |
||||
@Retention(RetentionPolicy.RUNTIME) |
||||
@Inherited |
||||
public @interface ColumnWidth { |
||||
|
||||
/** |
||||
* Column width |
||||
* <p> |
||||
* -1 means the default column width is used |
||||
* |
||||
* @return Column width |
||||
*/ |
||||
int value() default -1; |
||||
} |
@ -0,0 +1,27 @@
|
||||
package com.alibaba.excel.annotation.write.style; |
||||
|
||||
import java.lang.annotation.ElementType; |
||||
import java.lang.annotation.Inherited; |
||||
import java.lang.annotation.Retention; |
||||
import java.lang.annotation.RetentionPolicy; |
||||
import java.lang.annotation.Target; |
||||
|
||||
/** |
||||
* Set the height of each table |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@Target({ElementType.TYPE}) |
||||
@Retention(RetentionPolicy.RUNTIME) |
||||
@Inherited |
||||
public @interface ContentRowHeight { |
||||
|
||||
/** |
||||
* Set the content height |
||||
* <p> |
||||
* -1 mean the auto set height |
||||
* |
||||
* @return Content height |
||||
*/ |
||||
short value() default -1; |
||||
} |
@ -0,0 +1,26 @@
|
||||
package com.alibaba.excel.annotation.write.style; |
||||
|
||||
import java.lang.annotation.ElementType; |
||||
import java.lang.annotation.Inherited; |
||||
import java.lang.annotation.Retention; |
||||
import java.lang.annotation.RetentionPolicy; |
||||
import java.lang.annotation.Target; |
||||
|
||||
/** |
||||
* Set the height of each table |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@Target({ElementType.TYPE}) |
||||
@Retention(RetentionPolicy.RUNTIME) |
||||
@Inherited |
||||
public @interface HeadRowHeight { |
||||
/** |
||||
* Set the header height |
||||
* <p> |
||||
* -1 mean the auto set height |
||||
* |
||||
* @return Header height |
||||
*/ |
||||
short value() default -1; |
||||
} |
@ -0,0 +1,213 @@
|
||||
package com.alibaba.excel.cache; |
||||
|
||||
import java.io.File; |
||||
import java.util.HashMap; |
||||
import java.util.HashSet; |
||||
import java.util.Iterator; |
||||
import java.util.LinkedList; |
||||
import java.util.Map; |
||||
import java.util.Set; |
||||
import java.util.UUID; |
||||
|
||||
import org.ehcache.CacheManager; |
||||
import org.ehcache.PersistentCacheManager; |
||||
import org.ehcache.config.builders.CacheConfigurationBuilder; |
||||
import org.ehcache.config.builders.CacheManagerBuilder; |
||||
import org.ehcache.config.builders.ResourcePoolsBuilder; |
||||
import org.ehcache.config.units.MemoryUnit; |
||||
import org.slf4j.Logger; |
||||
import org.slf4j.LoggerFactory; |
||||
|
||||
import com.alibaba.excel.context.AnalysisContext; |
||||
import com.alibaba.excel.util.FileUtils; |
||||
import com.alibaba.excel.util.StringUtils; |
||||
|
||||
/** |
||||
* Default cache |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
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 CHECK_INTERVAL = 500; |
||||
private static final int MAX_CACHE_ACTIVATE = 10; |
||||
|
||||
private static final String CACHE = "cache"; |
||||
private static final String DATA_SEPARATOR = "@"; |
||||
private static final String KEY_VALUE_SEPARATOR = "!"; |
||||
private static final String SPECIAL_SEPARATOR = "&"; |
||||
private static final String ESCAPED_DATA_SEPARATOR = "&d;"; |
||||
private static final String ESCAPED_KEY_VALUE_SEPARATOR = "&kv;"; |
||||
private static final String ESCAPED_SPECIAL_SEPARATOR = "&s;"; |
||||
|
||||
private static final int DEBUG_WRITE_SIZE = 100 * 10000; |
||||
private static final int DEBUG_CACHE_MISS_SIZE = 1000; |
||||
|
||||
/** |
||||
* Key index |
||||
*/ |
||||
private int index = 0; |
||||
private StringBuilder data = new StringBuilder(); |
||||
private CacheManager cacheManager; |
||||
/** |
||||
* Bulk storage data |
||||
*/ |
||||
private org.ehcache.Cache<Integer, String> cache; |
||||
/** |
||||
* Currently active cache |
||||
*/ |
||||
private Map<Integer, Map<Integer, String>> cacheMap = new HashMap<Integer, Map<Integer, String>>(); |
||||
/** |
||||
* Count how many times get |
||||
*/ |
||||
private int getCount = 0; |
||||
/** |
||||
* Count active cache |
||||
* |
||||
*/ |
||||
private LinkedList<Integer> countList = new LinkedList<Integer>(); |
||||
|
||||
/** |
||||
* Count the last {@link #CHECK_INTERVAL} used |
||||
*/ |
||||
private Set<Integer> lastCheckIntervalUsedSet = new HashSet<Integer>(); |
||||
|
||||
/** |
||||
* Count the number of cache misses |
||||
*/ |
||||
private int cacheMiss = 0; |
||||
|
||||
@Override |
||||
public void init(AnalysisContext analysisContext) { |
||||
File readTempFile = analysisContext.readWorkbookHolder().getTempFile(); |
||||
if (readTempFile == null) { |
||||
readTempFile = FileUtils.createCacheTmpFile(); |
||||
analysisContext.readWorkbookHolder().setTempFile(readTempFile); |
||||
} |
||||
File cacheFile = new File(readTempFile.getPath(), UUID.randomUUID().toString()); |
||||
PersistentCacheManager persistentCacheManager = |
||||
CacheManagerBuilder.newCacheManagerBuilder().with(CacheManagerBuilder.persistence(cacheFile)) |
||||
.withCache(CACHE, CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, String.class, |
||||
ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MemoryUnit.GB))) |
||||
.build(true); |
||||
cacheManager = persistentCacheManager; |
||||
cache = persistentCacheManager.getCache(CACHE, Integer.class, String.class); |
||||
} |
||||
|
||||
@Override |
||||
public void put(String value) { |
||||
data.append(index).append(KEY_VALUE_SEPARATOR).append(escape(value)).append(DATA_SEPARATOR); |
||||
if ((index + 1) % BATCH_COUNT == 0) { |
||||
cache.put(index / BATCH_COUNT, data.toString()); |
||||
data = new StringBuilder(); |
||||
} |
||||
index++; |
||||
if (LOGGER.isDebugEnabled()) { |
||||
if (index % DEBUG_WRITE_SIZE == 0) { |
||||
LOGGER.debug("Already put :{}", index); |
||||
} |
||||
} |
||||
} |
||||
|
||||
private String escape(String str) { |
||||
if (StringUtils.isEmpty(str)) { |
||||
return str; |
||||
} |
||||
str = str.replaceAll(SPECIAL_SEPARATOR, ESCAPED_SPECIAL_SEPARATOR); |
||||
str = str.replaceAll(DATA_SEPARATOR, ESCAPED_DATA_SEPARATOR); |
||||
str = str.replaceAll(KEY_VALUE_SEPARATOR, ESCAPED_KEY_VALUE_SEPARATOR); |
||||
return str; |
||||
} |
||||
|
||||
private String unescape(String str) { |
||||
if (StringUtils.isEmpty(str)) { |
||||
return str; |
||||
} |
||||
str = str.replaceAll(ESCAPED_KEY_VALUE_SEPARATOR, KEY_VALUE_SEPARATOR); |
||||
str = str.replaceAll(ESCAPED_DATA_SEPARATOR, DATA_SEPARATOR); |
||||
str = str.replaceAll(ESCAPED_SPECIAL_SEPARATOR, SPECIAL_SEPARATOR); |
||||
return str; |
||||
} |
||||
|
||||
@Override |
||||
public String get(Integer key) { |
||||
if (key == null || key < 0) { |
||||
return null; |
||||
} |
||||
getCount++; |
||||
int route = key / BATCH_COUNT; |
||||
if (cacheMap.containsKey(route)) { |
||||
lastCheckIntervalUsedSet.add(route); |
||||
String value = cacheMap.get(route).get(key); |
||||
checkClear(); |
||||
return value; |
||||
} |
||||
Map<Integer, String> tempCacheMap = new HashMap<Integer, String>(BATCH_COUNT / 3 * 4 + 1); |
||||
String batchData = cache.get(route); |
||||
String[] dataStrings = batchData.split(DATA_SEPARATOR); |
||||
for (String dataString : dataStrings) { |
||||
String[] keyValue = dataString.split(KEY_VALUE_SEPARATOR); |
||||
tempCacheMap.put(Integer.valueOf(keyValue[0]), unescape(keyValue[1])); |
||||
} |
||||
countList.add(route); |
||||
cacheMap.put(route, tempCacheMap); |
||||
if (LOGGER.isDebugEnabled()) { |
||||
if (cacheMiss++ % DEBUG_CACHE_MISS_SIZE == 0) { |
||||
LOGGER.debug("Cache misses count:{}", cacheMiss); |
||||
} |
||||
} |
||||
lastCheckIntervalUsedSet.add(route); |
||||
String value = tempCacheMap.get(key); |
||||
checkClear(); |
||||
return value; |
||||
} |
||||
|
||||
private void checkClear() { |
||||
if (countList.size() > MAX_CACHE_ACTIVATE) { |
||||
Integer route = countList.getFirst(); |
||||
countList.removeFirst(); |
||||
cacheMap.remove(route); |
||||
} |
||||
if (getCount++ % CHECK_INTERVAL != 0) { |
||||
return; |
||||
} |
||||
Iterator<Map.Entry<Integer, Map<Integer, String>>> iterator = cacheMap.entrySet().iterator(); |
||||
while (iterator.hasNext()) { |
||||
Map.Entry<Integer, Map<Integer, String>> entry = iterator.next(); |
||||
if (lastCheckIntervalUsedSet.contains(entry.getKey())) { |
||||
continue; |
||||
} |
||||
// Last 'CHECK_INTERVAL' not use
|
||||
iterator.remove(); |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("Cache remove because {} times unused.", CHECK_INTERVAL); |
||||
} |
||||
Iterator<Integer> countIterator = countList.iterator(); |
||||
while (countIterator.hasNext()) { |
||||
Integer route = countIterator.next(); |
||||
if (route.equals(entry.getKey())) { |
||||
countIterator.remove(); |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
lastCheckIntervalUsedSet.clear(); |
||||
} |
||||
|
||||
@Override |
||||
public void putFinished() { |
||||
if (StringUtils.isEmpty(data.toString())) { |
||||
return; |
||||
} |
||||
cache.put(index / BATCH_COUNT, data.toString()); |
||||
} |
||||
|
||||
@Override |
||||
public void destroy() { |
||||
cacheManager.close(); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,40 @@
|
||||
package com.alibaba.excel.cache; |
||||
|
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
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; |
||||
|
||||
@Override |
||||
public void init(AnalysisContext analysisContext) {} |
||||
|
||||
@Override |
||||
public void put(String value) { |
||||
cache.put(index++, value); |
||||
} |
||||
|
||||
@Override |
||||
public String get(Integer key) { |
||||
if (key == null || key < 0) { |
||||
return null; |
||||
} |
||||
return cache.get(key); |
||||
} |
||||
|
||||
@Override |
||||
public void putFinished() {} |
||||
|
||||
@Override |
||||
public void destroy() {} |
||||
|
||||
} |
@ -0,0 +1,47 @@
|
||||
package com.alibaba.excel.cache; |
||||
|
||||
import com.alibaba.excel.context.AnalysisContext; |
||||
|
||||
/** |
||||
* Read cache |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public interface ReadCache { |
||||
|
||||
/** |
||||
* Initialize cache |
||||
* |
||||
* @param analysisContext |
||||
* A context is the main anchorage point of a excel reader. |
||||
*/ |
||||
void init(AnalysisContext analysisContext); |
||||
|
||||
/** |
||||
* Automatically generate the key and put it in the cache.Key start from 0 |
||||
* |
||||
* @param value |
||||
* Cache value |
||||
*/ |
||||
void put(String value); |
||||
|
||||
/** |
||||
* Get value |
||||
* |
||||
* @param key |
||||
* Index |
||||
* @return Value |
||||
*/ |
||||
String get(Integer key); |
||||
|
||||
/** |
||||
* It's called when all the values are put in |
||||
*/ |
||||
void putFinished(); |
||||
|
||||
/** |
||||
* Called when the excel read is complete |
||||
*/ |
||||
void destroy(); |
||||
|
||||
} |
@ -1,132 +1,137 @@
|
||||
package com.alibaba.excel.context; |
||||
|
||||
import java.io.InputStream; |
||||
|
||||
import com.alibaba.excel.analysis.ExcelExecutor; |
||||
import com.alibaba.excel.event.AnalysisEventListener; |
||||
import com.alibaba.excel.metadata.BaseRowModel; |
||||
import com.alibaba.excel.metadata.ExcelHeadProperty; |
||||
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; |
||||
import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; |
||||
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder; |
||||
import com.alibaba.excel.support.ExcelTypeEnum; |
||||
|
||||
import java.io.InputStream; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* |
||||
* A context is the main anchorage point of a excel reader. |
||||
* |
||||
* @author jipengfei |
||||
*/ |
||||
public interface AnalysisContext { |
||||
|
||||
/** |
||||
* Custom attribute |
||||
* Select the current table |
||||
* |
||||
* @param excelExecutor |
||||
* Excel file Executor |
||||
* @param readSheet |
||||
* sheet to read |
||||
*/ |
||||
Object getCustom(); |
||||
void currentSheet(ExcelExecutor excelExecutor, ReadSheet readSheet); |
||||
|
||||
/** |
||||
* get current sheet |
||||
* All information about the workbook you are currently working on |
||||
* |
||||
* @return current analysis sheet |
||||
* @return Current workbook holder |
||||
*/ |
||||
Sheet getCurrentSheet(); |
||||
ReadWorkbookHolder readWorkbookHolder(); |
||||
|
||||
/** |
||||
* set current sheet |
||||
* @param sheet |
||||
* All information about the sheet you are currently working on |
||||
* |
||||
* @return Current sheet holder |
||||
*/ |
||||
void setCurrentSheet(Sheet sheet); |
||||
ReadSheetHolder readSheetHolder(); |
||||
|
||||
/** |
||||
* Set row of currently operated cell |
||||
* |
||||
* get excel type |
||||
* @return excel type |
||||
* @param readRowHolder |
||||
* Current row holder |
||||
*/ |
||||
ExcelTypeEnum getExcelType(); |
||||
void readRowHolder(ReadRowHolder readRowHolder); |
||||
|
||||
/** |
||||
* get in io |
||||
* @return file io |
||||
* Row of currently operated cell |
||||
* |
||||
* @return Current row holder |
||||
*/ |
||||
InputStream getInputStream(); |
||||
ReadRowHolder readRowHolder(); |
||||
|
||||
/** |
||||
* The current read operation corresponds to the <code>readSheetHolder</code> or <code>readWorkbookHolder</code> |
||||
* |
||||
* custom listener |
||||
* @return listener |
||||
* @return Current holder |
||||
*/ |
||||
AnalysisEventListener getEventListener(); |
||||
ReadHolder currentReadHolder(); |
||||
|
||||
/** |
||||
* get current row |
||||
* Custom attribute |
||||
* |
||||
* @return |
||||
*/ |
||||
Integer getCurrentRowNum(); |
||||
|
||||
/** |
||||
* set current row num |
||||
* @param row |
||||
*/ |
||||
void setCurrentRowNum(Integer row); |
||||
Object getCustom(); |
||||
|
||||
/** |
||||
* get total row ,Data may be inaccurate |
||||
* @return |
||||
* get current sheet |
||||
* |
||||
* @return current analysis sheet |
||||
* @deprecated please use {@link #readSheetHolder()} |
||||
*/ |
||||
@Deprecated |
||||
Integer getTotalCount(); |
||||
Sheet getCurrentSheet(); |
||||
|
||||
/** |
||||
* get total row ,Data may be inaccurate |
||||
* |
||||
* @param totalCount |
||||
*/ |
||||
void setTotalCount(Integer totalCount); |
||||
|
||||
/** |
||||
* get excel head |
||||
* @return |
||||
* get excel type |
||||
* |
||||
* @return excel type |
||||
* @deprecated please use {@link #readWorkbookHolder()} |
||||
*/ |
||||
ExcelHeadProperty getExcelHeadProperty(); |
||||
@Deprecated |
||||
ExcelTypeEnum getExcelType(); |
||||
|
||||
/** |
||||
* get in io |
||||
* |
||||
* @param clazz |
||||
* @param headOneRow |
||||
* @return file io |
||||
* @deprecated please use {@link #readWorkbookHolder()} |
||||
*/ |
||||
void buildExcelHeadProperty(Class<? extends BaseRowModel> clazz, List<String> headOneRow); |
||||
@Deprecated |
||||
InputStream getInputStream(); |
||||
|
||||
/** |
||||
* get current row |
||||
* |
||||
*if need to short match the content |
||||
* @return |
||||
* @deprecated please use {@link #readRowHolder()} |
||||
*/ |
||||
boolean trim(); |
||||
@Deprecated |
||||
Integer getCurrentRowNum(); |
||||
|
||||
/** |
||||
* set current result |
||||
* @param result |
||||
* get total row ,Data may be inaccurate |
||||
* |
||||
* @return |
||||
* @deprecated please use {@link #readRowHolder()} |
||||
*/ |
||||
void setCurrentRowAnalysisResult(Object result); |
||||
|
||||
@Deprecated |
||||
Integer getTotalCount(); |
||||
|
||||
/** |
||||
* get current result |
||||
* @return get current result |
||||
* |
||||
* @return get current result |
||||
* @deprecated please use {@link #readRowHolder()} |
||||
*/ |
||||
@Deprecated |
||||
Object getCurrentRowAnalysisResult(); |
||||
|
||||
/** |
||||
* Interrupt execution |
||||
* |
||||
* @deprecated please use {@link AnalysisEventListener#hasNext(AnalysisContext)} |
||||
*/ |
||||
@Deprecated |
||||
void interrupt(); |
||||
|
||||
/** |
||||
* date use1904WindowDate |
||||
* @return |
||||
*/ |
||||
boolean use1904WindowDate(); |
||||
|
||||
/** |
||||
* date use1904WindowDate |
||||
* @param use1904WindowDate |
||||
*/ |
||||
void setUse1904WindowDate(boolean use1904WindowDate); |
||||
} |
||||
|
@ -1,172 +1,189 @@
|
||||
package com.alibaba.excel.context; |
||||
|
||||
import com.alibaba.excel.event.AnalysisEventListener; |
||||
import java.io.InputStream; |
||||
|
||||
import org.slf4j.Logger; |
||||
import org.slf4j.LoggerFactory; |
||||
|
||||
import com.alibaba.excel.analysis.ExcelExecutor; |
||||
import com.alibaba.excel.analysis.v07.XlsxSaxAnalyser; |
||||
import com.alibaba.excel.exception.ExcelAnalysisException; |
||||
import com.alibaba.excel.metadata.BaseRowModel; |
||||
import com.alibaba.excel.metadata.ExcelHeadProperty; |
||||
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.support.ExcelTypeEnum; |
||||
|
||||
import java.io.InputStream; |
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
import com.alibaba.excel.util.StringUtils; |
||||
|
||||
/** |
||||
* |
||||
* @author jipengfei |
||||
*/ |
||||
public class AnalysisContextImpl implements AnalysisContext { |
||||
|
||||
private Object custom; |
||||
|
||||
private Sheet currentSheet; |
||||
|
||||
private ExcelTypeEnum excelType; |
||||
|
||||
private InputStream inputStream; |
||||
|
||||
private AnalysisEventListener eventListener; |
||||
|
||||
private Integer currentRowNum; |
||||
|
||||
private Integer totalCount; |
||||
|
||||
private ExcelHeadProperty excelHeadProperty; |
||||
|
||||
private boolean trim; |
||||
|
||||
private boolean use1904WindowDate = false; |
||||
|
||||
@Override |
||||
public void setUse1904WindowDate(boolean use1904WindowDate) { |
||||
this.use1904WindowDate = use1904WindowDate; |
||||
private static final Logger LOGGER = LoggerFactory.getLogger(AnalysisContextImpl.class); |
||||
/** |
||||
* The Workbook currently written |
||||
*/ |
||||
private ReadWorkbookHolder readWorkbookHolder; |
||||
/** |
||||
* Current sheet holder |
||||
*/ |
||||
private ReadSheetHolder readSheetHolder; |
||||
/** |
||||
* Current row holder |
||||
*/ |
||||
private ReadRowHolder readRowHolder; |
||||
/** |
||||
* Configuration of currently operated cell |
||||
*/ |
||||
private ReadHolder currentReadHolder; |
||||
|
||||
public AnalysisContextImpl(ReadWorkbook readWorkbook) { |
||||
if (readWorkbook == null) { |
||||
throw new IllegalArgumentException("Workbook argument cannot be null"); |
||||
} |
||||
readWorkbookHolder = new ReadWorkbookHolder(readWorkbook); |
||||
currentReadHolder = readWorkbookHolder; |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("Initialization 'AnalysisContextImpl' complete"); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public Object getCurrentRowAnalysisResult() { |
||||
return currentRowAnalysisResult; |
||||
public void currentSheet(ExcelExecutor excelExecutor, ReadSheet readSheet) { |
||||
if (readSheet == null) { |
||||
throw new IllegalArgumentException("Sheet argument cannot be null."); |
||||
} |
||||
readSheetHolder = new ReadSheetHolder(readSheet, readWorkbookHolder); |
||||
currentReadHolder = readSheetHolder; |
||||
selectSheet(excelExecutor); |
||||
if (readWorkbookHolder.getHasReadSheet().contains(readSheetHolder.getSheetNo())) { |
||||
throw new ExcelAnalysisException("Cannot read sheet repeatedly."); |
||||
} |
||||
readWorkbookHolder.getHasReadSheet().add(readSheetHolder.getSheetNo()); |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("Began to read:{}", readSheetHolder); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void interrupt() { |
||||
throw new ExcelAnalysisException("interrupt error"); |
||||
private void selectSheet(ExcelExecutor excelExecutor) { |
||||
if (excelExecutor instanceof XlsxSaxAnalyser) { |
||||
selectSheet07(excelExecutor); |
||||
} else { |
||||
selectSheet03(); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public boolean use1904WindowDate() { |
||||
return use1904WindowDate; |
||||
private void selectSheet03() { |
||||
if (readSheetHolder.getSheetNo() != null && readSheetHolder.getSheetNo() >= 0) { |
||||
return; |
||||
} |
||||
if (!StringUtils.isEmpty(readSheetHolder.getSheetName())) { |
||||
LOGGER.warn("Excel 2003 does not support matching sheets by name, defaults to the first one."); |
||||
} |
||||
readSheetHolder.setSheetNo(0); |
||||
} |
||||
|
||||
private void selectSheet07(ExcelExecutor excelExecutor) { |
||||
if (readSheetHolder.getSheetNo() != null && readSheetHolder.getSheetNo() >= 0) { |
||||
for (ReadSheet readSheetExcel : excelExecutor.sheetList()) { |
||||
if (readSheetExcel.getSheetNo().equals(readSheetHolder.getSheetNo())) { |
||||
readSheetHolder.setSheetName(readSheetExcel.getSheetName()); |
||||
return; |
||||
} |
||||
} |
||||
throw new ExcelAnalysisException("Can not find sheet:" + readSheetHolder.getSheetNo()); |
||||
} |
||||
if (!StringUtils.isEmpty(readSheetHolder.getSheetName())) { |
||||
for (ReadSheet readSheetExcel : excelExecutor.sheetList()) { |
||||
String sheetName = readSheetExcel.getSheetName(); |
||||
if (sheetName == null) { |
||||
continue; |
||||
} |
||||
if (readSheetHolder.globalConfiguration().getAutoTrim()) { |
||||
sheetName = sheetName.trim(); |
||||
} |
||||
if (sheetName.equals(readSheetHolder.getSheetName())) { |
||||
readSheetHolder.setSheetNo(readSheetExcel.getSheetNo()); |
||||
return; |
||||
} |
||||
} |
||||
} |
||||
ReadSheet readSheetExcel = excelExecutor.sheetList().get(0); |
||||
readSheetHolder.setSheetNo(readSheetExcel.getSheetNo()); |
||||
readSheetHolder.setSheetName(readSheetExcel.getSheetName()); |
||||
} |
||||
|
||||
@Override |
||||
public void setCurrentRowAnalysisResult(Object currentRowAnalysisResult) { |
||||
this.currentRowAnalysisResult = currentRowAnalysisResult; |
||||
} |
||||
|
||||
private Object currentRowAnalysisResult; |
||||
|
||||
public AnalysisContextImpl(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Object custom, |
||||
AnalysisEventListener listener, boolean trim) { |
||||
this.custom = custom; |
||||
this.eventListener = listener; |
||||
this.inputStream = inputStream; |
||||
this.excelType = excelTypeEnum; |
||||
this.trim = trim; |
||||
public ReadWorkbookHolder readWorkbookHolder() { |
||||
return readWorkbookHolder; |
||||
} |
||||
|
||||
@Override |
||||
public void setCurrentSheet(Sheet currentSheet) { |
||||
cleanCurrentSheet(); |
||||
this.currentSheet = currentSheet; |
||||
if (currentSheet.getClazz() != null) { |
||||
buildExcelHeadProperty(currentSheet.getClazz(), null); |
||||
} |
||||
public ReadSheetHolder readSheetHolder() { |
||||
return readSheetHolder; |
||||
} |
||||
|
||||
private void cleanCurrentSheet() { |
||||
this.currentSheet = null; |
||||
this.excelHeadProperty = null; |
||||
this.totalCount = 0; |
||||
this.currentRowAnalysisResult = null; |
||||
this.currentRowNum =0; |
||||
@Override |
||||
public ReadRowHolder readRowHolder() { |
||||
return readRowHolder; |
||||
} |
||||
|
||||
@Override |
||||
public ExcelTypeEnum getExcelType() { |
||||
return excelType; |
||||
public void readRowHolder(ReadRowHolder readRowHolder) { |
||||
this.readRowHolder = readRowHolder; |
||||
} |
||||
|
||||
public void setExcelType(ExcelTypeEnum excelType) { |
||||
this.excelType = excelType; |
||||
@Override |
||||
public ReadHolder currentReadHolder() { |
||||
return currentReadHolder; |
||||
} |
||||
|
||||
@Override |
||||
public Object getCustom() { |
||||
return custom; |
||||
} |
||||
|
||||
public void setCustom(Object custom) { |
||||
this.custom = custom; |
||||
return readWorkbookHolder.getCustomObject(); |
||||
} |
||||
|
||||
@Override |
||||
public Sheet getCurrentSheet() { |
||||
return currentSheet; |
||||
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 InputStream getInputStream() { |
||||
return inputStream; |
||||
} |
||||
|
||||
public void setInputStream(InputStream inputStream) { |
||||
this.inputStream = inputStream; |
||||
public ExcelTypeEnum getExcelType() { |
||||
return readWorkbookHolder.getExcelType(); |
||||
} |
||||
|
||||
@Override |
||||
public AnalysisEventListener getEventListener() { |
||||
return eventListener; |
||||
} |
||||
|
||||
public void setEventListener(AnalysisEventListener eventListener) { |
||||
this.eventListener = eventListener; |
||||
public InputStream getInputStream() { |
||||
return readWorkbookHolder.getInputStream(); |
||||
} |
||||
|
||||
@Override |
||||
public Integer getCurrentRowNum() { |
||||
return this.currentRowNum; |
||||
} |
||||
|
||||
@Override |
||||
public void setCurrentRowNum(Integer row) { |
||||
this.currentRowNum = row; |
||||
return readRowHolder.getRowIndex(); |
||||
} |
||||
|
||||
@Override |
||||
public Integer getTotalCount() { |
||||
return totalCount; |
||||
return readSheetHolder.getTotal(); |
||||
} |
||||
|
||||
@Override |
||||
public void setTotalCount(Integer totalCount) { |
||||
this.totalCount = totalCount; |
||||
} |
||||
|
||||
@Override |
||||
public ExcelHeadProperty getExcelHeadProperty() { |
||||
return this.excelHeadProperty; |
||||
} |
||||
|
||||
@Override |
||||
public void buildExcelHeadProperty(Class<? extends BaseRowModel> clazz, List<String> headOneRow) { |
||||
if (this.excelHeadProperty == null && (clazz != null || headOneRow != null)) { |
||||
this.excelHeadProperty = new ExcelHeadProperty(clazz, new ArrayList<List<String>>()); |
||||
} |
||||
if (this.excelHeadProperty.getHead() == null && headOneRow != null) { |
||||
this.excelHeadProperty.appendOneRow(headOneRow); |
||||
} |
||||
public Object getCurrentRowAnalysisResult() { |
||||
return readRowHolder.getCurrentRowAnalysisResult(); |
||||
} |
||||
|
||||
@Override |
||||
public boolean trim() { |
||||
return this.trim; |
||||
public void interrupt() { |
||||
throw new ExcelAnalysisException("interrupt error"); |
||||
} |
||||
} |
||||
|
@ -0,0 +1,398 @@
|
||||
package com.alibaba.excel.context; |
||||
|
||||
import java.io.OutputStream; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
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.slf4j.Logger; |
||||
import org.slf4j.LoggerFactory; |
||||
|
||||
import com.alibaba.excel.exception.ExcelGenerateException; |
||||
import com.alibaba.excel.metadata.Head; |
||||
import com.alibaba.excel.util.WorkBookUtil; |
||||
import com.alibaba.excel.write.handler.CellWriteHandler; |
||||
import com.alibaba.excel.write.handler.RowWriteHandler; |
||||
import com.alibaba.excel.write.handler.SheetWriteHandler; |
||||
import com.alibaba.excel.write.handler.WorkbookWriteHandler; |
||||
import com.alibaba.excel.write.handler.WriteHandler; |
||||
import com.alibaba.excel.write.metadata.WriteSheet; |
||||
import com.alibaba.excel.write.metadata.WriteTable; |
||||
import com.alibaba.excel.write.metadata.WriteWorkbook; |
||||
import com.alibaba.excel.write.metadata.holder.WriteHolder; |
||||
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; |
||||
import com.alibaba.excel.write.metadata.holder.WriteTableHolder; |
||||
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; |
||||
import com.alibaba.excel.write.property.ExcelWriteHeadProperty; |
||||
|
||||
/** |
||||
* A context is the main anchorage point of a excel writer. |
||||
* |
||||
* @author jipengfei |
||||
*/ |
||||
public class WriteContextImpl implements WriteContext { |
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(WriteContextImpl.class); |
||||
|
||||
/** |
||||
* The Workbook currently written |
||||
*/ |
||||
private WriteWorkbookHolder writeWorkbookHolder; |
||||
/** |
||||
* Current sheet holder |
||||
*/ |
||||
private WriteSheetHolder writeSheetHolder; |
||||
/** |
||||
* The table currently written |
||||
*/ |
||||
private WriteTableHolder writeTableHolder; |
||||
/** |
||||
* Configuration of currently operated cell |
||||
*/ |
||||
private WriteHolder currentWriteHolder; |
||||
|
||||
public WriteContextImpl(WriteWorkbook writeWorkbook) { |
||||
if (writeWorkbook == null) { |
||||
throw new IllegalArgumentException("Workbook argument cannot be null"); |
||||
} |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("Begin to Initialization 'WriteContextImpl'"); |
||||
} |
||||
initCurrentWorkbookHolder(writeWorkbook); |
||||
beforeWorkbookCreate(); |
||||
try { |
||||
writeWorkbookHolder.setWorkbook(WorkBookUtil.createWorkBook(writeWorkbookHolder)); |
||||
} catch (Exception e) { |
||||
throw new ExcelGenerateException("Create workbook failure", e); |
||||
} |
||||
afterWorkbookCreate(); |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("Initialization 'WriteContextImpl' complete"); |
||||
} |
||||
} |
||||
|
||||
private void beforeWorkbookCreate() { |
||||
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(WorkbookWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof WorkbookWriteHandler) { |
||||
((WorkbookWriteHandler)writeHandler).beforeWorkbookCreate(); |
||||
} |
||||
} |
||||
} |
||||
|
||||
private void afterWorkbookCreate() { |
||||
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(WorkbookWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof WorkbookWriteHandler) { |
||||
((WorkbookWriteHandler)writeHandler).afterWorkbookCreate(writeWorkbookHolder); |
||||
} |
||||
} |
||||
} |
||||
|
||||
private void initCurrentWorkbookHolder(WriteWorkbook writeWorkbook) { |
||||
writeWorkbookHolder = new WriteWorkbookHolder(writeWorkbook); |
||||
currentWriteHolder = writeWorkbookHolder; |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("CurrentConfiguration is writeWorkbookHolder"); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* @param writeSheet |
||||
*/ |
||||
@Override |
||||
public void currentSheet(WriteSheet writeSheet) { |
||||
if (writeSheet == null) { |
||||
throw new IllegalArgumentException("Sheet argument cannot be null"); |
||||
} |
||||
if (writeSheet.getSheetNo() == null || writeSheet.getSheetNo() <= 0) { |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("Sheet number is null"); |
||||
} |
||||
writeSheet.setSheetNo(0); |
||||
} |
||||
if (writeWorkbookHolder.getHasBeenInitializedSheet().containsKey(writeSheet.getSheetNo())) { |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("Sheet:{} is already existed", writeSheet.getSheetNo()); |
||||
} |
||||
writeSheetHolder = writeWorkbookHolder.getHasBeenInitializedSheet().get(writeSheet.getSheetNo()); |
||||
writeSheetHolder.setNewInitialization(Boolean.FALSE); |
||||
writeTableHolder = null; |
||||
currentWriteHolder = writeSheetHolder; |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("CurrentConfiguration is writeSheetHolder"); |
||||
} |
||||
return; |
||||
} |
||||
initCurrentSheetHolder(writeSheet); |
||||
beforeSheetCreate(); |
||||
// Initialization current sheet
|
||||
initSheet(); |
||||
afterSheetCreate(); |
||||
} |
||||
|
||||
private void beforeSheetCreate() { |
||||
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(SheetWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof SheetWriteHandler) { |
||||
((SheetWriteHandler)writeHandler).beforeSheetCreate(writeWorkbookHolder, writeSheetHolder); |
||||
} |
||||
} |
||||
} |
||||
|
||||
private void afterSheetCreate() { |
||||
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(SheetWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof SheetWriteHandler) { |
||||
((SheetWriteHandler)writeHandler).afterSheetCreate(writeWorkbookHolder, writeSheetHolder); |
||||
} |
||||
} |
||||
if (null != writeWorkbookHolder.getWriteWorkbook().getWriteHandler()) { |
||||
writeWorkbookHolder.getWriteWorkbook().getWriteHandler().sheet(writeSheetHolder.getSheetNo(), |
||||
writeSheetHolder.getSheet()); |
||||
} |
||||
} |
||||
|
||||
private void initCurrentSheetHolder(WriteSheet writeSheet) { |
||||
writeSheetHolder = new WriteSheetHolder(writeSheet, writeWorkbookHolder); |
||||
writeWorkbookHolder.getHasBeenInitializedSheet().put(writeSheet.getSheetNo(), writeSheetHolder); |
||||
writeTableHolder = null; |
||||
currentWriteHolder = writeSheetHolder; |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("CurrentConfiguration is writeSheetHolder"); |
||||
} |
||||
} |
||||
|
||||
private void initSheet() { |
||||
Sheet currentSheet; |
||||
try { |
||||
currentSheet = writeWorkbookHolder.getWorkbook().getSheetAt(writeSheetHolder.getSheetNo()); |
||||
} catch (Exception e) { |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("Can not find sheet:{} ,now create it", writeSheetHolder.getSheetNo()); |
||||
} |
||||
currentSheet = WorkBookUtil.createSheet(writeWorkbookHolder.getWorkbook(), writeSheetHolder.getSheetName()); |
||||
} |
||||
writeSheetHolder.setSheet(currentSheet); |
||||
// Initialization head
|
||||
initHead(writeSheetHolder.excelWriteHeadProperty()); |
||||
} |
||||
|
||||
public void initHead(ExcelWriteHeadProperty excelWriteHeadProperty) { |
||||
if (!currentWriteHolder.needHead() || !currentWriteHolder.excelWriteHeadProperty().hasHead()) { |
||||
return; |
||||
} |
||||
int newRowIndex = writeSheetHolder.getNewRowIndexAndStartDoWrite(); |
||||
newRowIndex += currentWriteHolder.relativeHeadRowIndex(); |
||||
// Combined head
|
||||
addMergedRegionToCurrentSheet(excelWriteHeadProperty, newRowIndex); |
||||
for (int relativeRowIndex = 0, i = newRowIndex; i < excelWriteHeadProperty.getHeadRowNumber() + newRowIndex; |
||||
i++, relativeRowIndex++) { |
||||
beforeRowCreate(newRowIndex, relativeRowIndex); |
||||
Row row = WorkBookUtil.createRow(writeSheetHolder.getSheet(), i); |
||||
afterRowCreate(row, relativeRowIndex); |
||||
addOneRowOfHeadDataToExcel(row, excelWriteHeadProperty.getHeadMap(), relativeRowIndex); |
||||
} |
||||
} |
||||
|
||||
private void beforeRowCreate(int rowIndex, int relativeRowIndex) { |
||||
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(RowWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof RowWriteHandler) { |
||||
((RowWriteHandler)writeHandler).beforeRowCreate(writeSheetHolder, writeTableHolder, rowIndex, |
||||
relativeRowIndex, true); |
||||
} |
||||
} |
||||
} |
||||
|
||||
private void afterRowCreate(Row row, int relativeRowIndex) { |
||||
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(RowWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof RowWriteHandler) { |
||||
((RowWriteHandler)writeHandler).afterRowCreate(writeSheetHolder, writeTableHolder, row, |
||||
relativeRowIndex, true); |
||||
} |
||||
} |
||||
if (null != writeWorkbookHolder.getWriteWorkbook().getWriteHandler()) { |
||||
writeWorkbookHolder.getWriteWorkbook().getWriteHandler().row(row.getRowNum(), row); |
||||
} |
||||
} |
||||
|
||||
private void addMergedRegionToCurrentSheet(ExcelWriteHeadProperty excelWriteHeadProperty, int rowIndex) { |
||||
for (com.alibaba.excel.metadata.CellRange cellRangeModel : excelWriteHeadProperty.headCellRangeList()) { |
||||
writeSheetHolder.getSheet().addMergedRegion(new CellRangeAddress(cellRangeModel.getFirstRow() + rowIndex, |
||||
cellRangeModel.getLastRow() + rowIndex, cellRangeModel.getFirstCol(), cellRangeModel.getLastCol())); |
||||
} |
||||
} |
||||
|
||||
private void addOneRowOfHeadDataToExcel(Row row, Map<Integer, Head> headMap, int relativeRowIndex) { |
||||
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) { |
||||
Head head = entry.getValue(); |
||||
beforeCellCreate(row, head, relativeRowIndex); |
||||
Cell cell = WorkBookUtil.createCell(row, entry.getKey(), head.getHeadNameList().get(relativeRowIndex)); |
||||
afterCellCreate(head, cell, relativeRowIndex); |
||||
} |
||||
} |
||||
|
||||
private void beforeCellCreate(Row row, Head head, int relativeRowIndex) { |
||||
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(CellWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof CellWriteHandler) { |
||||
((CellWriteHandler)writeHandler).beforeCellCreate(writeSheetHolder, writeTableHolder, row, head, |
||||
relativeRowIndex, true); |
||||
} |
||||
} |
||||
} |
||||
|
||||
private void afterCellCreate(Head head, Cell cell, int relativeRowIndex) { |
||||
List<WriteHandler> handlerList = currentWriteHolder.writeHandlerMap().get(CellWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof CellWriteHandler) { |
||||
((CellWriteHandler)writeHandler).afterCellCreate(writeSheetHolder, writeTableHolder, null, cell, head, |
||||
relativeRowIndex, true); |
||||
} |
||||
} |
||||
if (null != writeWorkbookHolder.getWriteWorkbook().getWriteHandler()) { |
||||
writeWorkbookHolder.getWriteWorkbook().getWriteHandler().cell(cell.getRowIndex(), cell); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void currentTable(WriteTable writeTable) { |
||||
if (writeTable == null) { |
||||
return; |
||||
} |
||||
if (writeTable.getTableNo() == null || writeTable.getTableNo() <= 0) { |
||||
writeTable.setTableNo(0); |
||||
} |
||||
if (writeSheetHolder.getHasBeenInitializedTable().containsKey(writeTable.getTableNo())) { |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("Table:{} is already existed", writeTable.getTableNo()); |
||||
} |
||||
writeTableHolder = writeSheetHolder.getHasBeenInitializedTable().get(writeTable.getTableNo()); |
||||
writeTableHolder.setNewInitialization(Boolean.FALSE); |
||||
currentWriteHolder = writeTableHolder; |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("CurrentConfiguration is writeTableHolder"); |
||||
} |
||||
return; |
||||
} |
||||
initCurrentTableHolder(writeTable); |
||||
initHead(writeTableHolder.excelWriteHeadProperty()); |
||||
} |
||||
|
||||
private void initCurrentTableHolder(WriteTable writeTable) { |
||||
writeTableHolder = new WriteTableHolder(writeTable, writeSheetHolder, writeWorkbookHolder); |
||||
writeSheetHolder.getHasBeenInitializedTable().put(writeTable.getTableNo(), writeTableHolder); |
||||
currentWriteHolder = writeTableHolder; |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("CurrentConfiguration is writeTableHolder"); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public WriteWorkbookHolder writeWorkbookHolder() { |
||||
return writeWorkbookHolder; |
||||
} |
||||
|
||||
@Override |
||||
public WriteSheetHolder writeSheetHolder() { |
||||
return writeSheetHolder; |
||||
} |
||||
|
||||
@Override |
||||
public WriteTableHolder writeTableHolder() { |
||||
return writeTableHolder; |
||||
} |
||||
|
||||
@Override |
||||
public WriteHolder currentWriteHolder() { |
||||
return currentWriteHolder; |
||||
} |
||||
|
||||
@Override |
||||
public void finish() { |
||||
if (writeWorkbookHolder == null) { |
||||
return; |
||||
} |
||||
try { |
||||
writeWorkbookHolder.getWorkbook().write(writeWorkbookHolder.getOutputStream()); |
||||
writeWorkbookHolder.getWorkbook().close(); |
||||
} catch (Throwable e) { |
||||
throw new ExcelGenerateException("Can not close IO", e); |
||||
} |
||||
try { |
||||
if (writeWorkbookHolder.getAutoCloseStream() && writeWorkbookHolder.getOutputStream() != null) { |
||||
writeWorkbookHolder.getOutputStream().close(); |
||||
} |
||||
} catch (Throwable e) { |
||||
throw new ExcelGenerateException("Can not close IO", e); |
||||
} |
||||
try { |
||||
if (writeWorkbookHolder.getAutoCloseStream() && writeWorkbookHolder.getTemplateInputStream() != null) { |
||||
writeWorkbookHolder.getTemplateInputStream().close(); |
||||
} |
||||
} catch (Throwable e) { |
||||
throw new ExcelGenerateException("Can not close IO", e); |
||||
} |
||||
try { |
||||
if (!writeWorkbookHolder.getAutoCloseStream() && writeWorkbookHolder.getFile() != null |
||||
&& writeWorkbookHolder.getOutputStream() != null) { |
||||
writeWorkbookHolder.getOutputStream().close(); |
||||
} |
||||
} catch (Throwable e) { |
||||
throw new ExcelGenerateException("Can not close IO", e); |
||||
} |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("Finished write."); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public Sheet getCurrentSheet() { |
||||
return writeSheetHolder.getSheet(); |
||||
} |
||||
|
||||
@Override |
||||
public boolean needHead() { |
||||
return writeSheetHolder.needHead(); |
||||
} |
||||
|
||||
@Override |
||||
public OutputStream getOutputStream() { |
||||
return writeWorkbookHolder.getOutputStream(); |
||||
} |
||||
|
||||
@Override |
||||
public Workbook getWorkbook() { |
||||
return writeWorkbookHolder.getWorkbook(); |
||||
} |
||||
} |
@ -0,0 +1,36 @@
|
||||
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; |
||||
} |
||||
} |
@ -0,0 +1,61 @@
|
||||
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; |
||||
|
||||
/** |
||||
* Convert between Java objects and excel objects |
||||
* |
||||
* @author Dan Zheng |
||||
* @param <T> |
||||
*/ |
||||
public interface Converter<T> { |
||||
|
||||
/** |
||||
* Back to object types in Java |
||||
* |
||||
* @return Support for Java class
|
||||
*/ |
||||
Class supportJavaTypeKey(); |
||||
|
||||
/** |
||||
* Back to object enum in excel |
||||
* |
||||
* @return Support for {@link CellDataTypeEnum} |
||||
*/ |
||||
CellDataTypeEnum supportExcelTypeKey(); |
||||
|
||||
/** |
||||
* 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. |
||||
*/ |
||||
T convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) throws Exception; |
||||
|
||||
/** |
||||
* 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. |
||||
*/ |
||||
CellData convertToExcelData(T value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) |
||||
throws Exception; |
||||
} |
@ -0,0 +1,40 @@
|
||||
package com.alibaba.excel.converters; |
||||
|
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
|
||||
/** |
||||
* Converter unique key.Consider that you can just use class as the key. |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class ConverterKeyBuild { |
||||
|
||||
private static final Map<String, String> BOXING_MAP = new HashMap<String, String>(16); |
||||
|
||||
static { |
||||
BOXING_MAP.put(int.class.getName(), Integer.class.getName()); |
||||
BOXING_MAP.put(byte.class.getName(), Byte.class.getName()); |
||||
BOXING_MAP.put(long.class.getName(), Long.class.getName()); |
||||
BOXING_MAP.put(double.class.getName(), Double.class.getName()); |
||||
BOXING_MAP.put(float.class.getName(), Float.class.getName()); |
||||
BOXING_MAP.put(char.class.getName(), Character.class.getName()); |
||||
BOXING_MAP.put(short.class.getName(), Short.class.getName()); |
||||
BOXING_MAP.put(boolean.class.getName(), Boolean.class.getName()); |
||||
} |
||||
|
||||
public static String buildKey(Class clazz) { |
||||
String className = clazz.getName(); |
||||
String boxingClassName = BOXING_MAP.get(clazz.getName()); |
||||
if (boxingClassName == null) { |
||||
return className; |
||||
} |
||||
return boxingClassName; |
||||
} |
||||
|
||||
public static String buildKey(Class clazz, CellDataTypeEnum cellDataTypeEnum) { |
||||
return buildKey(clazz) + "-" + cellDataTypeEnum.toString(); |
||||
} |
||||
} |
@ -0,0 +1,146 @@
|
||||
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.booleanconverter.BooleanBooleanConverter; |
||||
import com.alibaba.excel.converters.booleanconverter.BooleanNumberConverter; |
||||
import com.alibaba.excel.converters.booleanconverter.BooleanStringConverter; |
||||
import com.alibaba.excel.converters.bytearray.BoxingByteArrayImageConverter; |
||||
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.DateNumberConverter; |
||||
import com.alibaba.excel.converters.date.DateStringConverter; |
||||
import com.alibaba.excel.converters.doubleconverter.DoubleBooleanConverter; |
||||
import com.alibaba.excel.converters.doubleconverter.DoubleNumberConverter; |
||||
import com.alibaba.excel.converters.doubleconverter.DoubleStringConverter; |
||||
import com.alibaba.excel.converters.file.FileImageConverter; |
||||
import com.alibaba.excel.converters.floatconverter.FloatBooleanConverter; |
||||
import com.alibaba.excel.converters.floatconverter.FloatNumberConverter; |
||||
import com.alibaba.excel.converters.floatconverter.FloatStringConverter; |
||||
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.longconverter.LongBooleanConverter; |
||||
import com.alibaba.excel.converters.longconverter.LongNumberConverter; |
||||
import com.alibaba.excel.converters.longconverter.LongStringConverter; |
||||
import com.alibaba.excel.converters.shortconverter.ShortBooleanConverter; |
||||
import com.alibaba.excel.converters.shortconverter.ShortNumberConverter; |
||||
import com.alibaba.excel.converters.shortconverter.ShortStringConverter; |
||||
import com.alibaba.excel.converters.string.StringBooleanConverter; |
||||
import com.alibaba.excel.converters.string.StringErrorConverter; |
||||
import com.alibaba.excel.converters.string.StringNumberConverter; |
||||
import com.alibaba.excel.converters.string.StringStringConverter; |
||||
|
||||
/** |
||||
* Load default handler |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class DefaultConverterLoader { |
||||
private static Map<String, Converter> defaultWriteConverter; |
||||
private static Map<String, Converter> allConverter; |
||||
|
||||
/** |
||||
* Load default write converter |
||||
* |
||||
* @return |
||||
*/ |
||||
public static Map<String, Converter> loadDefaultWriteConverter() { |
||||
if (defaultWriteConverter != null) { |
||||
return defaultWriteConverter; |
||||
} |
||||
defaultWriteConverter = new HashMap<String, Converter>(32); |
||||
putWriteConverter(new BigDecimalNumberConverter()); |
||||
putWriteConverter(new BooleanBooleanConverter()); |
||||
putWriteConverter(new ByteNumberConverter()); |
||||
putWriteConverter(new DateStringConverter()); |
||||
putWriteConverter(new DoubleNumberConverter()); |
||||
putWriteConverter(new FloatNumberConverter()); |
||||
putWriteConverter(new IntegerNumberConverter()); |
||||
putWriteConverter(new LongNumberConverter()); |
||||
putWriteConverter(new ShortNumberConverter()); |
||||
putWriteConverter(new StringStringConverter()); |
||||
putWriteConverter(new FileImageConverter()); |
||||
putWriteConverter(new InputStreamImageConverter()); |
||||
putWriteConverter(new ByteArrayImageConverter()); |
||||
putWriteConverter(new BoxingByteArrayImageConverter()); |
||||
return defaultWriteConverter; |
||||
} |
||||
|
||||
private static void putWriteConverter(Converter converter) { |
||||
defaultWriteConverter.put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey()), converter); |
||||
} |
||||
|
||||
/** |
||||
* Load default read converter |
||||
* |
||||
* @return |
||||
*/ |
||||
public static Map<String, Converter> loadDefaultReadConverter() { |
||||
return loadAllConverter(); |
||||
} |
||||
|
||||
/** |
||||
* Load all converter |
||||
* |
||||
* @return |
||||
*/ |
||||
public static Map<String, Converter> loadAllConverter() { |
||||
if (allConverter != null) { |
||||
return allConverter; |
||||
} |
||||
allConverter = new HashMap<String, Converter>(64); |
||||
putAllConverter(new BigDecimalBooleanConverter()); |
||||
putAllConverter(new BigDecimalNumberConverter()); |
||||
putAllConverter(new BigDecimalStringConverter()); |
||||
|
||||
putAllConverter(new BooleanBooleanConverter()); |
||||
putAllConverter(new BooleanNumberConverter()); |
||||
putAllConverter(new BooleanStringConverter()); |
||||
|
||||
putAllConverter(new ByteBooleanConverter()); |
||||
putAllConverter(new ByteNumberConverter()); |
||||
putAllConverter(new ByteStringConverter()); |
||||
|
||||
putAllConverter(new DateNumberConverter()); |
||||
putAllConverter(new DateStringConverter()); |
||||
|
||||
putAllConverter(new DoubleBooleanConverter()); |
||||
putAllConverter(new DoubleNumberConverter()); |
||||
putAllConverter(new DoubleStringConverter()); |
||||
|
||||
putAllConverter(new FloatBooleanConverter()); |
||||
putAllConverter(new FloatNumberConverter()); |
||||
putAllConverter(new FloatStringConverter()); |
||||
|
||||
putAllConverter(new IntegerBooleanConverter()); |
||||
putAllConverter(new IntegerNumberConverter()); |
||||
putAllConverter(new IntegerStringConverter()); |
||||
|
||||
putAllConverter(new LongBooleanConverter()); |
||||
putAllConverter(new LongNumberConverter()); |
||||
putAllConverter(new LongStringConverter()); |
||||
|
||||
putAllConverter(new ShortBooleanConverter()); |
||||
putAllConverter(new ShortNumberConverter()); |
||||
putAllConverter(new ShortStringConverter()); |
||||
|
||||
putAllConverter(new StringBooleanConverter()); |
||||
putAllConverter(new StringNumberConverter()); |
||||
putAllConverter(new StringStringConverter()); |
||||
putAllConverter(new StringErrorConverter()); |
||||
return allConverter; |
||||
} |
||||
|
||||
private static void putAllConverter(Converter converter) { |
||||
allConverter.put(ConverterKeyBuild.buildKey(converter.supportJavaTypeKey(), converter.supportExcelTypeKey()), |
||||
converter); |
||||
} |
||||
} |
@ -0,0 +1,46 @@
|
||||
package com.alibaba.excel.converters.bigdecimal; |
||||
|
||||
import java.math.BigDecimal; |
||||
|
||||
import com.alibaba.excel.converters.Converter; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
import com.alibaba.excel.metadata.GlobalConfiguration; |
||||
import com.alibaba.excel.metadata.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* BigDecimal and boolean converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class BigDecimalBooleanConverter implements Converter<BigDecimal> { |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return BigDecimal.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.BOOLEAN; |
||||
} |
||||
|
||||
@Override |
||||
public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (cellData.getBooleanValue()) { |
||||
return BigDecimal.ONE; |
||||
} |
||||
return BigDecimal.ZERO; |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (BigDecimal.ONE.equals(value)) { |
||||
return new CellData(Boolean.TRUE); |
||||
} |
||||
return new CellData(Boolean.FALSE); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,39 @@
|
||||
package com.alibaba.excel.converters.bigdecimal; |
||||
|
||||
import java.math.BigDecimal; |
||||
|
||||
import com.alibaba.excel.converters.Converter; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
import com.alibaba.excel.metadata.GlobalConfiguration; |
||||
import com.alibaba.excel.metadata.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* BigDecimal and number converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class BigDecimalNumberConverter implements Converter<BigDecimal> { |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return BigDecimal.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.NUMBER; |
||||
} |
||||
|
||||
@Override |
||||
public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return BigDecimal.valueOf(cellData.getDoubleValue()); |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return new CellData(value.doubleValue()); |
||||
} |
||||
} |
@ -0,0 +1,41 @@
|
||||
package com.alibaba.excel.converters.bigdecimal; |
||||
|
||||
import java.math.BigDecimal; |
||||
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.property.ExcelContentProperty; |
||||
import com.alibaba.excel.util.NumberUtils; |
||||
|
||||
/** |
||||
* BigDecimal and string converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class BigDecimalStringConverter implements Converter<BigDecimal> { |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return BigDecimal.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.STRING; |
||||
} |
||||
|
||||
@Override |
||||
public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) throws ParseException { |
||||
return NumberUtils.parseBigDecimal(cellData.getStringValue(), contentProperty); |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return NumberUtils.formatToCellData(value, contentProperty); |
||||
} |
||||
} |
@ -0,0 +1,38 @@
|
||||
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.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* Boolean and boolean converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class BooleanBooleanConverter implements Converter<Boolean> { |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Boolean.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.BOOLEAN; |
||||
} |
||||
|
||||
@Override |
||||
public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return cellData.getBooleanValue(); |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return new CellData(value); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,47 @@
|
||||
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.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* Boolean and number converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class BooleanNumberConverter implements Converter<Boolean> { |
||||
|
||||
private static final Double ONE = 1.0; |
||||
private static final Double ZERO = 0.0; |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Boolean.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.NUMBER; |
||||
} |
||||
|
||||
@Override |
||||
public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (ONE.equals(cellData.getDoubleValue())) { |
||||
return Boolean.TRUE; |
||||
} |
||||
return Boolean.FALSE; |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (value) { |
||||
return new CellData(ONE); |
||||
} |
||||
return new CellData(ZERO); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,38 @@
|
||||
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.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* Boolean and string converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class BooleanStringConverter implements Converter<Boolean> { |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Boolean.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.STRING; |
||||
} |
||||
|
||||
@Override |
||||
public Boolean convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return Boolean.valueOf(cellData.getStringValue()); |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Boolean value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return new CellData(value.toString()); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,41 @@
|
||||
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.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* Boxing Byte array and image converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class BoxingByteArrayImageConverter 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"); |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Byte[] value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
byte[] byteValue = new byte[value.length]; |
||||
for (int i = 0; i < value.length; i++) { |
||||
byteValue[i] = value[i]; |
||||
} |
||||
return new CellData(byteValue); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,37 @@
|
||||
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.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* Byte array and image converter |
||||
* |
||||
* @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"); |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(byte[] value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return new CellData(value); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,46 @@
|
||||
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.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* Byte and boolean converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class ByteBooleanConverter implements Converter<Byte> { |
||||
private static final Byte ONE = (byte)1; |
||||
private static final Byte ZERO = (byte)0; |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Byte.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.BOOLEAN; |
||||
} |
||||
|
||||
@Override |
||||
public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (cellData.getBooleanValue()) { |
||||
return ONE; |
||||
} |
||||
return ZERO; |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (ONE.equals(value)) { |
||||
return new CellData(Boolean.TRUE); |
||||
} |
||||
return new CellData(Boolean.FALSE); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,38 @@
|
||||
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.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* Byte and number converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class ByteNumberConverter implements Converter<Byte> { |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Byte.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.NUMBER; |
||||
} |
||||
|
||||
@Override |
||||
public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return cellData.getDoubleValue().byteValue(); |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return new CellData(value.doubleValue()); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,41 @@
|
||||
package com.alibaba.excel.converters.byteconverter; |
||||
|
||||
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.property.ExcelContentProperty; |
||||
import com.alibaba.excel.util.NumberUtils; |
||||
|
||||
/** |
||||
* Byte and string converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class ByteStringConverter implements Converter<Byte> { |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Byte.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.STRING; |
||||
} |
||||
|
||||
@Override |
||||
public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) throws ParseException { |
||||
return NumberUtils.parseByte(cellData.getStringValue(), contentProperty); |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Byte value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return NumberUtils.formatToCellData(value, contentProperty); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,46 @@
|
||||
package com.alibaba.excel.converters.date; |
||||
|
||||
import java.util.Date; |
||||
|
||||
import org.apache.poi.hssf.usermodel.HSSFDateUtil; |
||||
|
||||
import com.alibaba.excel.converters.Converter; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
import com.alibaba.excel.metadata.GlobalConfiguration; |
||||
import com.alibaba.excel.metadata.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* Date and number converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class DateNumberConverter implements Converter<Date> { |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Date.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.NUMBER; |
||||
} |
||||
|
||||
@Override |
||||
public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { |
||||
return HSSFDateUtil.getJavaDate(cellData.getDoubleValue(), globalConfiguration.getUse1904windowing(), null); |
||||
} else { |
||||
return HSSFDateUtil.getJavaDate(cellData.getDoubleValue(), |
||||
contentProperty.getDateTimeFormatProperty().getUse1904windowing(), null); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return new CellData((double)(value.getTime())); |
||||
} |
||||
} |
@ -0,0 +1,49 @@
|
||||
package com.alibaba.excel.converters.date; |
||||
|
||||
import java.text.ParseException; |
||||
import java.util.Date; |
||||
|
||||
import com.alibaba.excel.converters.Converter; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
import com.alibaba.excel.metadata.GlobalConfiguration; |
||||
import com.alibaba.excel.metadata.property.ExcelContentProperty; |
||||
import com.alibaba.excel.util.DateUtils; |
||||
|
||||
/** |
||||
* Date and string converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class DateStringConverter implements Converter<Date> { |
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Date.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.STRING; |
||||
} |
||||
|
||||
@Override |
||||
public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) throws ParseException { |
||||
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { |
||||
return DateUtils.parseDate(cellData.getStringValue(), null); |
||||
} else { |
||||
return DateUtils.parseDate(cellData.getStringValue(), |
||||
contentProperty.getDateTimeFormatProperty().getFormat()); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Date value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { |
||||
return new CellData(DateUtils.format(value, null)); |
||||
} else { |
||||
return new CellData(DateUtils.format(value, contentProperty.getDateTimeFormatProperty().getFormat())); |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,46 @@
|
||||
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.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* Double and boolean converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class DoubleBooleanConverter implements Converter<Double> { |
||||
private static final Double ONE = 1.0; |
||||
private static final Double ZERO = 0.0; |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Double.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.BOOLEAN; |
||||
} |
||||
|
||||
@Override |
||||
public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (cellData.getBooleanValue()) { |
||||
return ONE; |
||||
} |
||||
return ZERO; |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (ONE.equals(value)) { |
||||
return new CellData(Boolean.TRUE); |
||||
} |
||||
return new CellData(Boolean.FALSE); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,38 @@
|
||||
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.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* Double and number converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class DoubleNumberConverter implements Converter<Double> { |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Double.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.NUMBER; |
||||
} |
||||
|
||||
@Override |
||||
public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return cellData.getDoubleValue(); |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return new CellData(value); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,40 @@
|
||||
package com.alibaba.excel.converters.doubleconverter; |
||||
|
||||
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.property.ExcelContentProperty; |
||||
import com.alibaba.excel.util.NumberUtils; |
||||
|
||||
/** |
||||
* Double and string converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class DoubleStringConverter implements Converter<Double> { |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Double.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.STRING; |
||||
} |
||||
|
||||
@Override |
||||
public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) throws ParseException { |
||||
return NumberUtils.parseDouble(cellData.getStringValue(), contentProperty); |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Double value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return NumberUtils.formatToCellData(value, contentProperty); |
||||
} |
||||
} |
@ -0,0 +1,41 @@
|
||||
package com.alibaba.excel.converters.file; |
||||
|
||||
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.property.ExcelContentProperty; |
||||
import com.alibaba.excel.util.FileUtils; |
||||
|
||||
/** |
||||
* File and image converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class FileImageConverter implements Converter<File> { |
||||
@Override |
||||
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, |
||||
GlobalConfiguration globalConfiguration) throws IOException { |
||||
return new CellData(FileUtils.readFileToByteArray(value)); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,46 @@
|
||||
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.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* Float and boolean converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class FloatBooleanConverter implements Converter<Float> { |
||||
private static final Float ONE = (float)1.0; |
||||
private static final Float ZERO = (float)0.0; |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Float.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.BOOLEAN; |
||||
} |
||||
|
||||
@Override |
||||
public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (cellData.getBooleanValue()) { |
||||
return ONE; |
||||
} |
||||
return ZERO; |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (ONE.equals(value)) { |
||||
return new CellData(Boolean.TRUE); |
||||
} |
||||
return new CellData(Boolean.FALSE); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,38 @@
|
||||
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.property.ExcelContentProperty; |
||||
|
||||
/** |
||||
* Float and number converter |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class FloatNumberConverter implements Converter<Float> { |
||||
|
||||
@Override |
||||
public Class supportJavaTypeKey() { |
||||
return Float.class; |
||||
} |
||||
|
||||
@Override |
||||
public CellDataTypeEnum supportExcelTypeKey() { |
||||
return CellDataTypeEnum.NUMBER; |
||||
} |
||||
|
||||
@Override |
||||
public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return cellData.getDoubleValue().floatValue(); |
||||
} |
||||
|
||||
@Override |
||||
public CellData convertToExcelData(Float value, ExcelContentProperty contentProperty, |
||||
GlobalConfiguration globalConfiguration) { |
||||
return new CellData(value.doubleValue()); |
||||
} |
||||
|
||||
} |