Browse Source

阿里內部最新版本开源,为了稳定性07版本解析修改为底层使用POI解析。

developing
jipengfei.jpf 6 years ago
parent
commit
fb5ef154d4
  1. 15
      pom.xml
  2. 73
      src/main/java/com/alibaba/excel/ExcelReader.java
  3. 112
      src/main/java/com/alibaba/excel/ExcelWriter.java
  4. 36
      src/main/java/com/alibaba/excel/analysis/BaseSaxAnalyser.java
  5. 30
      src/main/java/com/alibaba/excel/analysis/ExcelAnalyser.java
  6. 38
      src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java
  7. 53
      src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java
  8. 40
      src/main/java/com/alibaba/excel/analysis/v07/XlsxRowHandler.java
  9. 144
      src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java
  10. 14
      src/main/java/com/alibaba/excel/annotation/ExcelColumnNum.java
  11. 16
      src/main/java/com/alibaba/excel/annotation/ExcelProperty.java
  12. 2
      src/main/java/com/alibaba/excel/annotation/FieldType.java
  13. 4
      src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java
  14. 57
      src/main/java/com/alibaba/excel/context/AnalysisContext.java
  15. 15
      src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java
  16. 29
      src/main/java/com/alibaba/excel/context/GenerateContext.java
  17. 56
      src/main/java/com/alibaba/excel/context/GenerateContextImpl.java
  18. 26
      src/main/java/com/alibaba/excel/event/AnalysisEventListener.java
  19. 12
      src/main/java/com/alibaba/excel/event/AnalysisEventRegisterCenter.java
  20. 3
      src/main/java/com/alibaba/excel/event/OneRowAnalysisFinishEvent.java
  21. 3
      src/main/java/com/alibaba/excel/exception/ExcelAnalysisException.java
  22. 4
      src/main/java/com/alibaba/excel/exception/ExcelGenerateException.java
  23. 25
      src/main/java/com/alibaba/excel/metadata/BaseRowModel.java
  24. 1
      src/main/java/com/alibaba/excel/metadata/CellRange.java
  25. 5
      src/main/java/com/alibaba/excel/metadata/ExcelColumnProperty.java
  26. 38
      src/main/java/com/alibaba/excel/metadata/ExcelHeadProperty.java
  27. 5
      src/main/java/com/alibaba/excel/metadata/Font.java
  28. 51
      src/main/java/com/alibaba/excel/metadata/Sheet.java
  29. 5
      src/main/java/com/alibaba/excel/metadata/Table.java
  30. 1
      src/main/java/com/alibaba/excel/metadata/TableStyle.java
  31. 16
      src/main/java/com/alibaba/excel/modelbuild/ModelBuildEventListener.java
  32. 58
      src/main/java/com/alibaba/excel/parameter/AnalysisParam.java
  33. 45
      src/main/java/com/alibaba/excel/parameter/ExcelWriteParam.java
  34. 58
      src/main/java/com/alibaba/excel/parameter/GenerateParam.java
  35. 54
      src/main/java/com/alibaba/excel/read/ExcelAnalyser.java
  36. 331
      src/main/java/com/alibaba/excel/read/SaxAnalyserV07.java
  37. 30
      src/main/java/com/alibaba/excel/read/event/AnalysisEventListener.java
  38. 48
      src/main/java/com/alibaba/excel/read/v07/XMLTempFile.java
  39. 42
      src/main/java/com/alibaba/excel/read/v07/XmlParserFactory.java
  40. 1
      src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java
  41. 62
      src/main/java/com/alibaba/excel/util/EasyExcelTempFile.java
  42. 122
      src/main/java/com/alibaba/excel/util/FileUtil.java
  43. 145
      src/main/java/com/alibaba/excel/util/IndexValueConverter.java
  44. 41
      src/main/java/com/alibaba/excel/util/POITempFile.java
  45. 1
      src/main/java/com/alibaba/excel/util/PositionUtils.java
  46. 77
      src/main/java/com/alibaba/excel/util/TypeUtil.java
  47. 45
      src/main/java/com/alibaba/excel/write/ExcelBuilder.java
  48. 89
      src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java
  49. 16
      src/test/java/function/listener/ExcelListener.java
  50. 9
      src/test/java/function/read/ExelAllDataTypeTest.java
  51. 9
      src/test/java/function/read/NumTest3.java
  52. 13
      src/test/java/function/read/ReadSheets.java
  53. 9
      src/test/java/function/read/XLSX2007FunctionTest.java
  54. 15
      src/test/java/function/write/ExcelWriteTest1.java
  55. 48
      src/test/java/javamodel/IdentificationExcel.java
  56. 9
      src/test/java/read/v03/XLS2003FunctionTest.java
  57. 11
      src/test/java/read/v07/Read2007MeanWhileWrite.java
  58. 56
      src/test/java/read/v07/Read2007Xlsx.java
  59. 10
      src/test/java/read/v07/listener/Excel2007NoJavaModelAnalysisListener.java
  60. 11
      src/test/java/read/v07/listener/Excel2007WithJavaModelAnalysisListener.java
  61. BIN
      src/test/resources/1.xlsx

15
pom.xml

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId> <artifactId>easyexcel</artifactId>
<version>1.0.4-SNAPSHOT</version> <version>1.0.4</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>easyexcel</name> <name>easyexcel</name>
<description>easyexcel is a excel handle tools written in Java</description> <description>easyexcel is a excel handle tools written in Java</description>
@ -118,18 +118,7 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<!--<plugin>-->
<!--<groupId>org.sonatype.plugins</groupId>-->
<!--<artifactId>nexus-staging-maven-plugin</artifactId>-->
<!--<version>1.6.7</version>-->
<!--<extensions>true</extensions>-->
<!--<configuration>-->
<!--<serverId>ossrh</serverId>-->
<!--<nexusUrl>https://oss.sonatype.org/</nexusUrl>-->
<!--<autoReleaseAfterClose>true</autoReleaseAfterClose>-->
<!--</configuration>-->
<!--</plugin>-->
<!-- GPG -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId> <artifactId>maven-gpg-plugin</artifactId>

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

@ -1,33 +1,35 @@
package com.alibaba.excel; package com.alibaba.excel;
import java.io.InputStream; import com.alibaba.excel.analysis.ExcelAnalyser;
import java.util.List; import com.alibaba.excel.analysis.ExcelAnalyserImpl;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.ExcelAnalyser; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.ExcelAnalyserImpl; import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.parameter.AnalysisParam;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.InputStream;
import java.util.List;
/** /**
* Excel解析thread unsafe * Excel thread unsafe
* *
* @author jipengfei * @author jipengfei
*/ */
public class ExcelReader { public class ExcelReader {
/** /**
* 解析器 * analyser
*/ */
private ExcelAnalyser analyser = new ExcelAnalyserImpl(); private ExcelAnalyser analyser = new ExcelAnalyserImpl();
/** /**
* @param in 文件输入流 * @param in
* @param excelTypeEnum excel类型0307 * @param excelTypeEnum 0307
* @param customContent 自定义模型可以在{@link AnalysisEventListener#invoke(Object, AnalysisContext) * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext)
* }AnalysisContext中获取用于监听者回调使用 * }AnalysisContext
* @param eventListener 用户监听 * @param eventListener
*/ */
public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent, public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent,
AnalysisEventListener eventListener) { AnalysisEventListener eventListener) {
@ -35,12 +37,22 @@ public class ExcelReader {
} }
/** /**
* @param in 文件输入流 * old 1.1.0
* @param excelTypeEnum excel类型0307 * @param param
* @param customContent 自定义模型可以在{@link AnalysisEventListener#invoke(Object, AnalysisContext) * @param eventListener
* }AnalysisContext中获取用于监听者回调使用 */
* @param eventListener 用户监听 @Deprecated
* @param trim 是否对解析的String做trim()默认true,用于防止 excel中空格引起的装换报错 public ExcelReader(AnalysisParam param, AnalysisEventListener eventListener) {
this(param.getIn(), param.getExcelTypeEnum(), param.getCustomContent(), eventListener, true);
}
/**
* @param in
* @param excelTypeEnum 03 07
* @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext)
* }AnalysisContext
* @param eventListener
* @param trim
*/ */
public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent, public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent,
AnalysisEventListener eventListener, boolean trim) { AnalysisEventListener eventListener, boolean trim) {
@ -49,39 +61,34 @@ public class ExcelReader {
} }
/** /**
* 读一个sheet且没有模型映射
*/ */
public void read() { public void read() {
analyser.analysis(); analyser.analysis();
} }
/** /**
* 读指定个sheet没有模型映射
* *
* @param sheet 需要解析的sheet * @param sheet
*/ */
public void read(Sheet sheet) { public void read(Sheet sheet) {
analyser.analysis(sheet); analyser.analysis(sheet);
} }
@Deprecated
public void read(Sheet sheet,Class<? extends BaseRowModel> clazz){
sheet.setClazz(clazz);
analyser.analysis(sheet);
}
/** /**
* 读取excel中包含哪些sheet
* *
* @return Sheets * @return
*/ */
public List<Sheet> getSheets() { public List<Sheet> getSheets() {
return analyser.getSheets(); return analyser.getSheets();
} }
/** /**
* 关闭流删除临时目录文件
*/
public void finish(){
analyser.stop();
}
/**
* 校验入参
* *
* @param in * @param in
* @param excelTypeEnum * @param excelTypeEnum

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

@ -1,17 +1,18 @@
package com.alibaba.excel; package com.alibaba.excel;
import java.io.OutputStream;
import java.util.List;
import com.alibaba.excel.metadata.BaseRowModel; import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table; import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.parameter.GenerateParam;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.ExcelBuilder; import com.alibaba.excel.write.ExcelBuilder;
import com.alibaba.excel.write.ExcelBuilderImpl; import com.alibaba.excel.write.ExcelBuilderImpl;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/** /**
* 生成excelthread unsafe
* *
* @author jipengfei * @author jipengfei
*/ */
@ -19,80 +20,119 @@ public class ExcelWriter {
private ExcelBuilder excelBuilder; private ExcelBuilder excelBuilder;
/** /**
* 生成EXCEL
* *
* @param outputStream 文件输出流 *
* @param typeEnum 输出文件类型03或07强烈建议使用07版可以输出超大excel而不内存溢出
*/ */
public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum) { public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum) {
this(outputStream, typeEnum, true); this(outputStream, typeEnum, true);
} }
private Class<? extends BaseRowModel> objectClass;
private String sheetName;
public ExcelWriter(GenerateParam generateParam) {
this(generateParam.getOutputStream(), generateParam.getType(), true);
this.objectClass = generateParam.getClazz();
this.sheetName = generateParam.getSheetName();
}
/** /**
* 生成EXCEL
* *
* @param outputStream 文件输出流 *
* @param typeEnum 输出文件类型03或07强烈建议使用07版可以输出超大excel而不内存溢出 * @param outputStream
* @param needHead 是否需要表头 * @param typeEnum
*/ */
public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) {
excelBuilder = new ExcelBuilderImpl(); excelBuilder = new ExcelBuilderImpl();
excelBuilder.init(outputStream, typeEnum, needHead); excelBuilder.init(null, outputStream, typeEnum, needHead);
} }
/** /**
* 生成多sheet,每个sheet一张表
* *
* @param data 一行数据是一个BaseRowModel子类的模型 * @param templateInputStream
* @param sheet data写入某个sheet * @param outputStream
* @return this当前引用 * @param typeEnum
*/
public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) {
excelBuilder = new ExcelBuilderImpl();
excelBuilder.init(templateInputStream,outputStream, typeEnum, needHead);
}
/**
*
* @param data
* @param sheet
* @return this
*/ */
public ExcelWriter write(List<? extends BaseRowModel> data, Sheet sheet) { public ExcelWriter write(List<? extends BaseRowModel> data, Sheet sheet) {
excelBuilder.addContent(data, sheet); excelBuilder.addContent(data, sheet);
return this; return this;
} }
//public Sheet(int sheetNo, int headLineMun, Class<? extends BaseRowModel> clazz, String sheetName,
// List<List<String>> head) {
// this.sheetNo = sheetNo;
// this.clazz = clazz;
// this.headLineMun = headLineMun;
// this.sheetName = sheetName;
// this.head = head;
//}
@Deprecated
public ExcelWriter write(List data) {
if (objectClass != null) {
return this.write(data,new Sheet(1,0,objectClass));
}else {
return this.write0(data,new Sheet(1,0,objectClass));
}
}
/** /**
* 生成多sheet,每个sheet一张表
* *
* @param data List代表一行数据 *
* @param sheet data写入某个sheet * @param data
* @return this当前引用 * @param sheet
* @return this
*/ */
public ExcelWriter write0(List<List<String>> data, Sheet sheet) { public ExcelWriter write1(List<List<Object>> data, Sheet sheet) {
excelBuilder.addContent(data, sheet); excelBuilder.addContent(data, sheet);
return this; return this;
} }
/** /**
* 可生成多sheet,每个sheet多张表
* *
* @param data type 一个java模型一行数据 * @param data
* @param sheet data写入某个sheet * @param sheet
* @param table data写入某个table * @return this
* @return this当前引用
*/ */
public ExcelWriter write0(List<List<String>> data, Sheet sheet) {
excelBuilder.addContent(data, sheet);
return this;
}
public ExcelWriter write(List<? extends BaseRowModel> data, Sheet sheet, Table table) { public ExcelWriter write(List<? extends BaseRowModel> data, Sheet sheet, Table table) {
excelBuilder.addContent(data, sheet, table); excelBuilder.addContent(data, sheet, table);
return this; return this;
} }
/**
* 可生成多sheet,每个sheet多张表
*
* @param data List 代表一行数据
* @param sheet data写入某个sheet
* @param table data写入某个table
* @return this当前引用
*/
public ExcelWriter write0(List<List<String>> data, Sheet sheet, Table table) { public ExcelWriter write0(List<List<String>> data, Sheet sheet, Table table) {
excelBuilder.addContent(data, sheet, table); excelBuilder.addContent(data, sheet, table);
return this; return this;
} }
public ExcelWriter write1(List<List<Object>> data, Sheet sheet, Table table) {
excelBuilder.addContent(data, sheet, table);
return this;
}
public void finish() { public void finish() {
excelBuilder.finish(); excelBuilder.finish();
} }

36
src/main/java/com/alibaba/excel/read/BaseSaxAnalyser.java → src/main/java/com/alibaba/excel/analysis/BaseSaxAnalyser.java

@ -1,19 +1,20 @@
package com.alibaba.excel.read; 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.support.ExcelTypeEnum;
import com.alibaba.excel.util.TypeUtil;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventListener;
import com.alibaba.excel.read.event.AnalysisEventRegisterCenter;
import com.alibaba.excel.read.event.OneRowAnalysisFinishEvent;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
/** /**
* 抽象sax模式 excel 解析类
* *
* @author jipengfei * @author jipengfei
*/ */
@ -24,7 +25,6 @@ public abstract class BaseSaxAnalyser implements AnalysisEventRegisterCenter, Ex
private LinkedHashMap<String, AnalysisEventListener> listeners = new LinkedHashMap<String, AnalysisEventListener>(); private LinkedHashMap<String, AnalysisEventListener> listeners = new LinkedHashMap<String, AnalysisEventListener>();
/** /**
* 开始执行解析
*/ */
protected abstract void execute(); protected abstract void execute();
@ -47,7 +47,6 @@ public abstract class BaseSaxAnalyser implements AnalysisEventRegisterCenter, Ex
} }
/** /**
* 清空所有监听者
*/ */
public void cleanAllListeners() { public void cleanAllListeners() {
listeners = new LinkedHashMap<String, AnalysisEventListener>(); listeners = new LinkedHashMap<String, AnalysisEventListener>();
@ -56,7 +55,6 @@ public abstract class BaseSaxAnalyser implements AnalysisEventRegisterCenter, Ex
public void notifyListeners(OneRowAnalysisFinishEvent event) { public void notifyListeners(OneRowAnalysisFinishEvent event) {
analysisContext.setCurrentRowAnalysisResult(event.getData()); analysisContext.setCurrentRowAnalysisResult(event.getData());
//表头数据
if (analysisContext.getCurrentRowNum() < analysisContext.getCurrentSheet().getHeadLineMun()) { if (analysisContext.getCurrentRowNum() < analysisContext.getCurrentSheet().getHeadLineMun()) {
if (analysisContext.getCurrentRowNum() <= analysisContext.getCurrentSheet().getHeadLineMun() - 1) { if (analysisContext.getCurrentRowNum() <= analysisContext.getCurrentSheet().getHeadLineMun() - 1) {
analysisContext.buildExcelHeadProperty(null, analysisContext.buildExcelHeadProperty(null,
@ -64,9 +62,23 @@ public abstract class BaseSaxAnalyser implements AnalysisEventRegisterCenter, Ex
} }
} else { } else {
analysisContext.setCurrentRowAnalysisResult(event.getData()); analysisContext.setCurrentRowAnalysisResult(event.getData());
if (listeners.size() == 1) {
analysisContext.setCurrentRowAnalysisResult(converter((List<String>)event.getData()));
}
for (Map.Entry<String, AnalysisEventListener> entry : listeners.entrySet()) { for (Map.Entry<String, AnalysisEventListener> entry : listeners.entrySet()) {
entry.getValue().invoke(analysisContext.getCurrentRowAnalysisResult(), analysisContext); 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;
}
} }

30
src/main/java/com/alibaba/excel/analysis/ExcelAnalyser.java

@ -0,0 +1,30 @@
package com.alibaba.excel.analysis;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.InputStream;
import java.util.List;
/**
*
* @author jipengfei
*/
public interface ExcelAnalyser {
void init(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Object custom, AnalysisEventListener eventListener,
boolean trim);
void analysis(Sheet sheetParam);
void analysis();
List<Sheet> getSheets();
}

38
src/main/java/com/alibaba/excel/read/ExcelAnalyserImpl.java → src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java

@ -1,15 +1,18 @@
package com.alibaba.excel.read; package com.alibaba.excel.analysis;
import java.io.InputStream; import com.alibaba.excel.analysis.v03.XlsSaxAnalyser;
import java.util.List; import com.alibaba.excel.analysis.v07.XlsxSaxAnalyser;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContextImpl;
import com.alibaba.excel.read.context.AnalysisContextImpl; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.event.AnalysisEventListener; import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.modelbuild.ModelBuildEventListener; import com.alibaba.excel.modelbuild.ModelBuildEventListener;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.InputStream;
import java.util.List;
/** /**
* @author jipengfei * @author jipengfei
*/ */
@ -21,14 +24,15 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
private BaseSaxAnalyser getSaxAnalyser() { private BaseSaxAnalyser getSaxAnalyser() {
if (saxAnalyser == null) { if (saxAnalyser == null) {
try {
if (ExcelTypeEnum.XLS.equals(analysisContext.getExcelType())) { if (ExcelTypeEnum.XLS.equals(analysisContext.getExcelType())) {
this.saxAnalyser = new SaxAnalyserV03(analysisContext); this.saxAnalyser = new XlsSaxAnalyser(analysisContext);
} else { } else {
try { this.saxAnalyser = new XlsxSaxAnalyser(analysisContext);
this.saxAnalyser = new SaxAnalyserV07(analysisContext);
} catch (Exception e) {
e.printStackTrace();
} }
} catch (Exception e) {
throw new ExcelAnalysisException("Analyse excel occur file error fileType " + analysisContext.getExcelType(),
e);
} }
} }
return this.saxAnalyser; return this.saxAnalyser;
@ -59,10 +63,6 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
return saxAnalyser.getSheets(); return saxAnalyser.getSheets();
} }
public void stop() {
saxAnalyser.stop();
}
private void appendListeners(BaseSaxAnalyser saxAnalyser) { private void appendListeners(BaseSaxAnalyser saxAnalyser) {
if (analysisContext.getCurrentSheet() != null && analysisContext.getCurrentSheet().getClazz() != null) { if (analysisContext.getCurrentSheet() != null && analysisContext.getCurrentSheet().getClazz() != null) {
saxAnalyser.appendLister("model_build_listener", new ModelBuildEventListener()); saxAnalyser.appendLister("model_build_listener", new ModelBuildEventListener());
@ -72,8 +72,4 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
} }
} }
protected void finalize() throws Throwable {
stop();
}
} }

53
src/main/java/com/alibaba/excel/read/SaxAnalyserV03.java → src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java

@ -1,60 +1,39 @@
package com.alibaba.excel.read; package com.alibaba.excel.analysis.v03;
import java.io.IOException; import com.alibaba.excel.analysis.BaseSaxAnalyser;
import java.util.ArrayList; import com.alibaba.excel.context.AnalysisContext;
import java.util.List; import com.alibaba.excel.event.OneRowAnalysisFinishEvent;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.event.OneRowAnalysisFinishEvent;
import com.alibaba.excel.read.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import org.apache.poi.hssf.eventusermodel.*;
import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder;
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener;
import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord; import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord; import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
import org.apache.poi.hssf.model.HSSFFormulaParser; import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.hssf.record.BOFRecord; import org.apache.poi.hssf.record.*;
import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.LabelRecord;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.NoteRecord;
import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.RKRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.SSTRecord;
import org.apache.poi.hssf.record.StringRecord;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/** /**
* 2003版Excel解析器
* *
* @author jipengfei * @author jipengfei
*/ */
public class SaxAnalyserV03 extends BaseSaxAnalyser implements HSSFListener { public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener {
private boolean analyAllSheet = false; private boolean analyAllSheet = false;
public SaxAnalyserV03(AnalysisContext context) { public XlsSaxAnalyser(AnalysisContext context) throws IOException {
this.analysisContext = context; this.analysisContext = context;
this.records = new ArrayList<String>(); this.records = new ArrayList<String>();
if (analysisContext.getCurrentSheet() == null) { if (analysisContext.getCurrentSheet() == null) {
this.analyAllSheet = true; this.analyAllSheet = true;
} }
context.setCurrentRowNum(0); context.setCurrentRowNum(0);
try {
this.fs = new POIFSFileSystem(analysisContext.getInputStream()); this.fs = new POIFSFileSystem(analysisContext.getInputStream());
} catch (IOException e) {
throw new ExcelAnalysisException(e);
}
} }
public List<Sheet> getSheets() { public List<Sheet> getSheets() {
@ -62,10 +41,6 @@ public class SaxAnalyserV03 extends BaseSaxAnalyser implements HSSFListener {
return sheets; return sheets;
} }
public void stop() {
}
@Override @Override
public void execute() { public void execute() {
init(); init();

40
src/main/java/com/alibaba/excel/read/v07/RowHandler.java → src/main/java/com/alibaba/excel/analysis/v07/XlsxRowHandler.java

@ -1,30 +1,26 @@
package com.alibaba.excel.read.v07; package com.alibaba.excel.analysis.v07;
import java.util.Arrays;
import java.util.List;
import com.alibaba.excel.annotation.FieldType; import com.alibaba.excel.annotation.FieldType;
import com.alibaba.excel.util.ExcelXmlConstants; import com.alibaba.excel.constant.ExcelXmlConstants;
import com.alibaba.excel.read.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventRegisterCenter; import com.alibaba.excel.event.AnalysisEventRegisterCenter;
import com.alibaba.excel.read.event.OneRowAnalysisFinishEvent; import com.alibaba.excel.event.OneRowAnalysisFinishEvent;
import com.alibaba.excel.util.PositionUtils; import com.alibaba.excel.util.PositionUtils;
import org.apache.poi.xssf.model.SharedStringsTable; import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.DefaultHandler;
import static com.alibaba.excel.util.ExcelXmlConstants.CELL_VALUE_TAG; import java.util.Arrays;
import static com.alibaba.excel.util.ExcelXmlConstants.CELL_VALUE_TAG_1;
import static com.alibaba.excel.util.ExcelXmlConstants.DIMENSION; import static com.alibaba.excel.constant.ExcelXmlConstants.*;
import static com.alibaba.excel.util.ExcelXmlConstants.DIMENSION_REF;
import static com.alibaba.excel.util.ExcelXmlConstants.ROW_TAG;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/08/23
*/ */
public class RowHandler extends DefaultHandler { public class XlsxRowHandler extends DefaultHandler {
private String currentCellIndex; private String currentCellIndex;
@ -44,14 +40,11 @@ public class RowHandler extends DefaultHandler {
private AnalysisEventRegisterCenter registerCenter; private AnalysisEventRegisterCenter registerCenter;
private List<String> sharedStringList; public XlsxRowHandler(AnalysisEventRegisterCenter registerCenter, SharedStringsTable sst,
AnalysisContext analysisContext) {
public RowHandler(AnalysisEventRegisterCenter registerCenter, SharedStringsTable sst,
AnalysisContext analysisContext, List<String> sharedStringList) {
this.registerCenter = registerCenter; this.registerCenter = registerCenter;
this.analysisContext = analysisContext; this.analysisContext = analysisContext;
this.sst = sst; this.sst = sst;
this.sharedStringList = sharedStringList;
} }
@ -107,11 +100,7 @@ public class RowHandler extends DefaultHandler {
switch (currentCellType) { switch (currentCellType) {
case STRING: case STRING:
int idx = Integer.parseInt(currentCellValue); int idx = Integer.parseInt(currentCellValue);
if (idx < sharedStringList.size()) { currentCellValue = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
currentCellValue = sharedStringList.get(idx);
} else {
currentCellValue = "";
}
currentCellType = FieldType.EMPTY; currentCellType = FieldType.EMPTY;
break; break;
//case DATE: //case DATE:
@ -141,6 +130,7 @@ public class RowHandler extends DefaultHandler {
} }
private void setTotalRowCount(String name, Attributes attributes) { private void setTotalRowCount(String name, Attributes attributes) {
if (DIMENSION.equals(name)) { if (DIMENSION.equals(name)) {
String d = attributes.getValue(DIMENSION_REF); String d = attributes.getValue(DIMENSION_REF);

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

@ -0,0 +1,144 @@
package com.alibaba.excel.analysis.v07;
import com.alibaba.excel.analysis.BaseSaxAnalyser;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.Sheet;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @author jipengfei
* @date 2017/08/27
*/
public class XlsxSaxAnalyser extends BaseSaxAnalyser {
private XSSFReader xssfReader;
private SharedStringsTable sharedStringsTable;
private List<SheetSource> sheetSourceList = new ArrayList<SheetSource>();
private boolean use1904WindowDate = false;
public XlsxSaxAnalyser(AnalysisContext analysisContext) throws IOException, OpenXML4JException, XmlException {
this.analysisContext = analysisContext;
analysisContext.setCurrentRowNum(0);
this.xssfReader = new XSSFReader(OPCPackage.open(analysisContext.getInputStream()));
this.sharedStringsTable = this.xssfReader.getSharedStringsTable();
InputStream workbookXml = xssfReader.getWorkbookData();
WorkbookDocument ctWorkbook = WorkbookDocument.Factory.parse(workbookXml);
CTWorkbook wb = ctWorkbook.getWorkbook();
CTWorkbookPr prefix = wb.getWorkbookPr();
if (prefix != null) {
this.use1904WindowDate = prefix.getDate1904();
}
this.analysisContext.setUse1904WindowDate(use1904WindowDate);
XSSFReader.SheetIterator ite;
sheetSourceList = new ArrayList<SheetSource>();
ite = (XSSFReader.SheetIterator)xssfReader.getSheetsData();
while (ite.hasNext()) {
InputStream inputStream = ite.next();
String sheetName = ite.getSheetName();
SheetSource sheetSource = new SheetSource(sheetName, inputStream);
sheetSourceList.add(sheetSource);
}
}
protected void execute() {
Sheet sheetParam = analysisContext.getCurrentSheet();
if (sheetParam != null && sheetParam.getSheetNo() > 0 && sheetSourceList.size() >= sheetParam.getSheetNo()) {
InputStream sheetInputStream = sheetSourceList.get(sheetParam.getSheetNo() - 1).getInputStream();
parseXmlSource(sheetInputStream);
} else {
int i = 0;
for (SheetSource sheetSource : sheetSourceList) {
i++;
analysisContext.setCurrentSheet(new Sheet(i));
parseXmlSource(sheetSource.getInputStream());
}
}
}
private void parseXmlSource(InputStream inputStream) {
InputSource sheetSource = new InputSource(inputStream);
try {
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
saxFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
saxFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
saxFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
SAXParser saxParser = saxFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
ContentHandler handler = new XlsxRowHandler(this, sharedStringsTable, analysisContext);
xmlReader.setContentHandler(handler);
xmlReader.parse(sheetSource);
inputStream.close();
} catch (Exception e) {
throw new ExcelAnalysisException(e);
}
}
public List<Sheet> getSheets() {
List<Sheet> sheets = new ArrayList<Sheet>();
int i = 1;
for (SheetSource sheetSource : sheetSourceList) {
Sheet sheet = new Sheet(i, 0);
sheet.setSheetName(sheetSource.getSheetName());
i++;
sheets.add(sheet);
}
return sheets;
}
class SheetSource {
private String sheetName;
private InputStream inputStream;
public SheetSource(String sheetName, InputStream inputStream) {
this.sheetName = sheetName;
this.inputStream = inputStream;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}
}

14
src/main/java/com/alibaba/excel/annotation/ExcelColumnNum.java

@ -1,17 +1,13 @@
package com.alibaba.excel.annotation; package com.alibaba.excel.annotation;
import java.lang.annotation.ElementType; import java.lang.annotation.*;
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. * Created by jipengfei on 17/3/19.
* Field column num at excel head * Field column num at excel head
* *
* @author jipengfei * @author jipengfei
* * @date 2017/03/19
*/ */
@Target(ElementType.FIELD) @Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@ -20,16 +16,16 @@ public @interface ExcelColumnNum {
/** /**
* col num * col num
* @return col num * @return
*/ */
int value(); int value();
/** /**
* *
* Default @see com.alibaba.TypeUtil * Default @see com.alibaba.excel.util.TypeUtil
* if default is not meet you can set format * if default is not meet you can set format
* *
* @return format * @return
*/ */
String format() default ""; String format() default "";
} }

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

@ -1,10 +1,6 @@
package com.alibaba.excel.annotation; package com.alibaba.excel.annotation;
import java.lang.annotation.ElementType; import java.lang.annotation.*;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** /**
* @author jipengfei * @author jipengfei
@ -15,24 +11,22 @@ import java.lang.annotation.Target;
public @interface ExcelProperty { public @interface ExcelProperty {
/** /**
* 某列表头值 * @return
* @return 表头值
*/ */
String[] value() default {""}; String[] value() default {""};
/** /**
* 列顺序越小越靠前 * @return
* @return 列顺序
*/ */
int index() default 99999; int index() default 99999;
/** /**
* *
* default @see com.alibaba.TypeUtil * default @see com.alibaba.excel.util.TypeUtil
* if default is not meet you can set format * if default is not meet you can set format
* *
* @return 日期格式化 * @return
*/ */
String format() default ""; String format() default "";
} }

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

@ -3,7 +3,7 @@ package com.alibaba.excel.annotation;
/** /**
* *
* @author jipengfei * @author jipengfei
* * @date 2017/03/15
*/ */
public enum FieldType { public enum FieldType {

4
src/main/java/com/alibaba/excel/util/ExcelXmlConstants.java → src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java

@ -1,8 +1,8 @@
package com.alibaba.excel.util; package com.alibaba.excel.constant;
/** /**
* @author jipengfei * @author jipengfei
* * @date 2017/08/24
*/ */
public class ExcelXmlConstants { public class ExcelXmlConstants {
public static final String DIMENSION = "dimension"; public static final String DIMENSION = "dimension";

57
src/main/java/com/alibaba/excel/read/context/AnalysisContext.java → src/main/java/com/alibaba/excel/context/AnalysisContext.java

@ -1,140 +1,123 @@
package com.alibaba.excel.read.context; package com.alibaba.excel.context;
import java.io.InputStream; import com.alibaba.excel.event.AnalysisEventListener;
import java.util.List;
import com.alibaba.excel.read.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel; import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.ExcelHeadProperty; import com.alibaba.excel.metadata.ExcelHeadProperty;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.InputStream;
import java.util.List;
/** /**
* 解析文件上下文
* *
* @author jipengfei * @author jipengfei
*/ */
public interface AnalysisContext { public interface AnalysisContext {
/** /**
* 返回用户自定义数据
* *
* @return 返回用户自定义数据
*/ */
Object getCustom(); Object getCustom();
/** /**
* 返回当前Sheet
* *
* @return current read sheet * @return current analysis sheet
*/ */
Sheet getCurrentSheet(); Sheet getCurrentSheet();
/** /**
* 设置当前解析的Sheet
* *
* @param sheet 入参 * @param sheet
*/ */
void setCurrentSheet(Sheet sheet); void setCurrentSheet(Sheet sheet);
/** /**
* 返回解析的Excel类型
* *
* @return excel type * @return excel type
*/ */
ExcelTypeEnum getExcelType(); ExcelTypeEnum getExcelType();
/** /**
* 返回输入IO
* *
* @return file io * @return file io
*/ */
InputStream getInputStream(); InputStream getInputStream();
/** /**
* 获取当前监听者
* *
* @return listener * @return
*/ */
AnalysisEventListener getEventListener(); AnalysisEventListener getEventListener();
/** /**
* 获取当前行数
* *
* @return 当前行 * @return
*/ */
Integer getCurrentRowNum(); Integer getCurrentRowNum();
/** /**
* 设置当前行数
* *
* @param row 设置行号 * @param row
*/ */
void setCurrentRowNum(Integer row); void setCurrentRowNum(Integer row);
/** /**
* 返回当前sheet共有多少行数据仅限07版excel
* *
* @return 总行数 * @return
*/ */
@Deprecated
Integer getTotalCount(); Integer getTotalCount();
/** /**
* 设置总条数
* *
* @param totalCount 总行数 * @param totalCount
*/ */
void setTotalCount(Integer totalCount); void setTotalCount(Integer totalCount);
/** /**
* 返回表头信息
* *
* @return 表头信息 * @return
*/ */
ExcelHeadProperty getExcelHeadProperty(); ExcelHeadProperty getExcelHeadProperty();
/** /**
* 构建 ExcelHeadProperty
* *
* @param clazz 自定义model * @param clazz
* @param headOneRow 表头内容 * @param headOneRow
*/ */
void buildExcelHeadProperty(Class<? extends BaseRowModel> clazz, List<String> headOneRow); void buildExcelHeadProperty(Class<? extends BaseRowModel> clazz, List<String> headOneRow);
/** /**
* 是否trim()
* *
* @return 是否trim * @return
*/ */
boolean trim(); boolean trim();
/** /**
* *
* @param result 解析结果
*/ */
void setCurrentRowAnalysisResult(Object result); void setCurrentRowAnalysisResult(Object result);
/** /**
* *
* @return 当前行解析结果
*/ */
Object getCurrentRowAnalysisResult(); Object getCurrentRowAnalysisResult();
/** /**
* 中断 *
*/ */
void interrupt(); void interrupt();
/** /**
* *
* @return 是否use1904WindowDate * @return
*/ */
boolean use1904WindowDate(); boolean use1904WindowDate();
/** /**
* *
* @param use1904WindowDate 是否use1904WindowDate * @param use1904WindowDate
*/ */
void setUse1904WindowDate(boolean use1904WindowDate); void setUse1904WindowDate(boolean use1904WindowDate);
} }

15
src/main/java/com/alibaba/excel/read/context/AnalysisContextImpl.java → src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java

@ -1,18 +1,17 @@
package com.alibaba.excel.read.context; package com.alibaba.excel.context;
import java.io.InputStream; import com.alibaba.excel.event.AnalysisEventListener;
import java.util.ArrayList; import com.alibaba.excel.exception.ExcelAnalysisException;
import java.util.List;
import com.alibaba.excel.read.event.AnalysisEventListener;
import com.alibaba.excel.read.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.BaseRowModel; import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.ExcelHeadProperty; import com.alibaba.excel.metadata.ExcelHeadProperty;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/** /**
* 解析Excel上线文默认实现
* *
* @author jipengfei * @author jipengfei
*/ */

29
src/main/java/com/alibaba/excel/write/context/GenerateContext.java → src/main/java/com/alibaba/excel/context/GenerateContext.java

@ -1,14 +1,13 @@
package com.alibaba.excel.write.context; package com.alibaba.excel.context;
import java.io.OutputStream;
import com.alibaba.excel.metadata.ExcelHeadProperty; import com.alibaba.excel.metadata.ExcelHeadProperty;
import com.alibaba.excel.metadata.Table; import com.alibaba.excel.metadata.Table;
import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import java.io.OutputStream;
/** /**
* @author jipengfei * @author jipengfei
*/ */
@ -16,58 +15,50 @@ public interface GenerateContext {
/** /**
* 返回当前sheet * @return current analysis sheet
* @return current read sheet
*/ */
Sheet getCurrentSheet(); Sheet getCurrentSheet();
/** /**
* *
* 获取表头样式 * @return
* @return 当前行表头样式
*/ */
CellStyle getCurrentHeadCellStyle(); CellStyle getCurrentHeadCellStyle();
/** /**
* 获取内容样式 * @return
* @return 当前行内容样式
*/ */
CellStyle getCurrentContentStyle(); CellStyle getCurrentContentStyle();
/** /**
* 返回WorkBook * @return
* @return 返回文件book
*/ */
Workbook getWorkbook(); Workbook getWorkbook();
/** /**
* 返回Io流 * @return
* @return 返回out流
*/ */
OutputStream getOutputStream(); OutputStream getOutputStream();
/** /**
* 构建一个sheet
* @param sheet * @param sheet
*/ */
void buildCurrentSheet(com.alibaba.excel.metadata.Sheet sheet); void buildCurrentSheet(com.alibaba.excel.metadata.Sheet sheet);
/** /**
* 构建一个Table
* @param table * @param table
*/ */
void buildTable(Table table); void buildTable(Table table);
/** /**
* 返回表头信息 * @return
* @return 返回表头信息
*/ */
ExcelHeadProperty getExcelHeadProperty(); ExcelHeadProperty getExcelHeadProperty();
/** /**
* *
* @return 是否需要表头 * @return
*/ */
boolean needHead(); boolean needHead();
} }

56
src/main/java/com/alibaba/excel/write/context/GenerateContextImpl.java → src/main/java/com/alibaba/excel/context/GenerateContextImpl.java

@ -1,34 +1,26 @@
package com.alibaba.excel.write.context; package com.alibaba.excel.context;
import java.io.OutputStream; import com.alibaba.excel.metadata.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.CellRange; import com.alibaba.excel.metadata.CellRange;
import com.alibaba.excel.metadata.ExcelHeadProperty;
import com.alibaba.excel.metadata.Table; import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* 生成Excel上下文
* *
* @author jipengfei * @author jipengfei
*/ */
@ -58,11 +50,20 @@ public class GenerateContextImpl implements GenerateContext {
private boolean needHead = true; private boolean needHead = true;
public GenerateContextImpl(OutputStream out, ExcelTypeEnum excelType, boolean needHead) { public GenerateContextImpl(InputStream templateInputStream, OutputStream out, ExcelTypeEnum excelType,
boolean needHead) throws IOException {
if (ExcelTypeEnum.XLS.equals(excelType)) { if (ExcelTypeEnum.XLS.equals(excelType)) {
if(templateInputStream == null) {
this.workbook = new HSSFWorkbook(); this.workbook = new HSSFWorkbook();
}else {
this.workbook = new HSSFWorkbook(new POIFSFileSystem(templateInputStream));
}
} else { } else {
if(templateInputStream == null) {
this.workbook = new SXSSFWorkbook(500); this.workbook = new SXSSFWorkbook(500);
}else {
this.workbook = new SXSSFWorkbook(new XSSFWorkbook(templateInputStream));
}
} }
this.outputStream = out; this.outputStream = out;
this.defaultCellStyle = buildDefaultCellStyle(); this.defaultCellStyle = buildDefaultCellStyle();
@ -91,9 +92,22 @@ public class GenerateContextImpl implements GenerateContext {
if (sheetMap.containsKey(sheet.getSheetNo())) { if (sheetMap.containsKey(sheet.getSheetNo())) {
this.currentSheet = sheetMap.get(sheet.getSheetNo()); this.currentSheet = sheetMap.get(sheet.getSheetNo());
} else { } else {
Sheet sheet1 = null;
try {
sheet1 = workbook.getSheetAt(sheet.getSheetNo());
}catch (Exception e){
}
if(sheet1 == null) {
this.currentSheet = workbook.createSheet( this.currentSheet = workbook.createSheet(
sheet.getSheetName() != null ? sheet.getSheetName() : sheet.getSheetNo() + ""); sheet.getSheetName() != null ? sheet.getSheetName() : sheet.getSheetNo() + "");
this.currentSheet.setDefaultColumnWidth(20); this.currentSheet.setDefaultColumnWidth(20);
for (Map.Entry<Integer, Integer> entry : sheet.getColumnWidthMap().entrySet()) {
currentSheet.setColumnWidth(entry.getKey(), entry.getValue());
}
}else {
this.currentSheet = sheet1;
}
sheetMap.put(sheet.getSheetNo(), this.currentSheet); sheetMap.put(sheet.getSheetNo(), this.currentSheet);
buildHead(sheet.getHead(), sheet.getClazz()); buildHead(sheet.getHead(), sheet.getClazz());
buildTableStyle(sheet.getTableStyle()); buildTableStyle(sheet.getTableStyle());

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

@ -0,0 +1,26 @@
package com.alibaba.excel.event;
import com.alibaba.excel.context.AnalysisContext;
/**
*
*
* @author jipengfei
*/
public abstract class AnalysisEventListener<T> {
/**
* when analysis one row trigger invoke function
*
* @param object one row data
* @param context analysis context
*/
public abstract void invoke(T object, AnalysisContext context);
/**
* if have something to do after all analysis
*
* @param context
*/
public abstract void doAfterAllAnalysed(AnalysisContext context);
}

12
src/main/java/com/alibaba/excel/read/event/AnalysisEventRegisterCenter.java → src/main/java/com/alibaba/excel/event/AnalysisEventRegisterCenter.java

@ -1,29 +1,25 @@
package com.alibaba.excel.read.event; package com.alibaba.excel.event;
/** /**
* 管理每个监听者
* *
* @author jipengfei * @author jipengfei
*/ */
public interface AnalysisEventRegisterCenter { public interface AnalysisEventRegisterCenter {
/** /**
* 增加监听者 * @param name
* @param name 名称 * @param listener
* @param listener 监听器
*/ */
void appendLister(String name, AnalysisEventListener listener); void appendLister(String name, AnalysisEventListener listener);
/** /**
* 通知所有监听者 * @param event
* @param event 事件
*/ */
void notifyListeners(OneRowAnalysisFinishEvent event); void notifyListeners(OneRowAnalysisFinishEvent event);
/** /**
* 清空所有监听者
*/ */
void cleanAllListeners(); void cleanAllListeners();
} }

3
src/main/java/com/alibaba/excel/read/event/OneRowAnalysisFinishEvent.java → src/main/java/com/alibaba/excel/event/OneRowAnalysisFinishEvent.java

@ -1,7 +1,8 @@
package com.alibaba.excel.read.event; package com.alibaba.excel.event;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/07/21
*/ */
public class OneRowAnalysisFinishEvent { public class OneRowAnalysisFinishEvent {

3
src/main/java/com/alibaba/excel/read/exception/ExcelAnalysisException.java → src/main/java/com/alibaba/excel/exception/ExcelAnalysisException.java

@ -1,7 +1,6 @@
package com.alibaba.excel.read.exception; package com.alibaba.excel.exception;
/** /**
* Excel解析时候封装的异常
* *
* @author jipengfei * @author jipengfei
*/ */

4
src/main/java/com/alibaba/excel/write/exception/ExcelGenerateException.java → src/main/java/com/alibaba/excel/exception/ExcelGenerateException.java

@ -1,7 +1,6 @@
package com.alibaba.excel.write.exception; package com.alibaba.excel.exception;
/** /**
* 生成Excel封装的异常
* @author jipengfei * @author jipengfei
*/ */
public class ExcelGenerateException extends RuntimeException { public class ExcelGenerateException extends RuntimeException {
@ -18,4 +17,5 @@ public class ExcelGenerateException extends RuntimeException {
public ExcelGenerateException(Throwable cause) { public ExcelGenerateException(Throwable cause) {
super(cause); super(cause);
} }
} }

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

@ -1,9 +1,34 @@
package com.alibaba.excel.metadata; package com.alibaba.excel.metadata;
import org.apache.poi.ss.usermodel.CellStyle;
import java.util.HashMap;
import java.util.Map;
/** /**
* Excel基础模型 * Excel基础模型
* @author jipengfei * @author jipengfei
*/ */
public class BaseRowModel { public class BaseRowModel {
/**
* 每列样式
*/
private Map<Integer, CellStyle> cellStyleMap = new HashMap<Integer, CellStyle>();
public void addStyle(Integer row, CellStyle cellStyle){
cellStyleMap.put(row,cellStyle);
}
public CellStyle getStyle(Integer row){
return cellStyleMap.get(row);
}
public Map<Integer, CellStyle> getCellStyleMap() {
return cellStyleMap;
}
public void setCellStyleMap(Map<Integer, CellStyle> cellStyleMap) {
this.cellStyleMap = cellStyleMap;
}
} }

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

@ -2,6 +2,7 @@ package com.alibaba.excel.metadata;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/06/02
*/ */
public class CellRange { public class CellRange {

5
src/main/java/com/alibaba/excel/metadata/ExcelColumnProperty.java

@ -6,26 +6,23 @@ import java.util.List;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/05/31
*/ */
public class ExcelColumnProperty implements Comparable<ExcelColumnProperty> { public class ExcelColumnProperty implements Comparable<ExcelColumnProperty> {
/** /**
* 列对应的Class field字段
*/ */
private Field field; private Field field;
/** /**
* 列顺序 默认很大
*/ */
private int index = 99999; private int index = 99999;
/** /**
* 该列对应的表头
*/ */
private List<String> head = new ArrayList<String>(); private List<String> head = new ArrayList<String>();
/** /**
* 日期类型format "yyyy-MM-dd HH:mm:ss"
*/ */
private String format; private String format;

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

@ -1,40 +1,31 @@
package com.alibaba.excel.metadata; package com.alibaba.excel.metadata;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.annotation.ExcelColumnNum; import com.alibaba.excel.annotation.ExcelColumnNum;
import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.ExcelProperty;
import java.lang.reflect.Field;
import java.util.*;
/** /**
* 表头信息
* *
* @author jipengfei * @author jipengfei
* @date 2017/05/31
*/ */
public class ExcelHeadProperty { public class ExcelHeadProperty {
/** /**
* 表头数据对应的Class
*/ */
private Class<? extends BaseRowModel> headClazz; private Class<? extends BaseRowModel> headClazz;
/** /**
* 表头名称
*/ */
private List<List<String>> head = new ArrayList<List<String>>(); private List<List<String>> head = new ArrayList<List<String>>();
/** /**
* Excel每列表头数据
*/ */
private List<ExcelColumnProperty> columnPropertyList = new ArrayList<ExcelColumnProperty>(); private List<ExcelColumnProperty> columnPropertyList = new ArrayList<ExcelColumnProperty>();
/** /**
* key:Excel列号value:表头数据
*/ */
private Map<Integer, ExcelColumnProperty> excelColumnPropertyMap1 = new HashMap<Integer, ExcelColumnProperty>(); private Map<Integer, ExcelColumnProperty> excelColumnPropertyMap1 = new HashMap<Integer, ExcelColumnProperty>();
@ -45,7 +36,6 @@ public class ExcelHeadProperty {
} }
/** /**
* 初始化每列
*/ */
private void initColumnProperties() { private void initColumnProperties() {
if (this.headClazz != null) { if (this.headClazz != null) {
@ -66,7 +56,6 @@ public class ExcelHeadProperty {
} }
/** /**
* 初始化一列
* *
* @param f * @param f
*/ */
@ -97,9 +86,7 @@ public class ExcelHeadProperty {
} }
/** /**
* 将表头的一行数据转换为一列一列形式组成表头
* *
* @param row 表头中的一行数据
*/ */
public void appendOneRow(List<String> row) { public void appendOneRow(List<String> row) {
@ -117,10 +104,9 @@ public class ExcelHeadProperty {
} }
/** /**
* 根据Excel中的列号获取Excel的表头信息
* *
* @param columnNum 列号 * @param columnNum
* @return ExcelColumnProperty * @return
*/ */
public ExcelColumnProperty getExcelColumnProperty(int columnNum) { public ExcelColumnProperty getExcelColumnProperty(int columnNum) {
ExcelColumnProperty excelColumnProperty = excelColumnPropertyMap1.get(columnNum); ExcelColumnProperty excelColumnProperty = excelColumnPropertyMap1.get(columnNum);
@ -138,18 +124,6 @@ public class ExcelHeadProperty {
} }
/** /**
* 根据Excel中的列号获取Excel的表头信息
*
* @param columnNum 列号
* @return ExcelColumnProperty
*/
public ExcelColumnProperty getExcelColumnProperty1(int columnNum) {
return excelColumnPropertyMap1.get(columnNum);
}
/**
* 判断表头是否相同
* *
* @param columnHead * @param columnHead
* @param head * @param head

5
src/main/java/com/alibaba/excel/metadata/Font.java

@ -1,24 +1,21 @@
package com.alibaba.excel.metadata; package com.alibaba.excel.metadata;
/** /**
* 字体样式
* *
* @author jipengfei * @author jipengfei
* @date 2017/05/24
*/ */
public class Font { public class Font {
/** /**
* 字体名称宋体黑体
*/ */
private String fontName; private String fontName;
/** /**
* 字体大小
*/ */
private short fontHeightInPoints; private short fontHeightInPoints;
/** /**
* 是否加粗
*/ */
private boolean bold; private boolean bold;

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

@ -1,36 +1,32 @@
package com.alibaba.excel.metadata; package com.alibaba.excel.metadata;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* Sheet参数
* *
* @author jipengfei * @author jipengfei
*/ */
public class Sheet { public class Sheet {
/** /**
* 表头行数
*/ */
private int headLineMun; private int headLineMun;
/** /**
* sheet序号 从0开始
*/ */
private int sheetNo; private int sheetNo;
/** /**
* 名称 可不填
*/ */
private String sheetName; private String sheetName;
/** /**
* 对用的表头模型
*/ */
private Class<? extends BaseRowModel> clazz; private Class<? extends BaseRowModel> clazz;
/** /**
* 对用的表头层级树,用于clazz不确定时候动态生成表头
*/ */
private List<List<String>> head; private List<List<String>> head;
@ -39,6 +35,22 @@ public class Sheet {
*/ */
private TableStyle tableStyle; private TableStyle tableStyle;
/**
* column with
*/
private Map<Integer,Integer> columnWidthMap = new HashMap<Integer, Integer>();
/**
*
*/
private Boolean autoWidth = Boolean.FALSE;
/**
*
*/
private int startRow = -1;
public Sheet(int sheetNo) { public Sheet(int sheetNo) {
this.sheetNo = sheetNo; this.sheetNo = sheetNo;
} }
@ -114,6 +126,16 @@ public class Sheet {
this.tableStyle = tableStyle; this.tableStyle = tableStyle;
} }
public Map<Integer, Integer> getColumnWidthMap() {
return columnWidthMap;
}
public void setColumnWidthMap(Map<Integer, Integer> columnWidthMap) {
this.columnWidthMap = columnWidthMap;
}
@Override @Override
public String toString() { public String toString() {
return "Sheet{" + return "Sheet{" +
@ -123,6 +145,23 @@ public class Sheet {
", clazz=" + clazz + ", clazz=" + clazz +
", head=" + head + ", head=" + head +
", tableStyle=" + tableStyle + ", tableStyle=" + tableStyle +
", columnWidthMap=" + columnWidthMap +
'}'; '}';
} }
public Boolean getAutoWidth() {
return autoWidth;
}
public void setAutoWidth(Boolean autoWidth) {
this.autoWidth = autoWidth;
}
public int getStartRow() {
return startRow;
}
public void setStartRow(int startRow) {
this.startRow = startRow;
}
} }

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

@ -4,25 +4,22 @@ import java.util.List;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/05/16
*/ */
public class Table { public class Table {
/** /**
* 对用的表头模型
*/ */
private Class<? extends BaseRowModel> clazz; private Class<? extends BaseRowModel> clazz;
/** /**
* 对用的表头层级树,用于clazz不确定时候动态生成表头
*/ */
private List<List<String>> head; private List<List<String>> head;
/** /**
* 第几个table,用于和其他table区分
*/ */
private Integer tableNo; private Integer tableNo;
/** /**
* 支持表格简单样式自定义
*/ */
private TableStyle tableStyle; private TableStyle tableStyle;

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

@ -4,6 +4,7 @@ import org.apache.poi.ss.usermodel.IndexedColors;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/05/24
*/ */
public class TableStyle { public class TableStyle {

16
src/main/java/com/alibaba/excel/read/modelbuild/ModelBuildEventListener.java → src/main/java/com/alibaba/excel/modelbuild/ModelBuildEventListener.java

@ -1,18 +1,16 @@
package com.alibaba.excel.read.modelbuild; package com.alibaba.excel.modelbuild;
import java.util.List; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.context.AnalysisContext; import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.read.event.AnalysisEventListener;
import com.alibaba.excel.write.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.ExcelColumnProperty; import com.alibaba.excel.metadata.ExcelColumnProperty;
import com.alibaba.excel.metadata.ExcelHeadProperty; import com.alibaba.excel.metadata.ExcelHeadProperty;
import com.alibaba.excel.util.TypeUtil; import com.alibaba.excel.util.TypeUtil;
import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.BeanUtils;
import java.util.List;
/** /**
* 监听POI Sax解析的每行结果
* *
* @author jipengfei * @author jipengfei
*/ */
@ -43,7 +41,7 @@ public class ModelBuildEventListener extends AnalysisEventListener {
} }
if (excelHeadProperty != null) { if (excelHeadProperty != null) {
for (int i = 0; i < stringList.size(); i++) { for (int i = 0; i < stringList.size(); i++) {
ExcelColumnProperty columnProperty = excelHeadProperty.getExcelColumnProperty1(i); ExcelColumnProperty columnProperty = excelHeadProperty.getExcelColumnProperty(i);
if (columnProperty != null) { if (columnProperty != null) {
Object value = TypeUtil.convert(stringList.get(i), columnProperty.getField(), Object value = TypeUtil.convert(stringList.get(i), columnProperty.getField(),
columnProperty.getFormat(),context.use1904WindowDate()); columnProperty.getFormat(),context.use1904WindowDate());

58
src/main/java/com/alibaba/excel/parameter/AnalysisParam.java

@ -0,0 +1,58 @@
package com.alibaba.excel.parameter;
import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.InputStream;
/**
*
* @author jipengfei
*/
@Deprecated
public class AnalysisParam {
/**
* @see ExcelTypeEnum
*/
private ExcelTypeEnum excelTypeEnum;
/**
* file in
*/
private InputStream in;
/**
* user defined param to listener use
*/
private Object customContent;
public AnalysisParam(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent) {
this.in = in;
this.excelTypeEnum = excelTypeEnum;
this.customContent = customContent;
}
public ExcelTypeEnum getExcelTypeEnum() {
return excelTypeEnum;
}
public void setExcelTypeEnum(ExcelTypeEnum excelTypeEnum) {
this.excelTypeEnum = excelTypeEnum;
}
public Object getCustomContent() {
return customContent;
}
public void setCustomContent(Object customContent) {
this.customContent = customContent;
}
public InputStream getIn() {
return in;
}
public void setIn(InputStream in) {
this.in = in;
}
}

45
src/main/java/com/alibaba/excel/parameter/ExcelWriteParam.java

@ -0,0 +1,45 @@
package com.alibaba.excel.parameter;
import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.OutputStream;
/**
* {@link com.alibaba.excel.ExcelWriter}
*
* @author jipengfei
* @date 2017/05/15
*/
@Deprecated
public class ExcelWriteParam {
/**
*/
private OutputStream outputStream;
/**
*/
private ExcelTypeEnum type;
public ExcelWriteParam(OutputStream outputStream, ExcelTypeEnum type) {
this.outputStream = outputStream;
this.type = type;
}
public OutputStream getOutputStream() {
return outputStream;
}
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
public ExcelTypeEnum getType() {
return type;
}
public void setType(ExcelTypeEnum type) {
this.type = type;
}
}

58
src/main/java/com/alibaba/excel/parameter/GenerateParam.java

@ -0,0 +1,58 @@
package com.alibaba.excel.parameter;
import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.OutputStream;
/**
* Created by jipengfei on 17/2/19.
*/
public class GenerateParam {
private OutputStream outputStream;
private String sheetName;
private Class clazz;
private ExcelTypeEnum type;
public GenerateParam(String sheetName, Class clazz, OutputStream outputStream) {
this.outputStream = outputStream;
this.sheetName = sheetName;
this.clazz = clazz;
}
public OutputStream getOutputStream() {
return outputStream;
}
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public Class getClazz() {
return clazz;
}
public void setClazz(Class clazz) {
this.clazz = clazz;
}
public ExcelTypeEnum getType() {
return type;
}
public void setType(ExcelTypeEnum type) {
this.type = type;
}
}

54
src/main/java/com/alibaba/excel/read/ExcelAnalyser.java

@ -1,54 +0,0 @@
package com.alibaba.excel.read;
import java.io.InputStream;
import java.util.List;
import com.alibaba.excel.read.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
/**
* Excel解析器
*
* @author jipengfei
*/
public interface ExcelAnalyser {
/**
* Excel解析初始化
*
* @param inputStream 解析为文件流
* @param excelTypeEnum 解析文件类型
* @param custom 用户自定义参数用户回调时候可以获取到
* @param eventListener 解析器需要的监听器
* @param trim 是否去空格
*/
void init(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Object custom, AnalysisEventListener eventListener,
boolean trim);
/**
* 解析指定sheet,{@link AnalysisEventListener}监听中使用
*
* @param sheetParam 入参
*/
void analysis(Sheet sheetParam);
/**
*
* 默认解析第一个sheet解析结果在 {@link AnalysisEventListener}监听中使用
*/
void analysis();
/**
* 返回excel中包含哪些sheet
*
* @return 返回所有sheet
*/
List<Sheet> getSheets();
/**
* 关闭流
*/
void stop();
}

331
src/main/java/com/alibaba/excel/read/SaxAnalyserV07.java

@ -1,331 +0,0 @@
package com.alibaba.excel.read;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import javax.xml.parsers.ParserConfigurationException;
import com.alibaba.excel.read.v07.RowHandler;
import com.alibaba.excel.read.v07.XmlParserFactory;
import com.alibaba.excel.read.v07.XMLTempFile;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.util.FileUtil;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* @author jipengfei
*/
public class SaxAnalyserV07 extends BaseSaxAnalyser {
private SharedStringsTable sharedStringsTable;
private List<String> sharedStringList = new LinkedList<String>();
private List<SheetSource> sheetSourceList = new ArrayList<SheetSource>();
private boolean use1904WindowDate = false;
private final String path;
private File tmpFile;
private String workBookXMLFilePath;
private String sharedStringXMLFilePath;
public SaxAnalyserV07(AnalysisContext analysisContext) throws Exception {
this.analysisContext = analysisContext;
this.path = XMLTempFile.createPath();
this.tmpFile = new File(XMLTempFile.getTmpFilePath(path));
this.workBookXMLFilePath = XMLTempFile.getWorkBookFilePath(path);
this.sharedStringXMLFilePath = XMLTempFile.getSharedStringFilePath(path);
start();
}
@Override
protected void execute() {
try {
Sheet sheet = analysisContext.getCurrentSheet();
if (!isAnalysisAllSheets(sheet)) {
if (this.sheetSourceList.size() < sheet.getSheetNo() || sheet.getSheetNo() == 0) {
return;
}
InputStream sheetInputStream = this.sheetSourceList.get(sheet.getSheetNo() - 1).getInputStream();
parseXmlSource(sheetInputStream);
return;
}
int i = 0;
for (SheetSource sheetSource : this.sheetSourceList) {
i++;
this.analysisContext.setCurrentSheet(new Sheet(i));
parseXmlSource(sheetSource.getInputStream());
}
} catch (Exception e) {
stop();
throw new ExcelAnalysisException(e);
} finally {
}
}
private boolean isAnalysisAllSheets(Sheet sheet) {
if (sheet == null) {
return true;
}
if (sheet.getSheetNo() < 0) {
return true;
}
return false;
}
public void stop() {
for (SheetSource sheet : sheetSourceList) {
if (sheet.getInputStream() != null) {
try {
sheet.getInputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileUtil.deletefile(path);
}
private void parseXmlSource(InputStream inputStream) {
try {
ContentHandler handler = new RowHandler(this, this.sharedStringsTable, this.analysisContext,
sharedStringList);
XmlParserFactory.parse(inputStream, handler);
inputStream.close();
} catch (Exception e) {
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
throw new ExcelAnalysisException(e);
}
}
public List<Sheet> getSheets() {
List<Sheet> sheets = new ArrayList<Sheet>();
try {
int i = 1;
for (SheetSource sheetSource : this.sheetSourceList) {
Sheet sheet = new Sheet(i, 0);
sheet.setSheetName(sheetSource.getSheetName());
i++;
sheets.add(sheet);
}
} catch (Exception e) {
stop();
throw new ExcelAnalysisException(e);
} finally {
}
return sheets;
}
private void start() throws IOException, XmlException, ParserConfigurationException, SAXException {
createTmpFile();
unZipTempFile();
initSharedStringsTable();
initUse1904WindowDate();
initSheetSourceList();
}
private void createTmpFile() throws FileNotFoundException {
FileUtil.writeFile(tmpFile, analysisContext.getInputStream());
}
private void unZipTempFile() throws IOException {
FileUtil.doUnZip(path, tmpFile);
}
private void initSheetSourceList() throws IOException, ParserConfigurationException, SAXException {
this.sheetSourceList = new ArrayList<SheetSource>();
InputStream workbookXml = new FileInputStream(this.workBookXMLFilePath);
XmlParserFactory.parse(workbookXml, new DefaultHandler() {
private int id = 0;
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
if (qName.toLowerCase(Locale.US).equals("sheet")) {
String name = null;
id++;
for (int i = 0; i < attrs.getLength(); i++) {
if (attrs.getLocalName(i).toLowerCase(Locale.US).equals("name")) {
name = attrs.getValue(i);
} else if (attrs.getLocalName(i).toLowerCase(Locale.US).equals("r:id")) {
//id = Integer.parseInt(attrs.getValue(i).replaceAll("rId", ""));
try {
InputStream inputStream = new FileInputStream(XMLTempFile.getSheetFilePath(path, id));
sheetSourceList.add(new SheetSource(id, name, inputStream));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
});
workbookXml.close();
Collections.sort(sheetSourceList);
}
private void initUse1904WindowDate() throws IOException, XmlException {
InputStream workbookXml = new FileInputStream(workBookXMLFilePath);
WorkbookDocument ctWorkbook = WorkbookDocument.Factory.parse(workbookXml);
CTWorkbook wb = ctWorkbook.getWorkbook();
CTWorkbookPr prefix = wb.getWorkbookPr();
if (prefix != null) {
this.use1904WindowDate = prefix.getDate1904();
}
this.analysisContext.setUse1904WindowDate(use1904WindowDate);
workbookXml.close();
}
private void initSharedStringsTable() throws IOException, ParserConfigurationException, SAXException {
InputStream inputStream = new FileInputStream(this.sharedStringXMLFilePath);
//this.sharedStringsTable = new SharedStringsTable();
//this.sharedStringsTable.readFrom(inputStream);
XmlParserFactory.parse(inputStream, new DefaultHandler() {
//int lastElementPosition = -1;
//
//int lastHandledElementPosition = -1;
String beforeQName = "";
String currentQName = "";
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
//if (hasSkippedEmptySharedString()) {
// sharedStringList.add("");
//}
//if ("t".equals(qName)) {
// lastElementPosition++;
//}
if ("si".equals(qName) || "t".equals(qName)) {
beforeQName = currentQName;
currentQName = qName;
}
}
//@Override
//public void endElement (String uri, String localName, String qName)
// throws SAXException
//{
// if ("si".equals(qName) || "t".equals(qName)) {
// beforeQName = qName;
// currentQName = "";
// }
//}
//private boolean hasSkippedEmptySharedString() {
// return lastElementPosition > lastHandledElementPosition;
//}
@Override
public void characters(char[] ch, int start, int length) {
if ("t".equals(currentQName) && ("t".equals(beforeQName))) {
String pre = sharedStringList.get(sharedStringList.size() - 1);
String str = pre + new String(ch, start, length);
sharedStringList.remove(sharedStringList.size() - 1);
sharedStringList.add(str);
}else if ("t".equals(currentQName) && ("si".equals(beforeQName))){
sharedStringList.add(new String(ch, start, length));
}
// lastHandledElementPosition++;
}
});
inputStream.close();
}
private class SheetSource implements Comparable<SheetSource> {
private int id;
private String sheetName;
private InputStream inputStream;
public SheetSource(int id, String sheetName, InputStream inputStream) {
this.id = id;
this.sheetName = sheetName;
this.inputStream = inputStream;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int compareTo(SheetSource o) {
if (o.id == this.id) {
return 0;
} else if (o.id > this.id) {
return -1;
} else {
return 1;
}
}
}
}

30
src/main/java/com/alibaba/excel/read/event/AnalysisEventListener.java

@ -1,30 +0,0 @@
package com.alibaba.excel.read.event;
import com.alibaba.excel.read.context.AnalysisContext;
/**
* 监听Excel解析每行数据
* 不能单列每次使用new一个
* 不能单列每次使用new一个
* 不能单列每次使用new一个
* 重要事情说三遍
*
* @author jipengfei
*/
public abstract class AnalysisEventListener<T> {
/**
* when read one row trigger invoke function
*
* @param object one row data
* @param context read context
*/
public abstract void invoke(T object, AnalysisContext context);
/**
* if have something to do after all read
*
* @param context context
*/
public abstract void doAfterAllAnalysed(AnalysisContext context);
}

48
src/main/java/com/alibaba/excel/read/v07/XMLTempFile.java

@ -1,48 +0,0 @@
package com.alibaba.excel.read.v07;
import java.io.File;
import java.security.SecureRandom;
import com.alibaba.excel.util.EasyExcelTempFile;
/**
* @author jipengfei
*
*/
public class XMLTempFile {
private static final String TMP_FILE_NAME = "tmp.xlsx";
private static final String XL = "xl";
private static final String XML_WORKBOOK = "workbook.xml";
private static final String XML_SHARED_STRING = "sharedStrings.xml";
private static final String SHEET = "sheet";
private static final String WORK_SHEETS = "worksheets";
private static final SecureRandom random = new SecureRandom();
public static String getTmpFilePath(String path) {
return path + File.separator + TMP_FILE_NAME;
}
public static String createPath() {
return EasyExcelTempFile.getEasyExcelTmpDir() + File.separator + random.nextLong();
}
public static String getWorkBookFilePath(String path) {
return path + File.separator + XL + File.separator + XML_WORKBOOK;
}
public static String getSharedStringFilePath(String path) {
return path + File.separator + XL + File.separator + XML_SHARED_STRING;
}
public static String getSheetFilePath(String path, int id) {
return path + File.separator + XL + File.separator + WORK_SHEETS + File.separator + SHEET + id
+ ".xml";
}
}

42
src/main/java/com/alibaba/excel/read/v07/XmlParserFactory.java

@ -1,42 +0,0 @@
package com.alibaba.excel.read.v07;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* @author jipengfei
*
*/
public class XmlParserFactory {
/**
* xml解析
* @param inputStream
* @param contentHandler
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public static void parse(InputStream inputStream, ContentHandler contentHandler)
throws ParserConfigurationException, SAXException, IOException {
InputSource sheetSource = new InputSource(inputStream);
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
//防止XML实体注注入
saxFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
saxFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
saxFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
SAXParser saxParser = saxFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(contentHandler);
xmlReader.parse(sheetSource);
}
}

1
src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java

@ -1,7 +1,6 @@
package com.alibaba.excel.support; package com.alibaba.excel.support;
/** /**
* 支持读写的数据格式
* *
* @author jipengfei * @author jipengfei
*/ */

62
src/main/java/com/alibaba/excel/util/EasyExcelTempFile.java

@ -1,62 +0,0 @@
package com.alibaba.excel.util;
import java.io.File;
/**
* 用于修复POI {@link org.apache.poi.util.DefaultTempFileCreationStrategy}在并发写创建临时目录抛出异常的BUG
*
* @author jipengfei
*/
public class EasyExcelTempFile {
private static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
private static final String POIFILES = "poifiles";
private static final String EASY_EXCEL_FILES = "easyexcel";
/**
* 在创建ExcelBuilder后尝试创建临时目录避免poi创建时候报错
*/
public static void createPOIFilesDirectory() {
String tmpDir = System.getProperty(JAVA_IO_TMPDIR);
if (tmpDir == null) {
throw new RuntimeException(
"Systems temporary directory not defined - set the -D" + JAVA_IO_TMPDIR + " jvm property!");
}
File directory = new File(tmpDir, POIFILES);
if (!directory.exists()) {
syncCreatePOIFilesDirectory(directory);
}
}
/**
* 获取环境变量的配置
* @return easyexcel临时目录
*/
public static String getEasyExcelTmpDir() {
String tmpDir = System.getProperty(JAVA_IO_TMPDIR);
if (tmpDir == null) {
throw new RuntimeException(
"Systems temporary directory not defined - set the -D" + JAVA_IO_TMPDIR + " jvm property!");
}
File directory = new File(tmpDir, EASY_EXCEL_FILES);
if (!directory.exists()) {
syncCreatePOIFilesDirectory(directory);
}
return tmpDir + File.separator + EASY_EXCEL_FILES;
}
/**
* 如果directory 不存在则创建
*
* @param directory
*/
private static synchronized void syncCreatePOIFilesDirectory(File directory) {
if (!directory.exists()) {
directory.mkdirs();
}
}
}

122
src/main/java/com/alibaba/excel/util/FileUtil.java

@ -1,122 +0,0 @@
package com.alibaba.excel.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.utils.IOUtils;
/**
* @author jipengfei
*/
public class FileUtil {
private static final int BUF = 4096;
public static boolean writeFile(File file, InputStream stream) throws FileNotFoundException {
OutputStream o = null;
try {
makeDirs(file.getAbsolutePath());
if (!file.exists()) {
file.createNewFile();
}
o = new FileOutputStream(file);
byte data[] = new byte[1024];
int length = -1;
while ((length = stream.read(data)) != -1) {
o.write(data, 0, length);
}
o.flush();
return true;
} catch (FileNotFoundException e) {
throw new RuntimeException("FileNotFoundException occurred. ", e);
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
try {
o.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static boolean makeDirs(String filePath) {
String folderName = getFolderName(filePath);
if (folderName == null || "".equals(folderName)) {
return false;
}
File folder = new File(folderName);
return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
}
public static String getFolderName(String filePath) {
if (filePath == null || "".equals(filePath)) {
return filePath;
}
int filePosi = filePath.lastIndexOf(File.separator);
return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
}
/**
* 文件解压
* @param path
* @param file
* @return
* @throws IOException
*/
public static boolean doUnZip(String path, File file) throws IOException {
ZipFile zipFile = new ZipFile(file, "utf-8");
Enumeration<ZipArchiveEntry> en = zipFile.getEntries();
ZipArchiveEntry ze;
while (en.hasMoreElements()) {
ze = en.nextElement();
if(ze.getName().contains("../")){
//防止目录穿越
throw new IllegalStateException("unsecurity zipfile!");
}
File f = new File(path, ze.getName());
if (ze.isDirectory()) {
f.mkdirs();
continue;
} else { f.getParentFile().mkdirs(); }
InputStream is = zipFile.getInputStream(ze);
OutputStream os = new FileOutputStream(f);
IOUtils.copy(is, os, BUF);
is.close();
os.close();
}
zipFile.close();
return true;
}
public static void deletefile(String delpath) {
File file = new File(delpath);
// 当且仅当此抽象路径名表示的文件存在且 是一个目录时,返回 true
if (!file.isDirectory()) {
file.delete();
} else if (file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File delfile = new File(delpath + File.separator + filelist[i]);
if (!delfile.isDirectory()) {
delfile.delete();
} else if (delfile.isDirectory()) {
deletefile(delpath + File.separator + filelist[i]);
}
}
file.delete();
}
}
}

145
src/main/java/com/alibaba/excel/util/IndexValueConverter.java

@ -1,71 +1,74 @@
//package com.alibaba.excel.util; package com.alibaba.excel.util;
//
//import java.util.ArrayList; import com.alibaba.excel.metadata.IndexValue;
//import java.util.List;
//import java.util.Stack; import java.util.ArrayList;
// import java.util.List;
//import com.alibaba.excel.metadata.IndexValue; import java.util.Stack;
//
///** /**
// * 去除空Cell * 去除空Cell
// * @author jipengfei * @author jipengfei
// */ * @date 2017/04/13
//public class IndexValueConverter { */
// public static List<String> converter(List<IndexValue> i_list) { public class IndexValueConverter {
// public static List<String> converter(List<IndexValue> i_list) {
// List<String> tem = new ArrayList<String>();
// List<String> tem = new ArrayList<String>();
// char[] start = {'@'};
// int j = 0; char[] start = {'@'};
// for (; j < i_list.size(); j++) { int j = 0;
// IndexValue currentIndexValue = i_list.get(j); for (; j < i_list.size(); j++) {
// char[] currentIndex = currentIndexValue.getV_index().replaceAll("[0-9]", "").toCharArray(); IndexValue currentIndexValue = i_list.get(j);
// if (j > 0) { char[] currentIndex = currentIndexValue.getV_index().replaceAll("[0-9]", "").toCharArray();
// start = i_list.get(j - 1).getV_index().replaceAll("[0-9]", "").toCharArray(); if (j > 0) {
// } start = i_list.get(j - 1).getV_index().replaceAll("[0-9]", "").toCharArray();
// int deep = subtraction26(currentIndex, start); }
// int k = 0; int deep = subtraction26(currentIndex, start);
// for (; k < deep - 1; k++) { int k = 0;
// tem.add(null); for (; k < deep - 1; k++) {
// } tem.add(null);
// tem.add(currentIndexValue.getV_value()); }
// } tem.add(currentIndexValue.getV_value());
// return tem; }
// } return tem;
// }
// private static int subtraction26(char[] currentIndex, char[] beforeIndex) {
// int result = 0; private static int subtraction26(char[] currentIndex, char[] beforeIndex) {
// int result = 0;
// Stack<Character> currentStack = new Stack<Character>();
// Stack<Character> beforeStack = new Stack<Character>(); Stack<Character> currentStack = new Stack<Character>();
// Stack<Character> berforStack = new Stack<Character>();
// for (int i = 0; i < currentIndex.length; i++) {
// currentStack.push(currentIndex[i]); for (int i = 0; i < currentIndex.length; i++) {
// } currentStack.push(currentIndex[i]);
// for (int i = 0; i < beforeIndex.length; i++) { }
// beforeStack.push(beforeIndex[i]); for (int i = 0; i < beforeIndex.length; i++) {
// } berforStack.push(beforeIndex[i]);
// int i = 0; }
// char beforeChar = '@'; int i = 0;
// while (!currentStack.isEmpty()) { char beforechar = '@';
// char currentChar = currentStack.pop(); while (!currentStack.isEmpty()) {
// if (!beforeStack.isEmpty()) { char currentChar = currentStack.pop();
// beforeChar = beforeStack.pop(); if (!berforStack.isEmpty()) {
// } beforechar = berforStack.pop();
// int n = currentChar - beforeChar; }
// if(n<0){ int n = currentChar - beforechar;
// n = n+26; if(n<0){
// if(!currentStack.isEmpty()){ n = n+26;
// char borrow = currentStack.pop(); if(!currentStack.isEmpty()){
// char newBorrow =(char)(borrow -1); char borrow = currentStack.pop();
// currentStack.push(newBorrow); char newBorrow =(char)(borrow -1);
// } currentStack.push(newBorrow);
// } }
// result += n * Math.pow(26, i); }
// i++;
// beforeChar='@';
// } result += n * Math.pow(26, i);
// i++;
// return result; beforechar='@';
// } }
//}
return result;
}
}

41
src/main/java/com/alibaba/excel/util/POITempFile.java

@ -0,0 +1,41 @@
package com.alibaba.excel.util;
import java.io.File;
/**
*
* @author jipengfei
* @date 2017/06/22
*/
public class POITempFile {
private static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
private static final String POIFILES = "poifiles";
/**
*/
public static void createPOIFilesDirectory() {
String tmpDir = System.getProperty(JAVA_IO_TMPDIR);
if (tmpDir == null) {
throw new RuntimeException(
"Systems temporary directory not defined - set the -D" + JAVA_IO_TMPDIR + " jvm property!");
}
File directory = new File(tmpDir, POIFILES);
if (!directory.exists()) {
syncCreatePOIFilesDirectory(directory);
}
}
/**
*
* @param directory
*/
private static synchronized void syncCreatePOIFilesDirectory(File directory) {
if (!directory.exists()) {
directory.mkdirs();
}
}
}

1
src/main/java/com/alibaba/excel/util/PositionUtils.java

@ -2,6 +2,7 @@ package com.alibaba.excel.util;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/08/27
*/ */
public class PositionUtils { public class PositionUtils {

77
src/main/java/com/alibaba/excel/util/TypeUtil.java

@ -1,5 +1,7 @@
package com.alibaba.excel.util; package com.alibaba.excel.util;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.text.ParseException; import java.text.ParseException;
@ -10,12 +12,9 @@ import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
/** /**
* 类型转换工具类
*
* @author jipengfei * @author jipengfei
* @date 2017/03/15
*/ */
public class TypeUtil { public class TypeUtil {
@ -26,16 +25,35 @@ public class TypeUtil {
DATE_FORMAT_LIST.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); DATE_FORMAT_LIST.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
} }
private static int getCountOfChar(String value, char c) {
int n = 0;
if (value == null) {
return 0;
}
char[] chars = value.toCharArray();
for (char cc : chars) {
if (cc == c) {
n++;
}
}
return n;
}
public static Object convert(String value, Field field, String format, boolean us) { public static Object convert(String value, Field field, String format, boolean us) {
if (isNotEmpty(value)) { if (isNotEmpty(value)) {
if (String.class.equals(field.getType())) { if (String.class.equals(field.getType())) {
return value; return TypeUtil.formatFloat(value);
} }
if (Integer.class.equals(field.getType()) || int.class.equals(field.getType())) { if (Integer.class.equals(field.getType()) || int.class.equals(field.getType())) {
return Integer.parseInt(value); return Integer.parseInt(value);
} }
if (Double.class.equals(field.getType()) || double.class.equals(field.getType())) { if (Double.class.equals(field.getType()) || double.class.equals(field.getType())) {
return Double.parseDouble(value); if (null != format && !"".equals(format)) {
int n = getCountOfChar(value, '0');
return Double.parseDouble(TypeUtil.formatFloat0(value, n));
} else {
return Double.parseDouble(TypeUtil.formatFloat(value));
}
} }
if (Boolean.class.equals(field.getType()) || boolean.class.equals(field.getType())) { if (Boolean.class.equals(field.getType()) || boolean.class.equals(field.getType())) {
String valueLower = value.toLowerCase(); String valueLower = value.toLowerCase();
@ -68,6 +86,27 @@ public class TypeUtil {
return null; return null;
} }
public static Boolean isNum(Field field) {
if (field == null) {
return false;
}
if (Integer.class.equals(field.getType()) || int.class.equals(field.getType())) {
return true;
}
if (Double.class.equals(field.getType()) || double.class.equals(field.getType())) {
return true;
}
if (Long.class.equals(field.getType()) || long.class.equals(field.getType())) {
return true;
}
if (BigDecimal.class.equals(field.getType())) {
return true;
}
return false;
}
public static String getDefaultDateString(Date date) { public static String getDefaultDateString(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return simpleDateFormat.format(date); return simpleDateFormat.format(date);
@ -102,7 +141,7 @@ public class TypeUtil {
} }
private static Boolean isNotEmpty(String value) { public static Boolean isNotEmpty(String value) {
if (value == null) { if (value == null) {
return false; return false;
} }
@ -114,7 +153,7 @@ public class TypeUtil {
} }
public static String formatFloat(String value) { public static String formatFloat(String value) {
if (value.contains(".")) { if (null != value && value.contains(".")) {
if (isNumeric(value)) { if (isNumeric(value)) {
try { try {
BigDecimal decimal = new BigDecimal(value); BigDecimal decimal = new BigDecimal(value);
@ -127,6 +166,20 @@ public class TypeUtil {
return value; return value;
} }
public static String formatFloat0(String value, int n) {
if (null != value && value.contains(".")) {
if (isNumeric(value)) {
try {
BigDecimal decimal = new BigDecimal(value);
BigDecimal setScale = decimal.setScale(n, BigDecimal.ROUND_HALF_DOWN);
return setScale.toPlainString();
} catch (Exception e) {
}
}
}
return value;
}
public static final Pattern pattern = Pattern.compile("[\\+\\-]?[\\d]+([\\.][\\d]*)?([Ee][+-]?[\\d]+)?$"); public static final Pattern pattern = Pattern.compile("[\\+\\-]?[\\d]+([\\.][\\d]*)?([Ee][+-]?[\\d]+)?$");
private static boolean isNumeric(String str) { private static boolean isNumeric(String str) {
@ -137,5 +190,13 @@ public class TypeUtil {
return true; return true;
} }
public static String formatDate(Date cellValue, String format) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.format(cellValue);
}
public static void main(String[] args) {
System.out.println(new Date().toString());
}
} }

45
src/main/java/com/alibaba/excel/write/ExcelBuilder.java

@ -1,54 +1,31 @@
package com.alibaba.excel.write; package com.alibaba.excel.write;
import java.io.OutputStream;
import java.util.List;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table; import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/** /**
* Excel构建器
* *
* @author jipengfei * @author jipengfei
*/ */
public interface ExcelBuilder { public interface ExcelBuilder {
/**
* 初始化Excel构造器
*
* @param out 文件输出流
* @param excelType 输出Excel类型建议使用07版xlsx性能内存消耗cpu使用都远低于03版xls
* @param needHead 是否需要将表头写入Excel
*/
void init(OutputStream out, ExcelTypeEnum excelType, boolean needHead);
/** void init(InputStream templateInputStream, OutputStream out, ExcelTypeEnum excelType, boolean needHead);
* 向Excel增加的内容
*
* @param data 数据格式 void addContent(List data, int startRow);
*/
void addContent(List data);
/**
* 向Excel增加的内容
*
* @param data 数据格式
* @param sheetParam 数据写到某个sheet中
*/
void addContent(List data, Sheet sheetParam); void addContent(List data, Sheet sheetParam);
/**
* 向Excel增加的内容
*
* @param data 数据格式
* @param sheetParam 数据写到某个sheet中
* @param table 写到某个sheet的某个Table
*/
void addContent(List data, Sheet sheetParam, Table table); void addContent(List data, Sheet sheetParam, Table table);
/**
* 关闭资源
*/
void finish(); void finish();
} }

89
src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java

@ -1,64 +1,81 @@
package com.alibaba.excel.write; package com.alibaba.excel.write;
import java.io.IOException; import com.alibaba.excel.context.GenerateContext;
import java.io.OutputStream; import com.alibaba.excel.context.GenerateContextImpl;
import java.util.List; import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.write.context.GenerateContext;
import com.alibaba.excel.write.context.GenerateContextImpl;
import com.alibaba.excel.metadata.ExcelColumnProperty; import com.alibaba.excel.metadata.ExcelColumnProperty;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table; import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.EasyExcelTempFile; import com.alibaba.excel.util.POITempFile;
import com.alibaba.excel.util.TypeUtil;
import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/05/27
*/ */
public class ExcelBuilderImpl implements ExcelBuilder { public class ExcelBuilderImpl implements ExcelBuilder {
private GenerateContext context; private GenerateContext context;
public void init(OutputStream out, ExcelTypeEnum excelType, boolean needHead) { @Override
public void init(InputStream templateInputStream, OutputStream out, ExcelTypeEnum excelType, boolean needHead) {
try {
//初始化时候创建临时缓存目录,用于规避POI在并发写bug //初始化时候创建临时缓存目录,用于规避POI在并发写bug
EasyExcelTempFile.createPOIFilesDirectory(); POITempFile.createPOIFilesDirectory();
context = new GenerateContextImpl(out, excelType, needHead); context = new GenerateContextImpl(templateInputStream, out, excelType, needHead);
} catch (Exception e) {
throw new RuntimeException(e);
}
} }
public void addContent(List data) { @Override
public void addContent(List data, int startRow) {
if (data != null && data.size() > 0) { if (data != null && data.size() > 0) {
int rowNum = context.getCurrentSheet().getLastRowNum(); int rowNum = context.getCurrentSheet().getLastRowNum();
if (rowNum == 0) { if (rowNum == 0) {
Row row = context.getCurrentSheet().getRow(0); Row row = context.getCurrentSheet().getRow(0);
if(row ==null) { if (row == null) {
if (context.getExcelHeadProperty() == null || !context.needHead()) { if (context.getExcelHeadProperty() == null || !context.needHead()) {
rowNum = -1; rowNum = -1;
} }
} }
} }
if (rowNum < startRow) {
rowNum = startRow;
}
for (int i = 0; i < data.size(); i++) { for (int i = 0; i < data.size(); i++) {
int n = i + rowNum + 1; int n = i + rowNum + 1;
addOneRowOfDataToExcel(data.get(i), n); addOneRowOfDataToExcel(data.get(i), n);
} }
} }
} }
@Override
public void addContent(List data, Sheet sheetParam) { public void addContent(List data, Sheet sheetParam) {
context.buildCurrentSheet(sheetParam); context.buildCurrentSheet(sheetParam);
addContent(data); addContent(data, sheetParam.getStartRow());
} }
@Override
public void addContent(List data, Sheet sheetParam, Table table) { public void addContent(List data, Sheet sheetParam, Table table) {
context.buildCurrentSheet(sheetParam); context.buildCurrentSheet(sheetParam);
context.buildTable(table); context.buildTable(table);
addContent(data); addContent(data, sheetParam.getStartRow());
} }
@Override
public void finish() { public void finish() {
try { try {
context.getWorkbook().write(context.getOutputStream()); context.getWorkbook().write(context.getOutputStream());
@ -67,12 +84,25 @@ public class ExcelBuilderImpl implements ExcelBuilder {
} }
} }
private void addOneRowOfDataToExcel(List<String> oneRowData, Row row) { private void addOneRowOfDataToExcel(List<Object> oneRowData, Row row) {
if (oneRowData != null && oneRowData.size() > 0) { if (oneRowData != null && oneRowData.size() > 0) {
for (int i = 0; i < oneRowData.size(); i++) { for (int i = 0; i < oneRowData.size(); i++) {
Cell cell = row.createCell(i); Cell cell = row.createCell(i);
cell.setCellStyle(context.getCurrentContentStyle()); cell.setCellStyle(context.getCurrentContentStyle());
cell.setCellValue(oneRowData.get(i)); Object cellValue = oneRowData.get(i);
if (cellValue != null) {
if (cellValue instanceof String) {
cell.setCellValue((String)cellValue);
} else if (cellValue instanceof Integer) {
cell.setCellValue(Double.parseDouble(cellValue.toString()));
} else if (cellValue instanceof Double) {
cell.setCellValue((Double)cellValue);
} else if (cellValue instanceof Short) {
cell.setCellValue((Double.parseDouble(cellValue.toString())));
}
} else {
cell.setCellValue((String)null);
}
} }
} }
} }
@ -81,26 +111,43 @@ public class ExcelBuilderImpl implements ExcelBuilder {
int i = 0; int i = 0;
for (ExcelColumnProperty excelHeadProperty : context.getExcelHeadProperty().getColumnPropertyList()) { for (ExcelColumnProperty excelHeadProperty : context.getExcelHeadProperty().getColumnPropertyList()) {
Cell cell = row.createCell(i); Cell cell = row.createCell(i);
BaseRowModel baseRowModel = (BaseRowModel)oneRowData;
if (baseRowModel.getStyle(i) != null) {
cell.setCellStyle(baseRowModel.getStyle(i));
} else {
cell.setCellStyle(context.getCurrentContentStyle()); cell.setCellStyle(context.getCurrentContentStyle());
}
String cellValue = null; String cellValue = null;
try { try {
cellValue = BeanUtils.getProperty(oneRowData, excelHeadProperty.getField().getName()); Object value = BeanUtilsBean.getInstance().getPropertyUtils().getNestedProperty(oneRowData,
excelHeadProperty.getField().getName());
if (value instanceof Date) {
cellValue = TypeUtil.formatDate((Date)value, excelHeadProperty.getFormat());
} else {
cellValue = BeanUtilsBean.getInstance().getConvertUtils().convert(value);
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
if (cellValue != null) { if (TypeUtil.isNotEmpty(cellValue)) {
if (TypeUtil.isNum(excelHeadProperty.getField())) {
cell.setCellValue(Double.parseDouble(cellValue));
} else {
cell.setCellValue(cellValue); cell.setCellValue(cellValue);
}
} else { } else {
cell.setCellValue(""); cell.setCellValue("");
} }
i++; i++;
} }
} }
private void addOneRowOfDataToExcel(Object oneRowData, int n) { private void addOneRowOfDataToExcel(Object oneRowData, int n) {
Row row = context.getCurrentSheet().createRow(n); Row row = context.getCurrentSheet().createRow(n);
if (oneRowData instanceof List) { if (oneRowData instanceof List) {
addOneRowOfDataToExcel((List<String>)oneRowData, row); addOneRowOfDataToExcel((List)oneRowData, row);
} else { } else {
addOneRowOfDataToExcel(oneRowData, row); addOneRowOfDataToExcel(oneRowData, row);
} }

16
src/test/java/function/listener/ExcelListener.java

@ -1,18 +1,14 @@
package function.listener; package function.listener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/** /**
* Created by jipengfei on 17/3/14. * Created by jipengfei on 17/3/14.
* 解析监听器 * 解析监听器

9
src/test/java/function/read/ExelAllDataTypeTest.java

@ -1,17 +1,16 @@
package function.read; package function.read;
import java.io.IOException;
import java.io.InputStream;
import com.alibaba.excel.ExcelReader; import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import function.listener.ExcelListener; import function.listener.ExcelListener;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/** /**
* Created by jipengfei on 17/3/15. * Created by jipengfei on 17/3/15.
* *

9
src/test/java/function/read/NumTest3.java

@ -1,17 +1,16 @@
package function.read; package function.read;
import java.io.IOException;
import java.io.InputStream;
import com.alibaba.excel.ExcelReader; import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import function.listener.ExcelListener; import function.listener.ExcelListener;
import function.model.TestModel3; import function.model.TestModel3;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/** /**
* Created by jipengfei on 17/3/19. * Created by jipengfei on 17/3/19.
* *

13
src/test/java/function/read/ReadSheets.java

@ -1,19 +1,18 @@
package function.read; package function.read;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import com.alibaba.excel.ExcelReader; import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import function.listener.ExcelListener; import function.listener.ExcelListener;
import org.junit.Test; import org.junit.Test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/** /**
* Created by jipengfei on 17/3/22. * Created by jipengfei on 17/3/22.
* *

9
src/test/java/function/read/XLSX2007FunctionTest.java

@ -1,18 +1,17 @@
package function.read; package function.read;
import java.io.IOException;
import java.io.InputStream;
import com.alibaba.excel.ExcelReader; import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import function.listener.ExcelListener; import function.listener.ExcelListener;
import function.model.OneRowHeadExcelModel; import function.model.OneRowHeadExcelModel;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/** /**
* Created by jipengfei on 17/2/18. * Created by jipengfei on 17/2/18.
*/ */

15
src/test/java/function/write/ExcelWriteTest1.java

@ -1,19 +1,10 @@
package function.write; package function.write;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.ExcelReader; import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import function.listener.ExcelListener; import function.listener.ExcelListener;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
@ -21,6 +12,10 @@ import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.junit.Test; import org.junit.Test;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/08/15 * @date 2017/08/15

48
src/test/java/javamodel/IdentificationExcel.java

@ -0,0 +1,48 @@
package javamodel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
public class IdentificationExcel extends BaseRowModel{
@ExcelProperty(index=0)
private String materialnumber;
@ExcelProperty(index=17)
private String unit;
@ExcelProperty(index=42)
private String specproc;
public String getMaterialnumber() {
return materialnumber;
}
public void setMaterialnumber(String materialnumber) {
this.materialnumber = materialnumber;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getSpecproc() {
return specproc;
}
public void setSpecproc(String specproc) {
this.specproc = specproc;
}
@Override
public String toString() {
return "IdentificationExcel{" +
"materialnumber='" + materialnumber + '\'' +
", unit='" + unit + '\'' +
", specproc='" + specproc + '\'' +
'}';
}
}

9
src/test/java/read/v03/XLS2003FunctionTest.java

@ -1,18 +1,17 @@
package read.v03; package read.v03;
import java.io.IOException;
import java.io.InputStream;
import com.alibaba.excel.ExcelReader; import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import function.listener.ExcelListener; import function.listener.ExcelListener;
import function.model.LoanInfo; import function.model.LoanInfo;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/** /**
* Created by jipengfei on 17/2/19. * Created by jipengfei on 17/2/19.
*/ */

11
src/test/java/read/v07/Read2007MeanWhileWrite.java

@ -1,21 +1,20 @@
package read.v07; package read.v07;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import com.alibaba.excel.ExcelReader; import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import javamodel.ExcelRowJavaModel; import javamodel.ExcelRowJavaModel;
import javamodel.ExcelRowJavaModel1; import javamodel.ExcelRowJavaModel1;
import org.junit.Test; import org.junit.Test;
import read.v07.listener.Excel2007NoJavaModelAnalysisListener; import read.v07.listener.Excel2007NoJavaModelAnalysisListener;
import read.v07.listener.Excel2007WithJavaModelAnalysisListener; import read.v07.listener.Excel2007WithJavaModelAnalysisListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/08/27 * @date 2017/08/27

56
src/test/java/read/v07/Read2007Xlsx.java

@ -1,21 +1,20 @@
package read.v07; package read.v07;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.alibaba.excel.ExcelReader; import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.support.ExcelTypeEnum;
import javamodel.ExcelRowJavaModel; import javamodel.ExcelRowJavaModel;
import javamodel.ExcelRowJavaModel1; import javamodel.ExcelRowJavaModel1;
import javamodel.IdentificationExcel;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/08/27 * @date 2017/08/27
@ -24,7 +23,9 @@ public class Read2007Xlsx {
//创建没有自定义模型,没有sheet的解析器,默认解析所有sheet解析结果以List<String>的方式通知监听者 //创建没有自定义模型,没有sheet的解析器,默认解析所有sheet解析结果以List<String>的方式通知监听者
@Test @Test
public void noModel() { public void noModel() {
InputStream inputStream = getInputStream("1.xlsx"); InputStream inputStream = getInputStream("需要分批关闭客户名单 2018.8.24.xlsx");
final List<List<String>> ll = new ArrayList<List<String>>();
try { try {
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null,
new AnalysisEventListener<List<String>>() { new AnalysisEventListener<List<String>>() {
@ -34,6 +35,7 @@ public class Read2007Xlsx {
"当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum() "当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum()
+ " data:" + object); + " data:" + object);
ll.add(object);
} }
@Override @Override
@ -42,6 +44,21 @@ public class Read2007Xlsx {
}); });
reader.read(); reader.read();
String aa= "";
int i= 0;
for (List<String> strings:ll) {
i++;
aa = aa+","+ strings.get(1)+"";
if(i==25000){
System.out.println(aa);
aa="";
i=0;
}
}
System.out.println(aa);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -56,12 +73,12 @@ public class Read2007Xlsx {
@Test @Test
public void withJavaModel() { public void withJavaModel() {
InputStream inputStream = getInputStream("2007WithModel.xlsx"); InputStream inputStream = getInputStream("2-拆分标识数据库.xlsx");
try { try {
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null,
new AnalysisEventListener<ExcelRowJavaModel>() { new AnalysisEventListener<IdentificationExcel>() {
@Override @Override
public void invoke(ExcelRowJavaModel object, AnalysisContext context) { public void invoke(IdentificationExcel object, AnalysisContext context) {
System.out.println( System.out.println(
"当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum() "当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum()
+ " data:" + object); + " data:" + object);
@ -73,7 +90,7 @@ public class Read2007Xlsx {
} }
}); });
reader.read(new Sheet(1, 2, ExcelRowJavaModel.class)); reader.read(new Sheet(1, 1, IdentificationExcel.class));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -375,14 +392,7 @@ public class Read2007Xlsx {
} }
public static void main(String[] args) {
List<String> mm = new ArrayList<String>();
mm.add(null);
mm.add(null);
mm.add(null);
mm.add(null);
mm.removeAll(Collections.singleton(null));
System.out.println(mm);
}
} }

10
src/test/java/read/v07/listener/Excel2007NoJavaModelAnalysisListener.java

@ -1,12 +1,12 @@
package read.v07.listener; package read.v07.listener;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventListener;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/08/27 * @date 2017/08/27
@ -27,7 +27,7 @@ public class Excel2007NoJavaModelAnalysisListener extends AnalysisEventListener
List<List<String>> ll = new ArrayList<List<String>>(); List<List<String>> ll = new ArrayList<List<String>>();
ll.add((List<String>)object); ll.add((List<String>)object);
System.out.println(object); System.out.println(object);
excelWriter.write0(ll,context.getCurrentSheet()); excelWriter.write0(ll, context.getCurrentSheet());
} }
public void doAfterAllAnalysed(AnalysisContext context) { public void doAfterAllAnalysed(AnalysisContext context) {

11
src/test/java/read/v07/listener/Excel2007WithJavaModelAnalysisListener.java

@ -1,16 +1,15 @@
package read.v07.listener; package read.v07.listener;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel; import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import javamodel.ExcelRowJavaModel; import javamodel.ExcelRowJavaModel;
import java.util.ArrayList;
import java.util.List;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/08/27 * @date 2017/08/27

BIN
src/test/resources/1.xlsx

Binary file not shown.
Loading…
Cancel
Save