Browse Source

升级新版本,修复bug,提供编辑工具,提升模型转换性能

bugfix
jipengfei.jpf 6 years ago
parent
commit
f4b324556f
  1. 14
      pom.xml
  2. 100
      src/main/java/com/alibaba/excel/EasyExcelFactory.java
  3. 85
      src/main/java/com/alibaba/excel/ExcelReader.java
  4. 117
      src/main/java/com/alibaba/excel/ExcelWriter.java
  5. 16
      src/main/java/com/alibaba/excel/analysis/BaseSaxAnalyser.java
  6. 25
      src/main/java/com/alibaba/excel/analysis/ExcelAnalyser.java
  7. 51
      src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java
  8. 42
      src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java
  9. 18
      src/main/java/com/alibaba/excel/analysis/v07/XlsxRowHandler.java
  10. 7
      src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java
  11. 7
      src/main/java/com/alibaba/excel/annotation/ExcelColumnNum.java
  12. 6
      src/main/java/com/alibaba/excel/annotation/ExcelProperty.java
  13. 1
      src/main/java/com/alibaba/excel/annotation/FieldType.java
  14. 1
      src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java
  15. 35
      src/main/java/com/alibaba/excel/context/AnalysisContext.java
  16. 26
      src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java
  17. 66
      src/main/java/com/alibaba/excel/context/GenerateContext.java
  18. 246
      src/main/java/com/alibaba/excel/context/GenerateContextImpl.java
  19. 278
      src/main/java/com/alibaba/excel/context/WriteContext.java
  20. 14
      src/main/java/com/alibaba/excel/event/AnalysisEventRegisterCenter.java
  21. 18
      src/main/java/com/alibaba/excel/event/OneRowAnalysisFinishEvent.java
  22. 1
      src/main/java/com/alibaba/excel/exception/ExcelGenerateException.java
  23. 6
      src/main/java/com/alibaba/excel/metadata/BaseRowModel.java
  24. 1
      src/main/java/com/alibaba/excel/metadata/CellRange.java
  25. 1
      src/main/java/com/alibaba/excel/metadata/ExcelColumnProperty.java
  26. 110
      src/main/java/com/alibaba/excel/metadata/ExcelHeadProperty.java
  27. 1
      src/main/java/com/alibaba/excel/metadata/Font.java
  28. 3
      src/main/java/com/alibaba/excel/metadata/Sheet.java
  29. 7
      src/main/java/com/alibaba/excel/metadata/Table.java
  30. 1
      src/main/java/com/alibaba/excel/metadata/TableStyle.java
  31. 50
      src/main/java/com/alibaba/excel/modelbuild/ModelBuildEventListener.java
  32. 2
      src/main/java/com/alibaba/excel/parameter/AnalysisParam.java
  33. 5
      src/main/java/com/alibaba/excel/parameter/ExcelWriteParam.java
  34. 4
      src/main/java/com/alibaba/excel/parameter/GenerateParam.java
  35. 19
      src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java
  36. 340
      src/main/java/com/alibaba/excel/util/CollectionUtils.java
  37. 5
      src/main/java/com/alibaba/excel/util/IndexValueConverter.java
  38. 945
      src/main/java/com/alibaba/excel/util/ObjectUtils.java
  39. 1
      src/main/java/com/alibaba/excel/util/POITempFile.java
  40. 1
      src/main/java/com/alibaba/excel/util/PositionUtils.java
  41. 10
      src/main/java/com/alibaba/excel/util/RowUtil.java
  42. 1221
      src/main/java/com/alibaba/excel/util/StringUtils.java
  43. 68
      src/main/java/com/alibaba/excel/util/StyleUtil.java
  44. 91
      src/main/java/com/alibaba/excel/util/TypeUtil.java
  45. 75
      src/main/java/com/alibaba/excel/util/WorkBookUtil.java
  46. 42
      src/main/java/com/alibaba/excel/write/ExcelBuilder.java
  47. 141
      src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java
  48. 187
      src/test/java/com/alibaba/easyexcel/test/ReadTest.java
  49. 155
      src/test/java/com/alibaba/easyexcel/test/WriteTest.java
  50. 34
      src/test/java/com/alibaba/easyexcel/test/listen/ExcelListener.java
  51. 136
      src/test/java/com/alibaba/easyexcel/test/model/JavaModel.java
  52. 71
      src/test/java/com/alibaba/easyexcel/test/model/JavaModel1.java
  53. 136
      src/test/java/com/alibaba/easyexcel/test/model/JavaModel2.java
  54. 93
      src/test/java/com/alibaba/easyexcel/test/util/DataUtil.java
  55. 10
      src/test/java/com/alibaba/easyexcel/test/util/FileUtil.java
  56. 93
      src/test/java/function/listener/ExcelListener.java
  57. 87
      src/test/java/function/model/ExcelPropertyIndexModel.java
  58. 132
      src/test/java/function/model/LoanInfo.java
  59. 44
      src/test/java/function/model/NoAnnModel.java
  60. 270
      src/test/java/function/model/OneRowHeadExcelModel.java
  61. 354
      src/test/java/function/model/TestModel3.java
  62. 46
      src/test/java/function/read/ExelAllDataTypeTest.java
  63. 45
      src/test/java/function/read/NumTest3.java
  64. 82
      src/test/java/function/read/ReadSheets.java
  65. 139
      src/test/java/function/read/XLSX2007FunctionTest.java
  66. 117
      src/test/java/function/write/ExcelWriteIndexTest.java
  67. 246
      src/test/java/function/write/ExcelWriteTest.java
  68. 103
      src/test/java/function/write/ExcelWriteTest1.java
  69. 128
      src/test/java/javamodel/ExcelRowJavaModel.java
  70. 45
      src/test/java/javamodel/ExcelRowJavaModel1.java
  71. 48
      src/test/java/javamodel/IdentificationExcel.java
  72. 87
      src/test/java/read/v03/XLS2003FunctionTest.java
  73. 91
      src/test/java/read/v07/Read2007MeanWhileWrite.java
  74. 398
      src/test/java/read/v07/Read2007Xlsx.java
  75. 37
      src/test/java/read/v07/listener/Excel2007NoJavaModelAnalysisListener.java
  76. 40
      src/test/java/read/v07/listener/Excel2007WithJavaModelAnalysisListener.java
  77. BIN
      src/test/resources/111.xlsx
  78. BIN
      src/test/resources/1111.xlsx
  79. BIN
      src/test/resources/2003.xls
  80. BIN
      src/test/resources/2007.xlsx
  81. BIN
      src/test/resources/2007NoModelBigFile.xlsx
  82. BIN
      src/test/resources/2007NoModelMultipleSheet.xlsx
  83. BIN
      src/test/resources/2007WithModel.xlsx
  84. BIN
      src/test/resources/2007WithModelMultipleSheet.xlsx
  85. BIN
      src/test/resources/2007_1.xlsx
  86. BIN
      src/test/resources/77.xlsx
  87. BIN
      src/test/resources/sss.xlsx
  88. BIN
      src/test/resources/temp.xlsx

14
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.1.1</version> <version>1.1.2-beat1</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>easyexcel</name> <name>easyexcel</name>
@ -67,9 +67,9 @@
<version>3.17</version> <version>3.17</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-beanutils</groupId> <groupId>cglib</groupId>
<artifactId>commons-beanutils</artifactId> <artifactId>cglib</artifactId>
<version>1.9.2</version> <version>3.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
@ -77,11 +77,7 @@
<version>4.12</version> <version>4.12</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.14</version>
</dependency>
</dependencies> </dependencies>
<distributionManagement> <distributionManagement>
<snapshotRepository> <snapshotRepository>

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

@ -0,0 +1,100 @@
package com.alibaba.excel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Reader and writer factory class
*
* @author jipengfei
*/
public class EasyExcelFactory {
/**
* Quickly read small filesno more than 10,000 lines.
*
* @param in the POI filesystem that contains the Workbook stream.
* @param sheet read sheet.
* @return analysis result.
*/
public static List<Object> read(InputStream in, Sheet sheet) {
final List<Object> rows = new ArrayList<Object>();
new ExcelReader(in, null, new AnalysisEventListener() {
@Override
public void invoke(Object object, AnalysisContext context) {
rows.add(object);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
}, false).read(sheet);
return rows;
}
/**
* Parsing large file
*
* @param in the POI filesystem that contains the Workbook stream.
* @param sheet read sheet.
* @param listener Callback method after each row is parsed.
*/
public static void readBySax(InputStream in, Sheet sheet, AnalysisEventListener listener) {
new ExcelReader(in, null, listener).read(sheet);
}
/**
* Get ExcelReader.
*
* @param in the POI filesystem that contains the Workbook stream.
* @param listener Callback method after each row is parsed.
* @return ExcelReader.
*/
public static ExcelReader getReader(InputStream in, AnalysisEventListener listener) {
return new ExcelReader(in, null, listener);
}
/**
* Get ExcelWriter
*
* @param outputStream the java OutputStream you wish to write the data to.
* @return new ExcelWriter.
*/
public static ExcelWriter getWriter(OutputStream outputStream) {
return new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, true);
}
/**
* Get ExcelWriter
*
* @param outputStream the java OutputStream you wish to write the data to.
* @param typeEnum 03 or 07
* @param needHead Do you need to write the header to the file?
* @return new ExcelWriter
*/
public static ExcelWriter getWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) {
return new ExcelWriter(outputStream, typeEnum, needHead);
}
/**
* Get ExcelWriter with a template file
*
* @param temp Append data after a POI file , Can be nullthe template POI filesystem that contains the
* Workbook stream)
* @param outputStream the java OutputStream you wish to write the data to
* @param typeEnum 03 or 07
* @return new ExcelWriter
*/
public static ExcelWriter getWriterWithTemp(InputStream temp, OutputStream outputStream, ExcelTypeEnum typeEnum,
boolean needHead) {
return new ExcelWriter(temp, outputStream, typeEnum, needHead);
}
}

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

@ -13,23 +13,24 @@ import java.io.InputStream;
import java.util.List; import java.util.List;
/** /**
* Excel thread unsafe * Excel readers are all read in event mode.
* *
* @author jipengfei * @author jipengfei
*/ */
public class ExcelReader { public class ExcelReader {
/** /**
* analyser * Analyser
*/ */
private ExcelAnalyser analyser = new ExcelAnalyserImpl(); private ExcelAnalyser analyser ;
/** /**
* @param in * Create new reader
* @param excelTypeEnum 0307 *
* @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) * @param in the POI filesystem that contains the Workbook stream
* }AnalysisContext * @param excelTypeEnum 03 or 07
* @param eventListener * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener Callback method after each row is parsed.
*/ */
@Deprecated @Deprecated
public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent, public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent,
@ -38,10 +39,11 @@ public class ExcelReader {
} }
/** /**
* @param in * Create new reader
* @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) *
* }AnalysisContext * @param in the POI filesystem that contains the Workbook stream
* @param eventListener * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param eventListener Callback method after each row is parsed
*/ */
public ExcelReader(InputStream in, Object customContent, public ExcelReader(InputStream in, Object customContent,
AnalysisEventListener eventListener) { AnalysisEventListener eventListener) {
@ -49,8 +51,10 @@ public class ExcelReader {
} }
/** /**
* @param param * Create new reader
* @param eventListener *
* @param param old param Deprecated
* @param eventListener Callback method after each row is parsed.
*/ */
@Deprecated @Deprecated
public ExcelReader(AnalysisParam param, AnalysisEventListener eventListener) { public ExcelReader(AnalysisParam param, AnalysisEventListener eventListener) {
@ -58,75 +62,88 @@ public class ExcelReader {
} }
/** /**
* @param in * Create new reader
* @param excelTypeEnum 03 07 *
* @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) * @param in the POI filesystem that contains the Workbook stream
* }AnalysisContext * @param excelTypeEnum 03 or 07
* @param eventListener * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* @param trim * @param eventListener Callback method after each row is parsed.
* @param trim The content of the form is empty and needs to be empty. The purpose is to be fault-tolerant,
* because there are often table contents with spaces that can not be converted into custom
* types. For example: '1234 ' contain a space cannot be converted to int.
*/ */
@Deprecated @Deprecated
public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent, public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent,
AnalysisEventListener eventListener, boolean trim) { AnalysisEventListener eventListener, boolean trim) {
validateParam(in, excelTypeEnum, eventListener); validateParam(in, eventListener);
analyser.init(in, excelTypeEnum, customContent, eventListener, trim); analyser = new ExcelAnalyserImpl(in, excelTypeEnum, customContent, eventListener, trim);
} }
/** /**
* Create new reader
*
* @param in * @param in
* @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext
* }AnalysisContext
* @param eventListener * @param eventListener
* @param trim * @param trim The content of the form is empty and needs to be empty. The purpose is to be fault-tolerant,
* because there are often table contents with spaces that can not be converted into custom
* types. For example: '1234 ' contain a space cannot be converted to int.
*/ */
public ExcelReader(InputStream in, Object customContent, public ExcelReader(InputStream in, Object customContent,
AnalysisEventListener eventListener, boolean trim) { AnalysisEventListener eventListener, boolean trim) {
ExcelTypeEnum excelTypeEnum = ExcelTypeEnum.valueOf(in); ExcelTypeEnum excelTypeEnum = ExcelTypeEnum.valueOf(in);
validateParam(in, excelTypeEnum, eventListener); validateParam(in, eventListener);
analyser.init(in, excelTypeEnum, customContent, eventListener, trim); analyser =new ExcelAnalyserImpl(in, excelTypeEnum, customContent, eventListener, trim);
} }
/** /**
* Parse all sheet content by default
*/ */
public void read() { public void read() {
analyser.analysis(); analyser.analysis();
} }
/** /**
* Parse the specified sheetSheetNo start from 1
* *
* @param sheet * @param sheet Read sheet
*/ */
public void read(Sheet sheet) { public void read(Sheet sheet) {
analyser.analysis(sheet); analyser.analysis(sheet);
} }
/**
* Parse the specified sheet
*
* @param sheet Read sheet
* @param clazz object parsed into each row of data
*/
@Deprecated @Deprecated
public void read(Sheet sheet,Class<? extends BaseRowModel> clazz){ public void read(Sheet sheet, Class<? extends BaseRowModel> clazz) {
sheet.setClazz(clazz); sheet.setClazz(clazz);
analyser.analysis(sheet); analyser.analysis(sheet);
} }
/** /**
* Parse the workBook get all sheets
* *
* @return * @return workBook all sheets
*/ */
public List<Sheet> getSheets() { public List<Sheet> getSheets() {
return analyser.getSheets(); return analyser.getSheets();
} }
/** /**
* validate param
* *
* @param in * @param in
* @param excelTypeEnum
* @param eventListener * @param eventListener
*/ */
private void validateParam(InputStream in, ExcelTypeEnum excelTypeEnum, AnalysisEventListener eventListener) { private void validateParam(InputStream in, AnalysisEventListener eventListener) {
if (eventListener == null) { if (eventListener == null) {
throw new IllegalArgumentException("AnalysisEventListener can not null"); throw new IllegalArgumentException("AnalysisEventListener can not null");
} else if (in == null) { } else if (in == null) {
throw new IllegalArgumentException("InputStream can not null"); throw new IllegalArgumentException("InputStream can not null");
} else if (excelTypeEnum == null) {
throw new IllegalArgumentException("excelTypeEnum can not null");
} }
} }
} }

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

@ -13,7 +13,12 @@ import java.io.OutputStream;
import java.util.List; import java.util.List;
/** /**
* * Excel Writer This tool is used to write data out to Excel via POI.
* This object can perform the following two functions.
* <pre>
* 1. Create a new empty Excel workbook, write the data to the stream after the data is filled.
* 2. Edit existing Excel, write the original Excel file, or write it to other places.{@link ExcelWriter(InputStream , OutputStream , ExcelTypeEnum , boolean )}
* </pre>
* @author jipengfei * @author jipengfei
*/ */
public class ExcelWriter { public class ExcelWriter {
@ -21,66 +26,65 @@ public class ExcelWriter {
private ExcelBuilder excelBuilder; private ExcelBuilder excelBuilder;
/** /**
* * Create new writer
* * @param outputStream the java OutputStream you wish to write the data to
* @param typeEnum 03 or 07
*/ */
public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum) { public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum) {
this(outputStream, typeEnum, true); this(outputStream, typeEnum, true);
} }
@Deprecated
private Class<? extends BaseRowModel> objectClass; private Class<? extends BaseRowModel> objectClass;
private String sheetName; /**
* @param generateParam
* @since easyexcel 0.0.1 Use {@link new ExcelWrite(int, int, int)
*/
@Deprecated
public ExcelWriter(GenerateParam generateParam) { public ExcelWriter(GenerateParam generateParam) {
this(generateParam.getOutputStream(), generateParam.getType(), true); this(generateParam.getOutputStream(), generateParam.getType(), true);
this.objectClass = generateParam.getClazz(); this.objectClass = generateParam.getClazz();
this.sheetName = generateParam.getSheetName();
} }
/** /**
* *
* * Create new writer
* @param outputStream * @param outputStream the java OutputStream you wish to write the data to
* @param typeEnum * @param typeEnum 03 or 07
* @param needHead Do you need to write the header to the file?
*/ */
public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) {
excelBuilder = new ExcelBuilderImpl(); excelBuilder = new ExcelBuilderImpl(null, outputStream, typeEnum, needHead);
excelBuilder.init(null, outputStream, typeEnum, needHead);
} }
/** /**
* * Create new writer
* @param templateInputStream * @param templateInputStream Append data after a POI file ,Can be nullthe template POI filesystem that contains the Workbook stream)
* @param outputStream * @param outputStream the java OutputStream you wish to write the data to
* @param typeEnum * @param typeEnum 03 or 07
*/ */
public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum,Boolean needHead) {
excelBuilder = new ExcelBuilderImpl(); excelBuilder = new ExcelBuilderImpl(templateInputStream,outputStream, typeEnum, needHead);
excelBuilder.init(templateInputStream,outputStream, typeEnum, needHead);
} }
/** /**
* * Write data(List<? extends BaseRowModel>) to a sheet
* @param data * @param data Data to be written
* @param sheet * @param sheet Write to this sheet
* @return this * @return this current writer
*/ */
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;
//}
/**
* Write data to a sheet
* @param data Data to be written
* @return this current writer
*/
@Deprecated @Deprecated
public ExcelWriter write(List data) { public ExcelWriter write(List data) {
if (objectClass != null) { if (objectClass != null) {
@ -93,9 +97,9 @@ public class ExcelWriter {
/** /**
* *
* * Write data(List<List<String>>) to a sheet
* @param data * @param data Data to be written
* @param sheet * @param sheet Write to this sheet
* @return this * @return this
*/ */
public ExcelWriter write1(List<List<Object>> data, Sheet sheet) { public ExcelWriter write1(List<List<Object>> data, Sheet sheet) {
@ -104,9 +108,9 @@ public class ExcelWriter {
} }
/** /**
* * Write data(List<List<String>>) to a sheet
* @param data * @param data Data to be written
* @param sheet * @param sheet Write to this sheet
* @return this * @return this
*/ */
public ExcelWriter write0(List<List<String>> data, Sheet sheet) { public ExcelWriter write0(List<List<String>> data, Sheet sheet) {
@ -114,25 +118,58 @@ public class ExcelWriter {
return this; return this;
} }
/**
* Write data(List<? extends BaseRowModel>) to a sheet
* @param data Data to be written
* @param sheet Write to this sheet
* @param table Write to this table
* @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;
} }
/**
* Write data(List<List<String>>) to a sheet
* @param data Data to be written
* @param sheet Write to this sheet
* @param table Write to this 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;
} }
/**
* Merge CellsIndexes are zero-based.
*
* @param firstRow Index of first row
* @param lastRow Index of last row (inclusive), must be equal to or larger than {@code firstRow}
* @param firstCol Index of first column
* @param lastCol Index of last column (inclusive), must be equal to or larger than {@code firstCol}
*/
public ExcelWriter merge(int firstRow, int lastRow, int firstCol, int lastCol){
excelBuilder.merge(firstRow,lastRow,firstCol,lastCol);
return this;
}
/**
* Write data(List<List<Object>>) to a sheet
* @param data Data to be written
* @param sheet Write to this sheet
* @param table Write to this table
* @return
*/
public ExcelWriter write1(List<List<Object>> data, Sheet sheet, Table table) { public ExcelWriter write1(List<List<Object>> data, Sheet sheet, Table table) {
excelBuilder.addContent(data, sheet, table); excelBuilder.addContent(data, sheet, table);
return this; return this;
} }
/**
* Close IO
*/
public void finish() { public void finish() {
excelBuilder.finish(); excelBuilder.finish();
} }

16
src/main/java/com/alibaba/excel/analysis/BaseSaxAnalyser.java

@ -5,17 +5,14 @@ import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.event.AnalysisEventRegisterCenter; import com.alibaba.excel.event.AnalysisEventRegisterCenter;
import com.alibaba.excel.event.OneRowAnalysisFinishEvent; import com.alibaba.excel.event.OneRowAnalysisFinishEvent;
import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.TypeUtil; import com.alibaba.excel.util.TypeUtil;
import java.io.InputStream;
import java.util.ArrayList; 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;
/** /**
*
* @author jipengfei * @author jipengfei
*/ */
public abstract class BaseSaxAnalyser implements AnalysisEventRegisterCenter, ExcelAnalyser { public abstract class BaseSaxAnalyser implements AnalysisEventRegisterCenter, ExcelAnalyser {
@ -25,46 +22,51 @@ 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>();
/** /**
* execute method
*/ */
protected abstract void execute(); protected abstract void execute();
public void init(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Object custom,
AnalysisEventListener eventListener, boolean trim) {
}
@Override
public void appendLister(String name, AnalysisEventListener listener) { public void appendLister(String name, AnalysisEventListener listener) {
if (!listeners.containsKey(name)) { if (!listeners.containsKey(name)) {
listeners.put(name, listener); listeners.put(name, listener);
} }
} }
@Override
public void analysis(Sheet sheetParam) { public void analysis(Sheet sheetParam) {
execute(); execute();
} }
@Override
public void analysis() { public void analysis() {
execute(); execute();
} }
/** /**
*/ */
@Override
public void cleanAllListeners() { public void cleanAllListeners() {
listeners = new LinkedHashMap<String, AnalysisEventListener>(); listeners = new LinkedHashMap<String, AnalysisEventListener>();
} }
@Override
public void notifyListeners(OneRowAnalysisFinishEvent event) { public void notifyListeners(OneRowAnalysisFinishEvent event) {
analysisContext.setCurrentRowAnalysisResult(event.getData()); analysisContext.setCurrentRowAnalysisResult(event.getData());
/** Parsing header content **/
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,
(List<String>)analysisContext.getCurrentRowAnalysisResult()); (List<String>)analysisContext.getCurrentRowAnalysisResult());
} }
} else { } else {
/** Parsing Analyze the body content **/
analysisContext.setCurrentRowAnalysisResult(event.getData()); analysisContext.setCurrentRowAnalysisResult(event.getData());
if (listeners.size() == 1) { if (listeners.size() == 1) {
analysisContext.setCurrentRowAnalysisResult(converter((List<String>)event.getData())); analysisContext.setCurrentRowAnalysisResult(converter((List<String>)event.getData()));
} }
/** notify all event listeners **/
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);
} }

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

@ -1,30 +1,33 @@
package com.alibaba.excel.analysis; package com.alibaba.excel.analysis;
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 java.io.InputStream;
import java.util.List; import java.util.List;
/** /**
* Excel file analyser
* *
* @author jipengfei * @author jipengfei
*/ */
public interface ExcelAnalyser { public interface ExcelAnalyser {
void init(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Object custom, AnalysisEventListener eventListener, /**
boolean trim); * parse one sheet
*
* @param sheetParam
*/
void analysis(Sheet sheetParam); void analysis(Sheet sheetParam);
/**
* parse all sheets
*/
void analysis(); void analysis();
/**
* get all sheet of workbook
*
* @return all sheets
*/
List<Sheet> getSheets(); List<Sheet> getSheets();
} }

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

@ -22,41 +22,61 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
private BaseSaxAnalyser saxAnalyser; private BaseSaxAnalyser saxAnalyser;
public ExcelAnalyserImpl(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Object custom,
AnalysisEventListener eventListener, boolean trim) {
analysisContext = new AnalysisContextImpl(inputStream, excelTypeEnum, custom,
eventListener, trim);
}
private BaseSaxAnalyser getSaxAnalyser() { private BaseSaxAnalyser getSaxAnalyser() {
if (saxAnalyser == null) { if (saxAnalyser != null) {
try { return this.saxAnalyser;
if (ExcelTypeEnum.XLS.equals(analysisContext.getExcelType())) { }
this.saxAnalyser = new XlsSaxAnalyser(analysisContext); try {
} else { if (analysisContext.getExcelType() != null) {
switch (analysisContext.getExcelType()) {
case XLS:
this.saxAnalyser = new XlsSaxAnalyser(analysisContext);
break;
case XLSX:
this.saxAnalyser = new XlsxSaxAnalyser(analysisContext);
break;
}
} else {
try {
this.saxAnalyser = new XlsxSaxAnalyser(analysisContext); this.saxAnalyser = new XlsxSaxAnalyser(analysisContext);
} catch (Exception e) {
if (!analysisContext.getInputStream().markSupported()) {
throw new ExcelAnalysisException(
"Xls must be available markSupported,you can do like this <code> new "
+ "BufferedInputStream(new FileInputStream(\"/xxxx/xxx/77.xlsx\"))</code> ");
}
this.saxAnalyser = new XlsSaxAnalyser(analysisContext);
} }
} catch (Exception e) {
throw new ExcelAnalysisException("Analyse excel occur file error fileType " + analysisContext.getExcelType(),
e);
} }
} catch (Exception e) {
throw new ExcelAnalysisException("File type error,io must be available markSupported,you can do like "
+ "this <code> new BufferedInputStream(new FileInputStream(\\\"/xxxx/xxx/77.xlsx\\\"))</code> \"", e);
} }
return this.saxAnalyser; return this.saxAnalyser;
} }
public void init(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Object custom, @Override
AnalysisEventListener eventListener, boolean trim) {
analysisContext = new AnalysisContextImpl(inputStream, excelTypeEnum, custom,
eventListener, trim);
}
public void analysis(Sheet sheetParam) { public void analysis(Sheet sheetParam) {
analysisContext.setCurrentSheet(sheetParam); analysisContext.setCurrentSheet(sheetParam);
analysis(); analysis();
} }
@Override
public void analysis() { public void analysis() {
BaseSaxAnalyser saxAnalyser = getSaxAnalyser(); BaseSaxAnalyser saxAnalyser = getSaxAnalyser();
appendListeners(saxAnalyser); appendListeners(saxAnalyser);
saxAnalyser.execute(); saxAnalyser.execute();
analysisContext.getEventListener().doAfterAllAnalysed(analysisContext); analysisContext.getEventListener().doAfterAllAnalysed(analysisContext);
} }
@Override
public List<Sheet> getSheets() { public List<Sheet> getSheets() {
BaseSaxAnalyser saxAnalyser = getSaxAnalyser(); BaseSaxAnalyser saxAnalyser = getSaxAnalyser();
saxAnalyser.cleanAllListeners(); saxAnalyser.cleanAllListeners();
@ -64,6 +84,7 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
} }
private void appendListeners(BaseSaxAnalyser saxAnalyser) { private void appendListeners(BaseSaxAnalyser saxAnalyser) {
saxAnalyser.cleanAllListeners();
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());
} }

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

@ -18,6 +18,10 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* /** * A text extractor for Excel files. * <p> * Returns the textual content of the file, suitable for * indexing by
* something like Lucene, but not really * intended for display to the user. * </p> * <p> * To turn an excel file into
* a CSV or similar, then see * the XLS2CSVmra example * </p> * * @see
* <a href="http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java">XLS2CSVmra</a>
* *
* @author jipengfei * @author jipengfei
*/ */
@ -36,6 +40,7 @@ public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener {
} }
@Override
public List<Sheet> getSheets() { public List<Sheet> getSheets() {
execute(); execute();
return sheets; return sheets;
@ -104,27 +109,19 @@ public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener {
*/ */
private EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener; private EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener;
private HSSFWorkbook stubWorkbook; private HSSFWorkbook stubWorkbook;
// Records we pick up as we process
private SSTRecord sstRecord; private SSTRecord sstRecord;
private FormatTrackingHSSFListener formatListener; private FormatTrackingHSSFListener formatListener;
/** /**
* So we known which sheet we're on * So we known which sheet we're on
*/ */
// private BoundSheetRecord[] orderedBSRs;
// @SuppressWarnings("rawtypes")
// private ArrayList boundSheetRecords = new ArrayList();
// For handling formulas with string results
private int nextRow; private int nextRow;
private int nextColumn; private int nextColumn;
private boolean outputNextStringRecord; private boolean outputNextStringRecord;
/** /**
* Main HSSFListener method, processes events, and outputs the CSV as the * Main HSSFListener method, processes events, and outputs the CSV as the file is processed.
* file is processed.
*/ */
private int sheetIndex; private int sheetIndex;
@ -281,10 +278,7 @@ public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener {
// If we got something to print out, do so // If we got something to print out, do so
if (thisStr != null) { if (thisStr != null) {
//if (thisColumn > 1) {
// // output.print(',');
//}
//if (thisStr != null) {
if (analysisContext.trim()) { if (analysisContext.trim()) {
thisStr = thisStr.trim(); thisStr = thisStr.trim();
} }
@ -292,7 +286,6 @@ public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener {
notAllEmpty = true; notAllEmpty = true;
} }
// } // }
// output.print(thisStr);
records.add(thisStr); records.add(thisStr);
} }
@ -307,9 +300,7 @@ public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener {
// Handle end of row // Handle end of row
if (record instanceof LastCellOfRowDummyRecord) { if (record instanceof LastCellOfRowDummyRecord) {
thisRow = ((LastCellOfRowDummyRecord)record).getRow(); thisRow = ((LastCellOfRowDummyRecord)record).getRow();
// thisColumn = ((LastCellOfRowDummyRecord)
// record).getLastColumnNumber();
// Columns are 0 based
if (lastColumnNumber == -1) { if (lastColumnNumber == -1) {
lastColumnNumber = 0; lastColumnNumber = 0;
} }
@ -317,26 +308,11 @@ public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener {
Sheet sheet = analysisContext.getCurrentSheet(); Sheet sheet = analysisContext.getCurrentSheet();
if ((sheet == null || sheet.getSheetNo() == sheetIndex) && notAllEmpty) { if ((sheet == null || sheet.getSheetNo() == sheetIndex) && notAllEmpty) {
notifyListeners(new OneRowAnalysisFinishEvent(copyList(records))); notifyListeners(new OneRowAnalysisFinishEvent(records));
} }
// System.out.println(records);
records.clear(); records.clear();
lastColumnNumber = -1; lastColumnNumber = -1;
notAllEmpty = false; notAllEmpty = false;
} }
} }
private List<String> copyList(List<String> data) {
if (data == null) {
return null;
}
List<String> list = new ArrayList<String>();
for (String str : data) {
list.add(new String(str));
}
return list;
}
} }

18
src/main/java/com/alibaba/excel/analysis/v07/XlsxRowHandler.java

@ -17,7 +17,9 @@ import java.util.Arrays;
import static com.alibaba.excel.constant.ExcelXmlConstants.*; import static com.alibaba.excel.constant.ExcelXmlConstants.*;
/** /**
*
* @author jipengfei * @author jipengfei
* @date 2017/08/23
*/ */
public class XlsxRowHandler extends DefaultHandler { public class XlsxRowHandler extends DefaultHandler {
@ -81,11 +83,6 @@ public class XlsxRowHandler extends DefaultHandler {
if (cellType != null && cellType.equals("s")) { if (cellType != null && cellType.equals("s")) {
currentCellType = FieldType.STRING; currentCellType = FieldType.STRING;
} }
//if ("6".equals(attributes.getValue("s"))) {
// // date
// currentCellType = FieldType.DATE;
//}
} }
} }
@ -102,12 +99,6 @@ public class XlsxRowHandler extends DefaultHandler {
currentCellValue = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); currentCellValue = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
currentCellType = FieldType.EMPTY; currentCellType = FieldType.EMPTY;
break; break;
//case DATE:
// Date dateVal = HSSFDateUtil.getJavaDate(Double.parseDouble(currentCellValue),
// analysisContext.use1904WindowDate());
// currentCellValue = TypeUtil.getDefaultDateString(dateVal);
// currentCellType = FieldType.EMPTY;
// break;
} }
curRowContent[curCol] = currentCellValue; curRowContent[curCol] = currentCellValue;
} else if (CELL_VALUE_TAG_1.equals(name)) { } else if (CELL_VALUE_TAG_1.equals(name)) {
@ -117,16 +108,13 @@ public class XlsxRowHandler extends DefaultHandler {
@Override @Override
public void endElement(String uri, String localName, String name) throws SAXException { public void endElement(String uri, String localName, String name) throws SAXException {
endRow(name); endRow(name);
endCellValue(name); endCellValue(name);
} }
@Override @Override
public void characters(char[] ch, int start, int length) throws SAXException { public void characters(char[] ch, int start, int length) throws SAXException {
currentCellValue += new String(ch, start, length); currentCellValue += new String(ch, start, length);
} }
@ -142,7 +130,7 @@ public class XlsxRowHandler extends DefaultHandler {
private void endRow(String name) { private void endRow(String name) {
if (name.equals(ROW_TAG)) { if (name.equals(ROW_TAG)) {
registerCenter.notifyListeners(new OneRowAnalysisFinishEvent(Arrays.asList(curRowContent))); registerCenter.notifyListeners(new OneRowAnalysisFinishEvent(curRowContent,curCol));
curRowContent = new String[20]; curRowContent = new String[20];
} }
} }

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

@ -24,7 +24,9 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
*
* @author jipengfei * @author jipengfei
* @date 2017/08/27
*/ */
public class XlsxSaxAnalyser extends BaseSaxAnalyser { public class XlsxSaxAnalyser extends BaseSaxAnalyser {
@ -34,7 +36,6 @@ public class XlsxSaxAnalyser extends BaseSaxAnalyser {
private List<SheetSource> sheetSourceList = new ArrayList<SheetSource>(); private List<SheetSource> sheetSourceList = new ArrayList<SheetSource>();
private boolean use1904WindowDate = false; private boolean use1904WindowDate = false;
public XlsxSaxAnalyser(AnalysisContext analysisContext) throws IOException, OpenXML4JException, XmlException { public XlsxSaxAnalyser(AnalysisContext analysisContext) throws IOException, OpenXML4JException, XmlException {
@ -66,6 +67,7 @@ public class XlsxSaxAnalyser extends BaseSaxAnalyser {
} }
@Override
protected void execute() { protected void execute() {
Sheet sheetParam = analysisContext.getCurrentSheet(); Sheet sheetParam = analysisContext.getCurrentSheet();
if (sheetParam != null && sheetParam.getSheetNo() > 0 && sheetSourceList.size() >= sheetParam.getSheetNo()) { if (sheetParam != null && sheetParam.getSheetNo() > 0 && sheetSourceList.size() >= sheetParam.getSheetNo()) {
@ -91,16 +93,17 @@ public class XlsxSaxAnalyser extends BaseSaxAnalyser {
saxFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); saxFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
SAXParser saxParser = saxFactory.newSAXParser(); SAXParser saxParser = saxFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader(); XMLReader xmlReader = saxParser.getXMLReader();
ContentHandler handler = new XlsxRowHandler(this, sharedStringsTable, analysisContext); ContentHandler handler = new XlsxRowHandler(this, sharedStringsTable, analysisContext);
xmlReader.setContentHandler(handler); xmlReader.setContentHandler(handler);
xmlReader.parse(sheetSource); xmlReader.parse(sheetSource);
inputStream.close(); inputStream.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
throw new ExcelAnalysisException(e); throw new ExcelAnalysisException(e);
} }
} }
@Override
public List<Sheet> getSheets() { public List<Sheet> getSheets() {
List<Sheet> sheets = new ArrayList<Sheet>(); List<Sheet> sheets = new ArrayList<Sheet>();
int i = 1; int i = 1;

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

@ -1,12 +1,17 @@
package com.alibaba.excel.annotation; package com.alibaba.excel.annotation;
import java.lang.annotation.*; import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** /**
* Created by jipengfei on 17/3/19. * 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)

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

@ -1,6 +1,10 @@
package com.alibaba.excel.annotation; package com.alibaba.excel.annotation;
import java.lang.annotation.*; import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** /**
* @author jipengfei * @author jipengfei

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

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

1
src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java

@ -2,6 +2,7 @@ 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";

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

@ -11,71 +11,77 @@ import java.util.List;
/** /**
* *
* A context is the main anchorage point of a excel reader.
* @author jipengfei * @author jipengfei
*/ */
public interface AnalysisContext { public interface AnalysisContext {
/** /**
* * Custom attribute
*/ */
Object getCustom(); Object getCustom();
/** /**
* get current sheet
* *
* @return current analysis sheet * @return current analysis sheet
*/ */
Sheet getCurrentSheet(); Sheet getCurrentSheet();
/** /**
* * set current sheet
* @param sheet * @param sheet
*/ */
void setCurrentSheet(Sheet sheet); void setCurrentSheet(Sheet sheet);
/** /**
* *
* get excel type
* @return excel type * @return excel type
*/ */
ExcelTypeEnum getExcelType(); ExcelTypeEnum getExcelType();
/** /**
* * get in io
* @return file io * @return file io
*/ */
InputStream getInputStream(); InputStream getInputStream();
/** /**
* *
* @return * custom listener
* @return listener
*/ */
AnalysisEventListener getEventListener(); AnalysisEventListener getEventListener();
/** /**
* * get current row
* @return * @return
*/ */
Integer getCurrentRowNum(); Integer getCurrentRowNum();
/** /**
* * set current row num
* @param row * @param row
*/ */
void setCurrentRowNum(Integer row); void setCurrentRowNum(Integer row);
/** /**
* * get total row ,Data may be inaccurate
* @return * @return
*/ */
@Deprecated
Integer getTotalCount(); Integer getTotalCount();
/** /**
* get total row ,Data may be inaccurate
* *
* @param totalCount * @param totalCount
*/ */
void setTotalCount(Integer totalCount); void setTotalCount(Integer totalCount);
/** /**
* * get excel head
* @return * @return
*/ */
ExcelHeadProperty getExcelHeadProperty(); ExcelHeadProperty getExcelHeadProperty();
@ -89,34 +95,37 @@ public interface AnalysisContext {
/** /**
* *
*if need to short match the content
* @return * @return
*/ */
boolean trim(); boolean trim();
/** /**
* * set current result
* @param result
*/ */
void setCurrentRowAnalysisResult(Object result); void setCurrentRowAnalysisResult(Object result);
/** /**
* * get current result
* @return get current result
*/ */
Object getCurrentRowAnalysisResult(); Object getCurrentRowAnalysisResult();
/** /**
* * Interrupt execution
*/ */
void interrupt(); void interrupt();
/** /**
* * date use1904WindowDate
* @return * @return
*/ */
boolean use1904WindowDate(); boolean use1904WindowDate();
/** /**
* * date use1904WindowDate
* @param use1904WindowDate * @param use1904WindowDate
*/ */
void setUse1904WindowDate(boolean use1904WindowDate); void setUse1904WindowDate(boolean use1904WindowDate);

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

@ -37,22 +37,27 @@ public class AnalysisContextImpl implements AnalysisContext {
private boolean use1904WindowDate = false; private boolean use1904WindowDate = false;
@Override
public void setUse1904WindowDate(boolean use1904WindowDate) { public void setUse1904WindowDate(boolean use1904WindowDate) {
this.use1904WindowDate = use1904WindowDate; this.use1904WindowDate = use1904WindowDate;
} }
@Override
public Object getCurrentRowAnalysisResult() { public Object getCurrentRowAnalysisResult() {
return currentRowAnalysisResult; return currentRowAnalysisResult;
} }
@Override
public void interrupt() { public void interrupt() {
throw new ExcelAnalysisException("interrupt error"); throw new ExcelAnalysisException("interrupt error");
} }
@Override
public boolean use1904WindowDate() { public boolean use1904WindowDate() {
return use1904WindowDate; return use1904WindowDate;
} }
@Override
public void setCurrentRowAnalysisResult(Object currentRowAnalysisResult) { public void setCurrentRowAnalysisResult(Object currentRowAnalysisResult) {
this.currentRowAnalysisResult = currentRowAnalysisResult; this.currentRowAnalysisResult = currentRowAnalysisResult;
} }
@ -68,13 +73,24 @@ public class AnalysisContextImpl implements AnalysisContext {
this.trim = trim; this.trim = trim;
} }
@Override
public void setCurrentSheet(Sheet currentSheet) { public void setCurrentSheet(Sheet currentSheet) {
cleanCurrentSheet();
this.currentSheet = currentSheet; this.currentSheet = currentSheet;
if (currentSheet.getClazz() != null) { if (currentSheet.getClazz() != null) {
buildExcelHeadProperty(currentSheet.getClazz(), null); buildExcelHeadProperty(currentSheet.getClazz(), null);
} }
} }
private void cleanCurrentSheet() {
this.currentSheet = null;
this.excelHeadProperty = null;
this.totalCount = 0;
this.currentRowAnalysisResult = null;
this.currentRowNum =0;
}
@Override
public ExcelTypeEnum getExcelType() { public ExcelTypeEnum getExcelType() {
return excelType; return excelType;
} }
@ -91,10 +107,12 @@ public class AnalysisContextImpl implements AnalysisContext {
this.custom = custom; this.custom = custom;
} }
@Override
public Sheet getCurrentSheet() { public Sheet getCurrentSheet() {
return currentSheet; return currentSheet;
} }
@Override
public InputStream getInputStream() { public InputStream getInputStream() {
return inputStream; return inputStream;
} }
@ -103,6 +121,7 @@ public class AnalysisContextImpl implements AnalysisContext {
this.inputStream = inputStream; this.inputStream = inputStream;
} }
@Override
public AnalysisEventListener getEventListener() { public AnalysisEventListener getEventListener() {
return eventListener; return eventListener;
} }
@ -111,26 +130,32 @@ public class AnalysisContextImpl implements AnalysisContext {
this.eventListener = eventListener; this.eventListener = eventListener;
} }
@Override
public Integer getCurrentRowNum() { public Integer getCurrentRowNum() {
return this.currentRowNum; return this.currentRowNum;
} }
@Override
public void setCurrentRowNum(Integer row) { public void setCurrentRowNum(Integer row) {
this.currentRowNum = row; this.currentRowNum = row;
} }
@Override
public Integer getTotalCount() { public Integer getTotalCount() {
return totalCount; return totalCount;
} }
@Override
public void setTotalCount(Integer totalCount) { public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount; this.totalCount = totalCount;
} }
@Override
public ExcelHeadProperty getExcelHeadProperty() { public ExcelHeadProperty getExcelHeadProperty() {
return this.excelHeadProperty; return this.excelHeadProperty;
} }
@Override
public void buildExcelHeadProperty(Class<? extends BaseRowModel> clazz, List<String> headOneRow) { public void buildExcelHeadProperty(Class<? extends BaseRowModel> clazz, List<String> headOneRow) {
if (this.excelHeadProperty == null && (clazz != null || headOneRow != null)) { if (this.excelHeadProperty == null && (clazz != null || headOneRow != null)) {
this.excelHeadProperty = new ExcelHeadProperty(clazz, new ArrayList<List<String>>()); this.excelHeadProperty = new ExcelHeadProperty(clazz, new ArrayList<List<String>>());
@ -140,6 +165,7 @@ public class AnalysisContextImpl implements AnalysisContext {
} }
} }
@Override
public boolean trim() { public boolean trim() {
return this.trim; return this.trim;
} }

66
src/main/java/com/alibaba/excel/context/GenerateContext.java

@ -1,66 +0,0 @@
package com.alibaba.excel.context;
import com.alibaba.excel.metadata.ExcelHeadProperty;
import com.alibaba.excel.metadata.Table;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.OutputStream;
/**
* @author jipengfei
*/
public interface GenerateContext {
/**
* @return current analysis sheet
*/
Sheet getCurrentSheet();
/**
*
* @return
*/
CellStyle getCurrentHeadCellStyle();
/**
* @return
*/
CellStyle getCurrentContentStyle();
/**
* @return
*/
Workbook getWorkbook();
/**
* @return
*/
OutputStream getOutputStream();
/**
* @param sheet
*/
void buildCurrentSheet(com.alibaba.excel.metadata.Sheet sheet);
/**
* @param table
*/
void buildTable(Table table);
/**
* @return
*/
ExcelHeadProperty getExcelHeadProperty();
/**
*
* @return
*/
boolean needHead();
}

246
src/main/java/com/alibaba/excel/context/GenerateContextImpl.java

@ -1,246 +0,0 @@
package com.alibaba.excel.context;
import com.alibaba.excel.metadata.*;
import com.alibaba.excel.metadata.CellRange;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
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;
/**
*
* @author jipengfei
*/
public class GenerateContextImpl implements GenerateContext {
private Sheet currentSheet;
private String currentSheetName;
private ExcelTypeEnum excelType;
private Workbook workbook;
private OutputStream outputStream;
private Map<Integer, Sheet> sheetMap = new ConcurrentHashMap<Integer, Sheet>();
private Map<Integer, Table> tableMap = new ConcurrentHashMap<Integer, Table>();
private CellStyle defaultCellStyle;
private CellStyle currentHeadCellStyle;
private CellStyle currentContentCellStyle;
private ExcelHeadProperty excelHeadProperty;
private boolean needHead = true;
public GenerateContextImpl(InputStream templateInputStream, OutputStream out, ExcelTypeEnum excelType,
boolean needHead) throws IOException {
if (ExcelTypeEnum.XLS.equals(excelType)) {
if(templateInputStream == null) {
this.workbook = new HSSFWorkbook();
}else {
this.workbook = new HSSFWorkbook(new POIFSFileSystem(templateInputStream));
}
} else {
if(templateInputStream == null) {
this.workbook = new SXSSFWorkbook(500);
}else {
this.workbook = new SXSSFWorkbook(new XSSFWorkbook(templateInputStream));
}
}
this.outputStream = out;
this.defaultCellStyle = buildDefaultCellStyle();
this.needHead = needHead;
}
private CellStyle buildDefaultCellStyle() {
CellStyle newCellStyle = this.workbook.createCellStyle();
Font font = this.workbook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short)14);
font.setBold(true);
newCellStyle.setFont(font);
newCellStyle.setWrapText(true);
newCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
newCellStyle.setAlignment(HorizontalAlignment.CENTER);
newCellStyle.setLocked(true);
newCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
newCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
newCellStyle.setBorderBottom(BorderStyle.THIN);
newCellStyle.setBorderLeft(BorderStyle.THIN);
return newCellStyle;
}
public void buildCurrentSheet(com.alibaba.excel.metadata.Sheet sheet) {
if (sheetMap.containsKey(sheet.getSheetNo())) {
this.currentSheet = sheetMap.get(sheet.getSheetNo());
} else {
Sheet sheet1 = null;
try {
sheet1 = workbook.getSheetAt(sheet.getSheetNo());
}catch (Exception e){
}
if(sheet1 == null) {
this.currentSheet = workbook.createSheet(
sheet.getSheetName() != null ? sheet.getSheetName() : sheet.getSheetNo() + "");
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);
buildHead(sheet.getHead(), sheet.getClazz());
buildTableStyle(sheet.getTableStyle());
if (needHead && excelHeadProperty != null) {
appendHeadToExcel();
}
}
}
private void buildHead(List<List<String>> head, Class<? extends BaseRowModel> clazz) {
if (head != null || clazz != null) { excelHeadProperty = new ExcelHeadProperty(clazz, head); }
}
public void appendHeadToExcel() {
if (this.excelHeadProperty.getHead() != null && this.excelHeadProperty.getHead().size() > 0) {
List<CellRange> list = this.excelHeadProperty.getCellRangeModels();
int n = currentSheet.getLastRowNum();
if (n > 0) {
n = n + 4;
}
for (CellRange cellRangeModel : list) {
CellRangeAddress cra = new CellRangeAddress(cellRangeModel.getFirstRow() + n,
cellRangeModel.getLastRow() + n,
cellRangeModel.getFirstCol(), cellRangeModel.getLastCol());
currentSheet.addMergedRegion(cra);
}
int i = n;
for (; i < this.excelHeadProperty.getRowNum() + n; i++) {
Row row = currentSheet.createRow(i);
addOneRowOfHeadDataToExcel(row, this.excelHeadProperty.getHeadByRowNum(i - n));
}
}
}
private void addOneRowOfHeadDataToExcel(Row row, List<String> headByRowNum) {
if (headByRowNum != null && headByRowNum.size() > 0) {
for (int i = 0; i < headByRowNum.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(this.getCurrentHeadCellStyle());
cell.setCellValue(headByRowNum.get(i));
}
}
}
private void buildTableStyle(TableStyle tableStyle) {
if (tableStyle != null) {
CellStyle headStyle = buildDefaultCellStyle();
if (tableStyle.getTableHeadFont() != null) {
Font font = this.workbook.createFont();
font.setFontName(tableStyle.getTableHeadFont().getFontName());
font.setFontHeightInPoints(tableStyle.getTableHeadFont().getFontHeightInPoints());
font.setBold(tableStyle.getTableHeadFont().isBold());
headStyle.setFont(font);
}
if (tableStyle.getTableHeadBackGroundColor() != null) {
headStyle.setFillForegroundColor(tableStyle.getTableHeadBackGroundColor().getIndex());
}
this.currentHeadCellStyle = headStyle;
CellStyle contentStyle = buildDefaultCellStyle();
if (tableStyle.getTableContentFont() != null) {
Font font = this.workbook.createFont();
font.setFontName(tableStyle.getTableContentFont().getFontName());
font.setFontHeightInPoints(tableStyle.getTableContentFont().getFontHeightInPoints());
font.setBold(tableStyle.getTableContentFont().isBold());
contentStyle.setFont(font);
}
if (tableStyle.getTableContentBackGroundColor() != null) {
contentStyle.setFillForegroundColor(tableStyle.getTableContentBackGroundColor().getIndex());
}
this.currentContentCellStyle = contentStyle;
}
}
public void buildTable(Table table) {
if (!tableMap.containsKey(table.getTableNo())) {
buildHead(table.getHead(), table.getClazz());
tableMap.put(table.getTableNo(), table);
buildTableStyle(table.getTableStyle());
if (needHead && excelHeadProperty != null) {
appendHeadToExcel();
}
}
}
public ExcelHeadProperty getExcelHeadProperty() {
return this.excelHeadProperty;
}
public boolean needHead() {
return this.needHead;
}
public Sheet getCurrentSheet() {
return currentSheet;
}
public void setCurrentSheet(Sheet currentSheet) {
this.currentSheet = currentSheet;
}
public String getCurrentSheetName() {
return currentSheetName;
}
public void setCurrentSheetName(String currentSheetName) {
this.currentSheetName = currentSheetName;
}
public ExcelTypeEnum getExcelType() {
return excelType;
}
public void setExcelType(ExcelTypeEnum excelType) {
this.excelType = excelType;
}
public OutputStream getOutputStream() {
return outputStream;
}
public CellStyle getCurrentHeadCellStyle() {
return this.currentHeadCellStyle == null ? defaultCellStyle : this.currentHeadCellStyle;
}
public CellStyle getCurrentContentStyle() {
return this.currentContentCellStyle;
}
public Workbook getWorkbook() {
return workbook;
}
}

278
src/main/java/com/alibaba/excel/context/WriteContext.java

@ -0,0 +1,278 @@
package com.alibaba.excel.context;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.ExcelHeadProperty;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.util.WorkBookUtil;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static com.alibaba.excel.util.StyleUtil.buildSheetStyle;
/**
* A context is the main anchorage point of a excel writer.
*
* @author jipengfei
*/
public class WriteContext {
/***
* The sheet currently written
*/
private Sheet currentSheet;
/**
* current param
*/
private com.alibaba.excel.metadata.Sheet currentSheetParam;
/**
* The sheet currently written's name
*/
private String currentSheetName;
/**
*
*/
private Table currentTable;
/**
* Excel type
*/
private ExcelTypeEnum excelType;
/**
* POI Workbook
*/
private Workbook workbook;
/**
* Final output stream
*/
private OutputStream outputStream;
/**
* Written form collection
*/
private Map<Integer, Table> tableMap = new ConcurrentHashMap<Integer, Table>();
/**
* Cell default style
*/
private CellStyle defaultCellStyle;
/**
* Current table head style
*/
private CellStyle currentHeadCellStyle;
/**
* Current table content style
*/
private CellStyle currentContentCellStyle;
/**
* the header attribute of excel
*/
private ExcelHeadProperty excelHeadProperty;
private boolean needHead = Boolean.TRUE;
public WriteContext(InputStream templateInputStream, OutputStream out, ExcelTypeEnum excelType,
boolean needHead) throws IOException {
this.needHead = needHead;
this.outputStream = out;
this.workbook = WorkBookUtil.createWorkBook(templateInputStream, excelType);
this.defaultCellStyle = StyleUtil.buildDefaultCellStyle(this.workbook);
}
/**
* @param sheet
*/
public void currentSheet(com.alibaba.excel.metadata.Sheet sheet) {
if (null == currentSheetParam || currentSheetParam.getSheetNo() != sheet.getSheetNo()) {
cleanCurrentSheet();
currentSheetParam = sheet;
try {
this.currentSheet = workbook.getSheetAt(sheet.getSheetNo() - 1);
} catch (Exception e) {
this.currentSheet = WorkBookUtil.createSheet(workbook, sheet);
}
buildSheetStyle(currentSheet, sheet.getColumnWidthMap());
/** **/
this.initCurrentSheet(sheet);
}
}
private void initCurrentSheet(com.alibaba.excel.metadata.Sheet sheet) {
/** **/
initExcelHeadProperty(sheet.getHead(), sheet.getClazz());
initTableStyle(sheet.getTableStyle());
initTableHead();
}
private void cleanCurrentSheet() {
this.currentSheet = null;
this.currentSheetParam = null;
this.excelHeadProperty = null;
this.currentHeadCellStyle = null;
this.currentContentCellStyle = null;
this.currentTable = null;
}
/**
* init excel header
*
* @param head
* @param clazz
*/
private void initExcelHeadProperty(List<List<String>> head, Class<? extends BaseRowModel> clazz) {
if (head != null || clazz != null) { this.excelHeadProperty = new ExcelHeadProperty(clazz, head); }
}
public void initTableHead() {
if (needHead && null != excelHeadProperty && !CollectionUtils.isEmpty(excelHeadProperty.getHead())) {
int startRow = currentSheet.getLastRowNum();
if (startRow > 0) {
startRow += 4;
}else {
startRow = currentSheetParam.getStartRow();
}
addMergedRegionToCurrentSheet(startRow);
int i = startRow;
for (; i < this.excelHeadProperty.getRowNum() + startRow; i++) {
Row row = WorkBookUtil.createRow(currentSheet, i);
addOneRowOfHeadDataToExcel(row, this.excelHeadProperty.getHeadByRowNum(i - startRow));
}
}
}
private void addMergedRegionToCurrentSheet(int startRow) {
for (com.alibaba.excel.metadata.CellRange cellRangeModel : excelHeadProperty.getCellRangeModels()) {
currentSheet.addMergedRegion(new CellRangeAddress(cellRangeModel.getFirstRow() + startRow,
cellRangeModel.getLastRow() + startRow,
cellRangeModel.getFirstCol(), cellRangeModel.getLastCol()));
}
}
private void addOneRowOfHeadDataToExcel(Row row, List<String> headByRowNum) {
if (headByRowNum != null && headByRowNum.size() > 0) {
for (int i = 0; i < headByRowNum.size(); i++) {
WorkBookUtil.createCell(row, i, getCurrentHeadCellStyle(), headByRowNum.get(i));
}
}
}
private void initTableStyle(com.alibaba.excel.metadata.TableStyle tableStyle) {
if (tableStyle != null) {
this.currentHeadCellStyle = StyleUtil.buildCellStyle(this.workbook, tableStyle.getTableHeadFont(),
tableStyle.getTableHeadBackGroundColor());
this.currentContentCellStyle = StyleUtil.buildCellStyle(this.workbook, tableStyle.getTableContentFont(),
tableStyle.getTableContentBackGroundColor());
}
}
private void cleanCurrentTable() {
this.excelHeadProperty = null;
this.currentHeadCellStyle = null;
this.currentContentCellStyle = null;
this.currentTable = null;
}
public void currentTable(Table table) {
if (null == currentTable || currentTable.getTableNo() != table.getTableNo()) {
cleanCurrentTable();
this.currentTable = table;
this.initExcelHeadProperty(table.getHead(), table.getClazz());
this.initTableStyle(table.getTableStyle());
this.initTableHead();
}
}
public ExcelHeadProperty getExcelHeadProperty() {
return this.excelHeadProperty;
}
public boolean needHead() {
return this.needHead;
}
public Sheet getCurrentSheet() {
return currentSheet;
}
public void setCurrentSheet(Sheet currentSheet) {
this.currentSheet = currentSheet;
}
public String getCurrentSheetName() {
return currentSheetName;
}
public void setCurrentSheetName(String currentSheetName) {
this.currentSheetName = currentSheetName;
}
public ExcelTypeEnum getExcelType() {
return excelType;
}
public void setExcelType(ExcelTypeEnum excelType) {
this.excelType = excelType;
}
public OutputStream getOutputStream() {
return outputStream;
}
public CellStyle getCurrentHeadCellStyle() {
return this.currentHeadCellStyle == null ? defaultCellStyle : this.currentHeadCellStyle;
}
public CellStyle getCurrentContentStyle() {
return this.currentContentCellStyle;
}
public Workbook getWorkbook() {
return workbook;
}
public com.alibaba.excel.metadata.Sheet getCurrentSheetParam() {
return currentSheetParam;
}
public void setCurrentSheetParam(com.alibaba.excel.metadata.Sheet currentSheetParam) {
this.currentSheetParam = currentSheetParam;
}
public Table getCurrentTable() {
return currentTable;
}
public void setCurrentTable(Table currentTable) {
this.currentTable = currentTable;
}
}

14
src/main/java/com/alibaba/excel/event/AnalysisEventRegisterCenter.java

@ -1,25 +1,29 @@
package com.alibaba.excel.event; package com.alibaba.excel.event;
/** /**
* Event center.
* *
* @author jipengfei * @author jipengfei
*/ */
public interface AnalysisEventRegisterCenter { public interface AnalysisEventRegisterCenter {
/** /**
* @param name 监听名定义 * Append listener
* @param listener 具体实现 *
* @param name listener name.
* @param listener Callback method after each row is parsed.
*/ */
void appendLister(String name, AnalysisEventListener listener); void appendLister(String name, AnalysisEventListener listener);
/** /**
* @param event 事件 * Parse one row to notify all event listeners
*
* @param event parse event
*/ */
void notifyListeners(OneRowAnalysisFinishEvent event); void notifyListeners(OneRowAnalysisFinishEvent event);
/** /**
* Clean all listeners.
*/ */
void cleanAllListeners(); void cleanAllListeners();
} }

18
src/main/java/com/alibaba/excel/event/OneRowAnalysisFinishEvent.java

@ -1,12 +1,26 @@
package com.alibaba.excel.event; package com.alibaba.excel.event;
import java.util.ArrayList;
import java.util.List;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/07/21
*/ */
public class OneRowAnalysisFinishEvent { public class OneRowAnalysisFinishEvent {
public OneRowAnalysisFinishEvent(Object data) { public OneRowAnalysisFinishEvent(Object content) {
this.data = data; this.data = content;
}
public OneRowAnalysisFinishEvent(String[] content, int length) {
if (content != null) {
List<String> ls = new ArrayList<String>(length);
for (int i = 0; i <= length; i++) {
ls.add(content[i]);
}
data = ls;
}
} }
private Object data; private Object data;

1
src/main/java/com/alibaba/excel/exception/ExcelGenerateException.java

@ -17,5 +17,4 @@ public class ExcelGenerateException extends RuntimeException {
public ExcelGenerateException(Throwable cause) { public ExcelGenerateException(Throwable cause) {
super(cause); super(cause);
} }
} }

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

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

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 {

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

@ -6,6 +6,7 @@ import java.util.List;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/05/31
*/ */
public class ExcelColumnProperty implements Comparable<ExcelColumnProperty> { public class ExcelColumnProperty implements Comparable<ExcelColumnProperty> {

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

@ -2,29 +2,36 @@ package com.alibaba.excel.metadata;
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 com.alibaba.excel.util.StringUtils;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.*; import java.util.*;
/** /**
* Define the header attribute of excel
* *
* @author jipengfei * @author jipengfei
* @date 2017/05/31
*/ */
public class ExcelHeadProperty { public class ExcelHeadProperty {
/** /**
* Custom class
*/ */
private Class<? extends BaseRowModel> headClazz; private Class<? extends BaseRowModel> headClazz;
/** /**
* A two-dimensional array describing the header
*/ */
private List<List<String>> head = new ArrayList<List<String>>(); private List<List<String>> head = new ArrayList<List<String>>();
/** /**
* Attributes described by the header
*/ */
private List<ExcelColumnProperty> columnPropertyList = new ArrayList<ExcelColumnProperty>(); private List<ExcelColumnProperty> columnPropertyList = new ArrayList<ExcelColumnProperty>();
/** /**
* Attributes described by the header
*/ */
private Map<Integer, ExcelColumnProperty> excelColumnPropertyMap1 = new HashMap<Integer, ExcelColumnProperty>(); private Map<Integer, ExcelColumnProperty> excelColumnPropertyMap1 = new HashMap<Integer, ExcelColumnProperty>();
@ -55,7 +62,6 @@ public class ExcelHeadProperty {
} }
/** /**
*
* @param f * @param f
*/ */
private void initOneColumnProperty(Field f) { private void initOneColumnProperty(Field f) {
@ -103,44 +109,11 @@ public class ExcelHeadProperty {
} }
/** /**
*
* @param columnNum * @param columnNum
* @return * @return
*/ */
public ExcelColumnProperty getExcelColumnProperty(int columnNum) { public ExcelColumnProperty getExcelColumnProperty(int columnNum) {
ExcelColumnProperty excelColumnProperty = excelColumnPropertyMap1.get(columnNum); return excelColumnPropertyMap1.get(columnNum);
if (excelColumnProperty == null) {
if (head != null && head.size() > columnNum) {
List<String> columnHead = head.get(columnNum);
for (ExcelColumnProperty columnProperty : columnPropertyList) {
if (headEquals(columnHead, columnProperty.getHead())) {
return columnProperty;
}
}
}
}
return excelColumnProperty;
}
/**
*
* @param columnHead
* @param head
* @return
*/
private boolean headEquals(List<String> columnHead, List<String> head) {
boolean result = true;
if (columnHead == null || head == null || columnHead.size() != head.size()) {
return false;
} else {
for (int i = 0; i < head.size(); i++) {
if (!head.get(i).equals(columnHead.get(i))) {
result = false;
break;
}
}
}
return result;
} }
public Class getHeadClazz() { public Class getHeadClazz() {
@ -167,20 +140,24 @@ public class ExcelHeadProperty {
this.columnPropertyList = columnPropertyList; this.columnPropertyList = columnPropertyList;
} }
/**
* Calculate all cells that need to be merged
*
* @return cells that need to be merged
*/
public List<CellRange> getCellRangeModels() { public List<CellRange> getCellRangeModels() {
List<CellRange> rangs = new ArrayList<CellRange>(); List<CellRange> cellRanges = new ArrayList<CellRange>();
for (int i = 0; i < head.size(); i++) { for (int i = 0; i < head.size(); i++) {
List<String> columnvalues = head.get(i); List<String> columnValues = head.get(i);
for (int j = 0; j < columnvalues.size(); j++) { for (int j = 0; j < columnValues.size(); j++) {
int lastRow = getLastRangRow(j, columnvalues.get(j), columnvalues); int lastRow = getLastRangNum(j, columnValues.get(j), columnValues);
int lastColumn = getLastRangColumn(columnvalues.get(j), getHeadByRowNum(j), i); int lastColumn = getLastRangNum(i, columnValues.get(j), getHeadByRowNum(j));
if (lastRow >= 0 && lastColumn >= 0 && (lastRow > j || lastColumn > i)) { if ((lastRow > j || lastColumn > i) && lastRow >= 0 && lastColumn >= 0) {
rangs.add(new CellRange(j, lastRow, i, lastColumn)); cellRanges.add(new CellRange(j, lastRow, i, lastColumn));
} }
} }
} }
return rangs; return cellRanges;
} }
public List<String> getHeadByRowNum(int rowNum) { public List<String> getHeadByRowNum(int rowNum) {
@ -196,29 +173,36 @@ public class ExcelHeadProperty {
} }
/** /**
* @param value * Get the last consecutive string position
* @param headByRowNum *
* @param i * @param j current value position
* @return * @param value value content
* @param values values
* @return the last consecutive string position
*/ */
private int getLastRangColumn(String value, List<String> headByRowNum, int i) { private int getLastRangNum(int j, String value, List<String> values) {
if (headByRowNum.indexOf(value) < i) { int lastRow = -1;
if (StringUtils.isEmpty(value)) {
return -1; return -1;
} else {
return headByRowNum.lastIndexOf(value);
} }
} for (int i = 0; i < values.size(); i++) {
String current = values.get(i);
private int getLastRangRow(int j, String value, List<String> columnvalue) { if (value.equals(current)) {
if (i >= j) {
if (columnvalue.indexOf(value) < j) { lastRow = i;
return -1; } else {
} //if i<j && value.equals(current) Indicates that a merger has occurred
if (value != null && value.equals(columnvalue.get(columnvalue.size() - 1))) { return -1;
return getRowNum() - 1; }
} else { } else {
return columnvalue.lastIndexOf(value); // if i>j && !value.equals(current) Indicates that the continuous range is exceeded
if (i > j) {
break;
}
}
} }
return lastRow;
} }
public int getRowNum() { public int getRowNum() {

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

@ -3,6 +3,7 @@ package com.alibaba.excel.metadata;
/** /**
* *
* @author jipengfei * @author jipengfei
* @date 2017/05/24
*/ */
public class Font { public class Font {

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

@ -15,6 +15,7 @@ public class Sheet {
private int headLineMun; private int headLineMun;
/** /**
* Starting from 1
*/ */
private int sheetNo; private int sheetNo;
@ -48,7 +49,7 @@ public class Sheet {
/** /**
* *
*/ */
private int startRow = -1; private int startRow = 0;
public Sheet(int sheetNo) { public Sheet(int sheetNo) {

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

@ -4,6 +4,7 @@ import java.util.List;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/05/16
*/ */
public class Table { public class Table {
/** /**
@ -16,7 +17,7 @@ public class Table {
/** /**
*/ */
private Integer tableNo; private int tableNo;
/** /**
*/ */
@ -50,11 +51,11 @@ public class Table {
this.head = head; this.head = head;
} }
public Integer getTableNo() { public int getTableNo() {
return tableNo; return tableNo;
} }
public void setTableNo(Integer tableNo) { public void setTableNo(int tableNo) {
this.tableNo = tableNo; this.tableNo = tableNo;
} }
} }

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 {

50
src/main/java/com/alibaba/excel/modelbuild/ModelBuildEventListener.java

@ -3,59 +3,37 @@ package com.alibaba.excel.modelbuild;
import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.exception.ExcelGenerateException;
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 net.sf.cglib.beans.BeanMap;
import java.util.List; import java.util.List;
/** /**
*
* @author jipengfei * @author jipengfei
*/ */
public class ModelBuildEventListener extends AnalysisEventListener { public class ModelBuildEventListener extends AnalysisEventListener {
@Override @Override
public void invoke(Object object, AnalysisContext context) { public void invoke(Object object, AnalysisContext context) {
if (context.getExcelHeadProperty() != null && context.getExcelHeadProperty().getHeadClazz() != null) {
try {
if(context.getExcelHeadProperty() != null && context.getExcelHeadProperty().getHeadClazz()!=null ){ Object resultModel = buildUserModel(context, (List<String>)object);
Object resultModel = buildUserModel(context, (List<String>)object); context.setCurrentRowAnalysisResult(resultModel);
context.setCurrentRowAnalysisResult(resultModel); } catch (Exception e) {
throw new ExcelGenerateException(e);
}
} }
} }
private Object buildUserModel(AnalysisContext context, List<String> stringList) throws Exception {
private Object buildUserModel(AnalysisContext context, List<String> stringList) {
ExcelHeadProperty excelHeadProperty = context.getExcelHeadProperty(); ExcelHeadProperty excelHeadProperty = context.getExcelHeadProperty();
Object resultModel = excelHeadProperty.getHeadClazz().newInstance();
Object resultModel; if (excelHeadProperty == null) {
try { return resultModel;
resultModel = excelHeadProperty.getHeadClazz().newInstance();
} catch (Exception e) {
throw new ExcelGenerateException(e);
}
if (excelHeadProperty != null) {
for (int i = 0; i < stringList.size(); i++) {
ExcelColumnProperty columnProperty = excelHeadProperty.getExcelColumnProperty(i);
if (columnProperty != null) {
Object value = TypeUtil.convert(stringList.get(i), columnProperty.getField(),
columnProperty.getFormat(),context.use1904WindowDate());
if (value != null) {
try {
BeanUtils.setProperty(resultModel, columnProperty.getField().getName(), value);
} catch (Exception e) {
throw new ExcelGenerateException(
columnProperty.getField().getName() + " can not set value " + value, e);
}
}
}
}
} }
BeanMap.create(resultModel).putAll(
TypeUtil.getFieldValues(stringList, excelHeadProperty, context.use1904WindowDate()));
return resultModel; return resultModel;
} }

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

@ -17,7 +17,7 @@ public class AnalysisParam {
private ExcelTypeEnum excelTypeEnum; private ExcelTypeEnum excelTypeEnum;
/** /**
* file in * the POI filesystem that contains the Workbook stream
*/ */
private InputStream in; private InputStream in;

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

@ -1,13 +1,14 @@
package com.alibaba.excel.parameter; package com.alibaba.excel.parameter;
import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.OutputStream; import java.io.OutputStream;
import com.alibaba.excel.support.ExcelTypeEnum;
/** /**
* {@link com.alibaba.excel.ExcelWriter} * {@link com.alibaba.excel.ExcelWriter}
* *
* @author jipengfei * @author jipengfei
* @date 2017/05/15
*/ */
@Deprecated @Deprecated
public class ExcelWriteParam { public class ExcelWriteParam {

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

@ -1,9 +1,9 @@
package com.alibaba.excel.parameter; package com.alibaba.excel.parameter;
import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.OutputStream; import java.io.OutputStream;
import com.alibaba.excel.support.ExcelTypeEnum;
/** /**
* Created by jipengfei on 17/2/19. * Created by jipengfei on 17/2/19.
*/ */

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

@ -6,16 +6,15 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
/** /**
*
* @author jipengfei * @author jipengfei
*/ */
public enum ExcelTypeEnum { public enum ExcelTypeEnum {
XLS(".xls"),
XLSX(".xlsx"); XLS(".xls"), XLSX(".xlsx");
// CSV(".csv");
private String value; private String value;
private ExcelTypeEnum(String value) { ExcelTypeEnum(String value) {
this.setValue(value); this.setValue(value);
} }
@ -26,18 +25,20 @@ public enum ExcelTypeEnum {
public void setValue(String value) { public void setValue(String value) {
this.value = value; this.value = value;
} }
public static ExcelTypeEnum valueOf(InputStream inputStream){ public static ExcelTypeEnum valueOf(InputStream inputStream){
try { try {
InputStream in = FileMagic.prepareToCheckMagic(inputStream); if (!inputStream.markSupported()) {
FileMagic fileMagic = FileMagic.valueOf(in); return null;
}
FileMagic fileMagic = FileMagic.valueOf(inputStream);
if(FileMagic.OLE2.equals(fileMagic)){ if(FileMagic.OLE2.equals(fileMagic)){
return XLS; return XLS;
} }
if(FileMagic.OOXML.equals(fileMagic)){ if(FileMagic.OOXML.equals(fileMagic)){
return XLSX; return XLSX;
} }
throw new IllegalArgumentException("excelTypeEnum can not null"); return null;
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

340
src/main/java/com/alibaba/excel/util/CollectionUtils.java

@ -0,0 +1,340 @@
package com.alibaba.excel.util;
import java.util.*;
/**
* Miscellaneous collection utility methods.
* Mainly for internal use within the framework.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @author Arjen Poutsma
* @since 1.1.3
*/
public abstract class CollectionUtils {
/**
* Return {@code true} if the supplied Collection is {@code null} or empty.
* Otherwise, return {@code false}.
* @param collection the Collection to check
* @return whether the given Collection is empty
*/
public static boolean isEmpty(Collection<?> collection) {
return (collection == null || collection.isEmpty());
}
/**
* Return {@code true} if the supplied Map is {@code null} or empty.
* Otherwise, return {@code false}.
* @param map the Map to check
* @return whether the given Map is empty
*/
public static boolean isEmpty(Map<?, ?> map) {
return (map == null || map.isEmpty());
}
/**
* Convert the supplied array into a List. A primitive array gets converted
* into a List of the appropriate wrapper type.
* <p><b>NOTE:</b> Generally prefer the standard {@link Arrays#asList} method.
* This {@code arrayToList} method is just meant to deal with an incoming Object
* value that might be an {@code Object[]} or a primitive array at runtime.
* <p>A {@code null} source value will be converted to an empty List.
* @param source the (potentially primitive) array
* @return the converted List result
* @see ObjectUtils#toObjectArray(Object)
* @see Arrays#asList(Object[])
*/
@SuppressWarnings("rawtypes")
public static List arrayToList(Object source) {
return Arrays.asList(ObjectUtils.toObjectArray(source));
}
/**
* Merge the given array into the given Collection.
* @param array the array to merge (may be {@code null})
* @param collection the target Collection to merge the array into
*/
@SuppressWarnings("unchecked")
public static <E> void mergeArrayIntoCollection(Object array, Collection<E> collection) {
if (collection == null) {
throw new IllegalArgumentException("Collection must not be null");
}
Object[] arr = ObjectUtils.toObjectArray(array);
for (Object elem : arr) {
collection.add((E) elem);
}
}
/**
* Merge the given Properties instance into the given Map,
* copying all properties (key-value pairs) over.
* <p>Uses {@code Properties.propertyNames()} to even catch
* default properties linked into the original Properties instance.
* @param props the Properties instance to merge (may be {@code null})
* @param map the target Map to merge the properties into
*/
@SuppressWarnings("unchecked")
public static <K, V> void mergePropertiesIntoMap(Properties props, Map<K, V> map) {
if (map == null) {
throw new IllegalArgumentException("Map must not be null");
}
if (props != null) {
for (Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) {
String key = (String) en.nextElement();
Object value = props.get(key);
if (value == null) {
// Allow for defaults fallback or potentially overridden accessor...
value = props.getProperty(key);
}
map.put((K) key, (V) value);
}
}
}
/**
* Check whether the given Iterator contains the given element.
* @param iterator the Iterator to check
* @param element the element to look for
* @return {@code true} if found, {@code false} else
*/
public static boolean contains(Iterator<?> iterator, Object element) {
if (iterator != null) {
while (iterator.hasNext()) {
Object candidate = iterator.next();
if (ObjectUtils.nullSafeEquals(candidate, element)) {
return true;
}
}
}
return false;
}
/**
* Check whether the given Enumeration contains the given element.
* @param enumeration the Enumeration to check
* @param element the element to look for
* @return {@code true} if found, {@code false} else
*/
public static boolean contains(Enumeration<?> enumeration, Object element) {
if (enumeration != null) {
while (enumeration.hasMoreElements()) {
Object candidate = enumeration.nextElement();
if (ObjectUtils.nullSafeEquals(candidate, element)) {
return true;
}
}
}
return false;
}
/**
* Check whether the given Collection contains the given element instance.
* <p>Enforces the given instance to be present, rather than returning
* {@code true} for an equal element as well.
* @param collection the Collection to check
* @param element the element to look for
* @return {@code true} if found, {@code false} else
*/
public static boolean containsInstance(Collection<?> collection, Object element) {
if (collection != null) {
for (Object candidate : collection) {
if (candidate == element) {
return true;
}
}
}
return false;
}
/**
* Return {@code true} if any element in '{@code candidates}' is
* contained in '{@code source}'; otherwise returns {@code false}.
* @param source the source Collection
* @param candidates the candidates to search for
* @return whether any of the candidates has been found
*/
public static boolean containsAny(Collection<?> source, Collection<?> candidates) {
if (isEmpty(source) || isEmpty(candidates)) {
return false;
}
for (Object candidate : candidates) {
if (source.contains(candidate)) {
return true;
}
}
return false;
}
/**
* Return the first element in '{@code candidates}' that is contained in
* '{@code source}'. If no element in '{@code candidates}' is present in
* '{@code source}' returns {@code null}. Iteration order is
* {@link Collection} implementation specific.
* @param source the source Collection
* @param candidates the candidates to search for
* @return the first present object, or {@code null} if not found
*/
@SuppressWarnings("unchecked")
public static <E> E findFirstMatch(Collection<?> source, Collection<E> candidates) {
if (isEmpty(source) || isEmpty(candidates)) {
return null;
}
for (Object candidate : candidates) {
if (source.contains(candidate)) {
return (E) candidate;
}
}
return null;
}
/**
* Find a single value of the given type in the given Collection.
* @param collection the Collection to search
* @param type the type to look for
* @return a value of the given type found if there is a clear match,
* or {@code null} if none or more than one such value found
*/
@SuppressWarnings("unchecked")
public static <T> T findValueOfType(Collection<?> collection, Class<T> type) {
if (isEmpty(collection)) {
return null;
}
T value = null;
for (Object element : collection) {
if (type == null || type.isInstance(element)) {
if (value != null) {
// More than one value found... no clear single value.
return null;
}
value = (T) element;
}
}
return value;
}
/**
* Find a single value of one of the given types in the given Collection:
* searching the Collection for a value of the first type, then
* searching for a value of the second type, etc.
* @param collection the collection to search
* @param types the types to look for, in prioritized order
* @return a value of one of the given types found if there is a clear match,
* or {@code null} if none or more than one such value found
*/
public static Object findValueOfType(Collection<?> collection, Class<?>[] types) {
if (isEmpty(collection) || ObjectUtils.isEmpty(types)) {
return null;
}
for (Class<?> type : types) {
Object value = findValueOfType(collection, type);
if (value != null) {
return value;
}
}
return null;
}
/**
* Determine whether the given Collection only contains a single unique object.
* @param collection the Collection to check
* @return {@code true} if the collection contains a single reference or
* multiple references to the same instance, {@code false} else
*/
public static boolean hasUniqueObject(Collection<?> collection) {
if (isEmpty(collection)) {
return false;
}
boolean hasCandidate = false;
Object candidate = null;
for (Object elem : collection) {
if (!hasCandidate) {
hasCandidate = true;
candidate = elem;
}
else if (candidate != elem) {
return false;
}
}
return true;
}
/**
* Find the common element type of the given Collection, if any.
* @param collection the Collection to check
* @return the common element type, or {@code null} if no clear
* common type has been found (or the collection was empty)
*/
public static Class<?> findCommonElementType(Collection<?> collection) {
if (isEmpty(collection)) {
return null;
}
Class<?> candidate = null;
for (Object val : collection) {
if (val != null) {
if (candidate == null) {
candidate = val.getClass();
}
else if (candidate != val.getClass()) {
return null;
}
}
}
return candidate;
}
/**
* Marshal the elements from the given enumeration into an array of the given type.
* Enumeration elements must be assignable to the type of the given array. The array
* returned will be a different instance than the array given.
*/
public static <A, E extends A> A[] toArray(Enumeration<E> enumeration, A[] array) {
ArrayList<A> elements = new ArrayList<A>();
while (enumeration.hasMoreElements()) {
elements.add(enumeration.nextElement());
}
return elements.toArray(array);
}
/**
* Adapt an enumeration to an iterator.
* @param enumeration the enumeration
* @return the iterator
*/
public static <E> Iterator<E> toIterator(Enumeration<E> enumeration) {
return new EnumerationIterator<E>(enumeration);
}
/**
* Iterator wrapping an Enumeration.
*/
private static class EnumerationIterator<E> implements Iterator<E> {
private final Enumeration<E> enumeration;
public EnumerationIterator(Enumeration<E> enumeration) {
this.enumeration = enumeration;
}
@Override
public boolean hasNext() {
return this.enumeration.hasMoreElements();
}
@Override
public E next() {
return this.enumeration.nextElement();
}
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not supported");
}
}
}

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

@ -1,14 +1,15 @@
package com.alibaba.excel.util; package com.alibaba.excel.util;
import com.alibaba.excel.metadata.IndexValue;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Stack; import java.util.Stack;
import com.alibaba.excel.metadata.IndexValue;
/** /**
* 去除空Cell * 去除空Cell
* @author jipengfei * @author jipengfei
* @date 2017/04/13
*/ */
public class IndexValueConverter { public class IndexValueConverter {
public static List<String> converter(List<IndexValue> i_list) { public static List<String> converter(List<IndexValue> i_list) {

945
src/main/java/com/alibaba/excel/util/ObjectUtils.java

@ -0,0 +1,945 @@
package com.alibaba.excel.util;
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
/**
* Miscellaneous object utility methods.
*
* <p>Mainly for internal use within the framework.
*
* <p>Thanks to Alex Ruiz for contributing several enhancements to this class!
*
* @author Juergen Hoeller
* @author Keith Donald
* @author Rod Johnson
* @author Rob Harrop
* @author Chris Beams
* @author Sam Brannen
* @since 19.03.2004
* @see CollectionUtils
*/
public abstract class ObjectUtils {
private static final int INITIAL_HASH = 7;
private static final int MULTIPLIER = 31;
private static final String EMPTY_STRING = "";
private static final String NULL_STRING = "null";
private static final String ARRAY_START = "{";
private static final String ARRAY_END = "}";
private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
/**
* Return whether the given throwable is a checked exception:
* that is, neither a RuntimeException nor an Error.
* @param ex the throwable to check
* @return whether the throwable is a checked exception
* @see Exception
* @see RuntimeException
* @see Error
*/
public static boolean isCheckedException(Throwable ex) {
return !(ex instanceof RuntimeException || ex instanceof Error);
}
/**
* Check whether the given exception is compatible with the specified
* exception types, as declared in a throws clause.
* @param ex the exception to check
* @param declaredExceptions the exception types declared in the throws clause
* @return whether the given exception is compatible
*/
public static boolean isCompatibleWithThrowsClause(Throwable ex, Class<?>... declaredExceptions) {
if (!isCheckedException(ex)) {
return true;
}
if (declaredExceptions != null) {
for (Class<?> declaredException : declaredExceptions) {
if (declaredException.isInstance(ex)) {
return true;
}
}
}
return false;
}
/**
* Determine whether the given object is an array:
* either an Object array or a primitive array.
* @param obj the object to check
*/
public static boolean isArray(Object obj) {
return (obj != null && obj.getClass().isArray());
}
/**
* Determine whether the given array is empty:
* i.e. {@code null} or of zero length.
* @param array the array to check
* @see #isEmpty(Object)
*/
public static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
/**
* Determine whether the given object is empty.
* <p>This method supports the following object types.
* <ul>
* <li>{@code Array}: considered empty if its length is zero</li>
* <li>{@link CharSequence}: considered empty if its length is zero</li>
* <li>{@link Collection}: delegates to {@link Collection#isEmpty()}</li>
* <li>{@link Map}: delegates to {@link Map#isEmpty()}</li>
* </ul>
* <p>If the given object is non-null and not one of the aforementioned
* supported types, this method returns {@code false}.
* @param obj the object to check
* @return {@code true} if the object is {@code null} or <em>empty</em>
* @since 4.2
* @see ObjectUtils#isEmpty(Object[])
* @see StringUtils#hasLength(CharSequence)
* @see StringUtils#isEmpty(Object)
* @see CollectionUtils#isEmpty(Collection)
* @see CollectionUtils#isEmpty(Map)
*/
@SuppressWarnings("rawtypes")
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof CharSequence) {
return ((CharSequence) obj).length() == 0;
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
}
// else
return false;
}
/**
* Check whether the given array contains the given element.
* @param array the array to check (may be {@code null},
* in which case the return value will always be {@code false})
* @param element the element to check for
* @return whether the element has been found in the given array
*/
public static boolean containsElement(Object[] array, Object element) {
if (array == null) {
return false;
}
for (Object arrayEle : array) {
if (nullSafeEquals(arrayEle, element)) {
return true;
}
}
return false;
}
/**
* Check whether the given array of enum constants contains a constant with the given name,
* ignoring case when determining a match.
* @param enumValues the enum values to check, typically the product of a call to MyEnum.values()
* @param constant the constant name to find (must not be null or empty string)
* @return whether the constant has been found in the given array
*/
public static boolean containsConstant(Enum<?>[] enumValues, String constant) {
return containsConstant(enumValues, constant, false);
}
/**
* Check whether the given array of enum constants contains a constant with the given name.
* @param enumValues the enum values to check, typically the product of a call to MyEnum.values()
* @param constant the constant name to find (must not be null or empty string)
* @param caseSensitive whether case is significant in determining a match
* @return whether the constant has been found in the given array
*/
public static boolean containsConstant(Enum<?>[] enumValues, String constant, boolean caseSensitive) {
for (Enum<?> candidate : enumValues) {
if (caseSensitive ?
candidate.toString().equals(constant) :
candidate.toString().equalsIgnoreCase(constant)) {
return true;
}
}
return false;
}
/**
* Case insensitive alternative to {@link Enum#valueOf(Class, String)}.
* @param <E> the concrete Enum type
* @param enumValues the array of all Enum constants in question, usually per Enum.values()
* @param constant the constant to get the enum value of
* @throws IllegalArgumentException if the given constant is not found in the given array
* of enum values. Use {@link #containsConstant(Enum[], String)} as a guard to avoid this exception.
*/
public static <E extends Enum<?>> E caseInsensitiveValueOf(E[] enumValues, String constant) {
for (E candidate : enumValues) {
if (candidate.toString().equalsIgnoreCase(constant)) {
return candidate;
}
}
throw new IllegalArgumentException(
String.format("constant [%s] does not exist in enum type %s",
constant, enumValues.getClass().getComponentType().getName()));
}
/**
* Append the given object to the given array, returning a new array
* consisting of the input array contents plus the given object.
* @param array the array to append to (can be {@code null})
* @param obj the object to append
* @return the new array (of the same component type; never {@code null})
*/
public static <A, O extends A> A[] addObjectToArray(A[] array, O obj) {
Class<?> compType = Object.class;
if (array != null) {
compType = array.getClass().getComponentType();
}
else if (obj != null) {
compType = obj.getClass();
}
int newArrLength = (array != null ? array.length + 1 : 1);
@SuppressWarnings("unchecked")
A[] newArr = (A[]) Array.newInstance(compType, newArrLength);
if (array != null) {
System.arraycopy(array, 0, newArr, 0, array.length);
}
newArr[newArr.length - 1] = obj;
return newArr;
}
/**
* Convert the given array (which may be a primitive array) to an
* object array (if necessary of primitive wrapper objects).
* <p>A {@code null} source value will be converted to an
* empty Object array.
* @param source the (potentially primitive) array
* @return the corresponding object array (never {@code null})
* @throws IllegalArgumentException if the parameter is not an array
*/
public static Object[] toObjectArray(Object source) {
if (source instanceof Object[]) {
return (Object[]) source;
}
if (source == null) {
return new Object[0];
}
if (!source.getClass().isArray()) {
throw new IllegalArgumentException("Source is not an array: " + source);
}
int length = Array.getLength(source);
if (length == 0) {
return new Object[0];
}
Class<?> wrapperType = Array.get(source, 0).getClass();
Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
for (int i = 0; i < length; i++) {
newArray[i] = Array.get(source, i);
}
return newArray;
}
//---------------------------------------------------------------------
// Convenience methods for content-based equality/hash-code handling
//---------------------------------------------------------------------
/**
* Determine if the given objects are equal, returning {@code true} if
* both are {@code null} or {@code false} if only one is {@code null}.
* <p>Compares arrays with {@code Arrays.equals}, performing an equality
* check based on the array elements rather than the array reference.
* @param o1 first Object to compare
* @param o2 second Object to compare
* @return whether the given objects are equal
* @see Object#equals(Object)
* @see Arrays#equals
*/
public static boolean nullSafeEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
if (o1.getClass().isArray() && o2.getClass().isArray()) {
return arrayEquals(o1, o2);
}
return false;
}
/**
* Compare the given arrays with {@code Arrays.equals}, performing an equality
* check based on the array elements rather than the array reference.
* @param o1 first array to compare
* @param o2 second array to compare
* @return whether the given objects are equal
* @see #nullSafeEquals(Object, Object)
* @see Arrays#equals
*/
private static boolean arrayEquals(Object o1, Object o2) {
if (o1 instanceof Object[] && o2 instanceof Object[]) {
return Arrays.equals((Object[]) o1, (Object[]) o2);
}
if (o1 instanceof boolean[] && o2 instanceof boolean[]) {
return Arrays.equals((boolean[]) o1, (boolean[]) o2);
}
if (o1 instanceof byte[] && o2 instanceof byte[]) {
return Arrays.equals((byte[]) o1, (byte[]) o2);
}
if (o1 instanceof char[] && o2 instanceof char[]) {
return Arrays.equals((char[]) o1, (char[]) o2);
}
if (o1 instanceof double[] && o2 instanceof double[]) {
return Arrays.equals((double[]) o1, (double[]) o2);
}
if (o1 instanceof float[] && o2 instanceof float[]) {
return Arrays.equals((float[]) o1, (float[]) o2);
}
if (o1 instanceof int[] && o2 instanceof int[]) {
return Arrays.equals((int[]) o1, (int[]) o2);
}
if (o1 instanceof long[] && o2 instanceof long[]) {
return Arrays.equals((long[]) o1, (long[]) o2);
}
if (o1 instanceof short[] && o2 instanceof short[]) {
return Arrays.equals((short[]) o1, (short[]) o2);
}
return false;
}
/**
* Return as hash code for the given object; typically the value of
* {@code Object#hashCode()}}. If the object is an array,
* this method will delegate to any of the {@code nullSafeHashCode}
* methods for arrays in this class. If the object is {@code null},
* this method returns 0.
* @see Object#hashCode()
* @see #nullSafeHashCode(Object[])
* @see #nullSafeHashCode(boolean[])
* @see #nullSafeHashCode(byte[])
* @see #nullSafeHashCode(char[])
* @see #nullSafeHashCode(double[])
* @see #nullSafeHashCode(float[])
* @see #nullSafeHashCode(int[])
* @see #nullSafeHashCode(long[])
* @see #nullSafeHashCode(short[])
*/
public static int nullSafeHashCode(Object obj) {
if (obj == null) {
return 0;
}
if (obj.getClass().isArray()) {
if (obj instanceof Object[]) {
return nullSafeHashCode((Object[]) obj);
}
if (obj instanceof boolean[]) {
return nullSafeHashCode((boolean[]) obj);
}
if (obj instanceof byte[]) {
return nullSafeHashCode((byte[]) obj);
}
if (obj instanceof char[]) {
return nullSafeHashCode((char[]) obj);
}
if (obj instanceof double[]) {
return nullSafeHashCode((double[]) obj);
}
if (obj instanceof float[]) {
return nullSafeHashCode((float[]) obj);
}
if (obj instanceof int[]) {
return nullSafeHashCode((int[]) obj);
}
if (obj instanceof long[]) {
return nullSafeHashCode((long[]) obj);
}
if (obj instanceof short[]) {
return nullSafeHashCode((short[]) obj);
}
}
return obj.hashCode();
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(Object[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (Object element : array) {
hash = MULTIPLIER * hash + nullSafeHashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(boolean[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (boolean element : array) {
hash = MULTIPLIER * hash + hashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(byte[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (byte element : array) {
hash = MULTIPLIER * hash + element;
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(char[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (char element : array) {
hash = MULTIPLIER * hash + element;
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(double[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (double element : array) {
hash = MULTIPLIER * hash + hashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(float[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (float element : array) {
hash = MULTIPLIER * hash + hashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(int[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (int element : array) {
hash = MULTIPLIER * hash + element;
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(long[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (long element : array) {
hash = MULTIPLIER * hash + hashCode(element);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(short[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
for (short element : array) {
hash = MULTIPLIER * hash + element;
}
return hash;
}
/**
* Return the same value as {@link Boolean#hashCode()}}.
* @see Boolean#hashCode()
*/
public static int hashCode(boolean bool) {
return (bool ? 1231 : 1237);
}
/**
* Return the same value as {@link Double#hashCode()}}.
* @see Double#hashCode()
*/
public static int hashCode(double dbl) {
return hashCode(Double.doubleToLongBits(dbl));
}
/**
* Return the same value as {@link Float#hashCode()}}.
* @see Float#hashCode()
*/
public static int hashCode(float flt) {
return Float.floatToIntBits(flt);
}
/**
* Return the same value as {@link Long#hashCode()}}.
* @see Long#hashCode()
*/
public static int hashCode(long lng) {
return (int) (lng ^ (lng >>> 32));
}
//---------------------------------------------------------------------
// Convenience methods for toString output
//---------------------------------------------------------------------
/**
* Return a String representation of an object's overall identity.
* @param obj the object (may be {@code null})
* @return the object's identity as String representation,
* or an empty String if the object was {@code null}
*/
public static String identityToString(Object obj) {
if (obj == null) {
return EMPTY_STRING;
}
return obj.getClass().getName() + "@" + getIdentityHexString(obj);
}
/**
* Return a hex String form of an object's identity hash code.
* @param obj the object
* @return the object's identity code in hex notation
*/
public static String getIdentityHexString(Object obj) {
return Integer.toHexString(System.identityHashCode(obj));
}
/**
* Return a content-based String representation if {@code obj} is
* not {@code null}; otherwise returns an empty String.
* <p>Differs from {@link #nullSafeToString(Object)} in that it returns
* an empty String rather than "null" for a {@code null} value.
* @param obj the object to build a display String for
* @return a display String representation of {@code obj}
* @see #nullSafeToString(Object)
*/
public static String getDisplayString(Object obj) {
if (obj == null) {
return EMPTY_STRING;
}
return nullSafeToString(obj);
}
/**
* Determine the class name for the given object.
* <p>Returns {@code "null"} if {@code obj} is {@code null}.
* @param obj the object to introspect (may be {@code null})
* @return the corresponding class name
*/
public static String nullSafeClassName(Object obj) {
return (obj != null ? obj.getClass().getName() : NULL_STRING);
}
/**
* Return a String representation of the specified Object.
* <p>Builds a String representation of the contents in case of an array.
* Returns {@code "null"} if {@code obj} is {@code null}.
* @param obj the object to build a String representation for
* @return a String representation of {@code obj}
*/
public static String nullSafeToString(Object obj) {
if (obj == null) {
return NULL_STRING;
}
if (obj instanceof String) {
return (String) obj;
}
if (obj instanceof Object[]) {
return nullSafeToString((Object[]) obj);
}
if (obj instanceof boolean[]) {
return nullSafeToString((boolean[]) obj);
}
if (obj instanceof byte[]) {
return nullSafeToString((byte[]) obj);
}
if (obj instanceof char[]) {
return nullSafeToString((char[]) obj);
}
if (obj instanceof double[]) {
return nullSafeToString((double[]) obj);
}
if (obj instanceof float[]) {
return nullSafeToString((float[]) obj);
}
if (obj instanceof int[]) {
return nullSafeToString((int[]) obj);
}
if (obj instanceof long[]) {
return nullSafeToString((long[]) obj);
}
if (obj instanceof short[]) {
return nullSafeToString((short[]) obj);
}
String str = obj.toString();
return (str != null ? str : EMPTY_STRING);
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(Object[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(String.valueOf(array[i]));
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(boolean[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(byte[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(char[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append("'").append(array[i]).append("'");
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(double[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(float[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(int[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(long[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(short[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
}

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

@ -5,6 +5,7 @@ import java.io.File;
/** /**
* *
* @author jipengfei * @author jipengfei
* @date 2017/06/22
*/ */
public class POITempFile { public class POITempFile {

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 {

10
src/main/java/com/alibaba/excel/util/RowUtil.java

@ -0,0 +1,10 @@
package com.alibaba.excel.util;
import org.apache.poi.ss.usermodel.Workbook;
public class RowUtil {
//public static int computeNextRow(Workbook workbook,int startRow){
//
//}
}

1221
src/main/java/com/alibaba/excel/util/StringUtils.java

File diff suppressed because it is too large Load Diff

68
src/main/java/com/alibaba/excel/util/StyleUtil.java

@ -0,0 +1,68 @@
package com.alibaba.excel.util;
import org.apache.poi.ss.usermodel.*;
import java.util.Map;
/**
* @author jipengfei
* @date 2017/03/15
*/
public class StyleUtil {
/**
*
* @param workbook
* @return
*/
public static CellStyle buildDefaultCellStyle(Workbook workbook) {
CellStyle newCellStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short)14);
font.setBold(true);
newCellStyle.setFont(font);
newCellStyle.setWrapText(true);
newCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
newCellStyle.setAlignment(HorizontalAlignment.CENTER);
newCellStyle.setLocked(true);
newCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
newCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
newCellStyle.setBorderBottom(BorderStyle.THIN);
newCellStyle.setBorderLeft(BorderStyle.THIN);
return newCellStyle;
}
/**
*
* @param workbook
* @param f
* @param indexedColors
* @return
*/
public static CellStyle buildCellStyle(Workbook workbook, com.alibaba.excel.metadata.Font f,
IndexedColors indexedColors) {
CellStyle cellStyle = buildDefaultCellStyle(workbook);
if (f != null) {
Font font = workbook.createFont();
font.setFontName(f.getFontName());
font.setFontHeightInPoints(f.getFontHeightInPoints());
font.setBold(f.isBold());
cellStyle.setFont(font);
}
if (indexedColors != null) {
cellStyle.setFillForegroundColor(indexedColors.getIndex());
}
return cellStyle;
}
public static Sheet buildSheetStyle(Sheet currentSheet, Map<Integer, Integer> sheetWidthMap){
currentSheet.setDefaultColumnWidth(20);
for (Map.Entry<Integer, Integer> entry : sheetWidthMap.entrySet()) {
currentSheet.setColumnWidth(entry.getKey(), entry.getValue());
}
return currentSheet;
}
}

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

@ -1,27 +1,30 @@
package com.alibaba.excel.util; package com.alibaba.excel.util;
import com.alibaba.excel.metadata.ExcelColumnProperty;
import com.alibaba.excel.metadata.ExcelHeadProperty;
import net.sf.cglib.beans.BeanMap;
import org.apache.poi.hssf.usermodel.HSSFDateUtil; 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;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
* @author jipengfei * @author jipengfei
* @date 2017/03/15
*/ */
public class TypeUtil { public class TypeUtil {
private static List<SimpleDateFormat> DATE_FORMAT_LIST = new ArrayList<SimpleDateFormat>(4); private static List<String> DATE_FORMAT_LIST = new ArrayList<String>(4);
static { static {
DATE_FORMAT_LIST.add(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")); DATE_FORMAT_LIST.add("yyyy/MM/dd HH:mm:ss");
DATE_FORMAT_LIST.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); DATE_FORMAT_LIST.add("yyyy-MM-dd HH:mm:ss");
DATE_FORMAT_LIST.add("yyyyMMdd HH:mm:ss");
} }
private static int getCountOfChar(String value, char c) { private static int getCountOfChar(String value, char c) {
@ -39,9 +42,9 @@ public class TypeUtil {
} }
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 (!StringUtils.isEmpty(value)) {
if (String.class.equals(field.getType())) { if (Float.class.equals(field.getType())) {
return TypeUtil.formatFloat(value); return Float.parseFloat(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);
@ -80,6 +83,9 @@ public class TypeUtil {
if (BigDecimal.class.equals(field.getType())) { if (BigDecimal.class.equals(field.getType())) {
return new BigDecimal(value); return new BigDecimal(value);
} }
if(String.class.equals(field.getType())){
return formatFloat(value);
}
} }
return null; return null;
@ -106,6 +112,18 @@ public class TypeUtil {
return false; return false;
} }
public static Boolean isNum(Object cellValue) {
if (cellValue instanceof Integer
|| cellValue instanceof Double
|| cellValue instanceof Short
|| cellValue instanceof Long
|| cellValue instanceof Float
|| cellValue instanceof BigDecimal) {
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);
@ -113,9 +131,9 @@ public class TypeUtil {
} }
public static Date getSimpleDateFormatDate(String value, String format) { public static Date getSimpleDateFormatDate(String value, String format) {
if (isNotEmpty(value)) { if (!StringUtils.isEmpty(value)) {
Date date = null; Date date = null;
if (isNotEmpty(format)) { if (!StringUtils.isEmpty(format)) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
try { try {
date = simpleDateFormat.parse(value); date = simpleDateFormat.parse(value);
@ -123,9 +141,10 @@ public class TypeUtil {
} catch (ParseException e) { } catch (ParseException e) {
} }
} }
for (SimpleDateFormat dateFormat : DATE_FORMAT_LIST) { for (String dateFormat : DATE_FORMAT_LIST) {
try { try {
date = dateFormat.parse(value); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
date = simpleDateFormat.parse(value);
} catch (ParseException e) { } catch (ParseException e) {
} }
if (date != null) { if (date != null) {
@ -140,16 +159,6 @@ public class TypeUtil {
} }
public static Boolean isNotEmpty(String value) {
if (value == null) {
return false;
}
if (value.trim().equals("")) {
return false;
}
return true;
}
public static String formatFloat(String value) { public static String formatFloat(String value) {
if (null != value && value.contains(".")) { if (null != value && value.contains(".")) {
@ -190,12 +199,40 @@ public class TypeUtil {
} }
public static String formatDate(Date cellValue, String format) { public static String formatDate(Date cellValue, String format) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); SimpleDateFormat simpleDateFormat;
if(!StringUtils.isEmpty(format)) {
simpleDateFormat = new SimpleDateFormat(format);
}else {
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
return simpleDateFormat.format(cellValue); return simpleDateFormat.format(cellValue);
} }
public static void main(String[] args) { public static String getFieldStringValue(BeanMap beanMap, String fieldName, String format) {
System.out.println(new Date().toString()); String cellValue = null;
Object value = beanMap.get(fieldName);
if (value != null) {
if (value instanceof Date) {
cellValue = TypeUtil.formatDate((Date)value, format);
} else {
cellValue = value.toString();
}
}
return cellValue;
}
public static Map getFieldValues(List<String> stringList, ExcelHeadProperty excelHeadProperty, Boolean use1904WindowDate) {
Map map = new HashMap();
for (int i = 0; i < stringList.size(); i++) {
ExcelColumnProperty columnProperty = excelHeadProperty.getExcelColumnProperty(i);
if (columnProperty != null) {
Object value = TypeUtil.convert(stringList.get(i), columnProperty.getField(),
columnProperty.getFormat(), use1904WindowDate);
if (value != null) {
map.put(columnProperty.getField().getName(),value);
}
}
}
return map;
} }
} }

75
src/main/java/com/alibaba/excel/util/WorkBookUtil.java

@ -0,0 +1,75 @@
package com.alibaba.excel.util;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import static com.alibaba.excel.util.StyleUtil.buildSheetStyle;
/**
*
* @author jipengfei
*/
public class WorkBookUtil {
public static Workbook createWorkBook(InputStream templateInputStream, ExcelTypeEnum excelType) throws IOException {
Workbook workbook;
if (ExcelTypeEnum.XLS.equals(excelType)) {
workbook = (templateInputStream == null) ? new HSSFWorkbook() : new HSSFWorkbook(
new POIFSFileSystem(templateInputStream));
} else {
workbook = (templateInputStream == null) ? new SXSSFWorkbook(500) : new SXSSFWorkbook(
new XSSFWorkbook(templateInputStream));
}
return workbook;
}
public static Sheet createOrGetSheet(Workbook workbook, com.alibaba.excel.metadata.Sheet sheet) {
Sheet sheet1 = null;
try {
try {
sheet1 = workbook.getSheetAt(sheet.getSheetNo()-1);
} catch (Exception e) {
}
if (null == sheet1) {
sheet1 = createSheet(workbook, sheet);
buildSheetStyle(sheet1,sheet.getColumnWidthMap());
}
} catch (Exception e) {
throw new RuntimeException("constructCurrentSheet error", e);
}
return sheet1;
}
public static Sheet createSheet(Workbook workbook, com.alibaba.excel.metadata.Sheet sheet) {
return workbook.createSheet(sheet.getSheetName() != null ? sheet.getSheetName() : sheet.getSheetNo() + "");
}
public static Row createRow(Sheet sheet, int rowNum) {
return sheet.createRow(rowNum);
}
public static Cell createCell(Row row, int colNum, CellStyle cellStyle, String cellValue) {
return createCell(row, colNum, cellStyle, cellValue, false);
}
public static Cell createCell(Row row, int colNum, CellStyle cellStyle, Object cellValue, Boolean isNum) {
Cell cell = row.createCell(colNum);
cell.setCellStyle(cellStyle);
if (null != cellValue) {
if (isNum) {
cell.setCellValue(Double.parseDouble(cellValue.toString()));
} else {
cell.setCellValue(cellValue.toString());
}
}
return cell;
}
}

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

@ -2,30 +2,52 @@ package com.alibaba.excel.write;
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 java.io.InputStream;
import java.io.OutputStream;
import java.util.List; import java.util.List;
/** /**
*
* @author jipengfei * @author jipengfei
*/ */
public interface ExcelBuilder { public interface ExcelBuilder {
void init(InputStream templateInputStream, OutputStream out, ExcelTypeEnum excelType, boolean needHead); /**
* workBook increase data
*
* @param data List<List<String>> or List<? extends BaseRowModel>
* @param startRow Start row number
*/
void addContent(List data, int startRow); void addContent(List data, int startRow);
/**
* WorkBook increase data
*
* @param data List<List<String>> or List<? extends BaseRowModel>
* @param sheetParam Write the sheet
*/
void addContent(List data, Sheet sheetParam); void addContent(List data, Sheet sheetParam);
/**
* WorkBook increase data
*
* @param data List<List<String>> or List<? extends BaseRowModel>
* @param sheetParam Write the sheet
* @param table Write the table
*/
void addContent(List data, Sheet sheetParam, Table table); void addContent(List data, Sheet sheetParam, Table table);
/**
* Creates new cell range. Indexes are zero-based.
*
* @param firstRow Index of first row
* @param lastRow Index of last row (inclusive), must be equal to or larger than {@code firstRow}
* @param firstCol Index of first column
* @param lastCol Index of last column (inclusive), must be equal to or larger than {@code firstCol}
*/
void merge(int firstRow, int lastRow, int firstCol, int lastCol);
/**
* Close io
*/
void finish(); void finish();
} }

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

@ -1,38 +1,42 @@
package com.alibaba.excel.write; package com.alibaba.excel.write;
import com.alibaba.excel.context.GenerateContext; import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.context.GenerateContextImpl; import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.BaseRowModel; import com.alibaba.excel.metadata.BaseRowModel;
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.CollectionUtils;
import com.alibaba.excel.util.POITempFile; import com.alibaba.excel.util.POITempFile;
import com.alibaba.excel.util.TypeUtil; import com.alibaba.excel.util.TypeUtil;
import org.apache.commons.beanutils.BeanUtilsBean; import com.alibaba.excel.util.WorkBookUtil;
import org.apache.poi.ss.usermodel.Cell; import net.sf.cglib.beans.BeanMap;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Date;
import java.util.List; 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 WriteContext context;
@Override public ExcelBuilderImpl(InputStream templateInputStream,
public void init(InputStream templateInputStream, OutputStream out, ExcelTypeEnum excelType, boolean needHead) { OutputStream out,
ExcelTypeEnum excelType,
boolean needHead) {
try { try {
//初始化时候创建临时缓存目录,用于规避POI在并发写bug //初始化时候创建临时缓存目录,用于规避POI在并发写bug
POITempFile.createPOIFilesDirectory(); POITempFile.createPOIFilesDirectory();
context = new WriteContext(templateInputStream, out, excelType, needHead);
context = new GenerateContextImpl(templateInputStream, out, excelType, needHead);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -40,115 +44,88 @@ public class ExcelBuilderImpl implements ExcelBuilder {
@Override @Override
public void addContent(List data, int startRow) { public void addContent(List data, int startRow) {
if (data != null && data.size() > 0) { if (CollectionUtils.isEmpty(data)) {
int rowNum = context.getCurrentSheet().getLastRowNum(); return;
if (rowNum == 0) { }
Row row = context.getCurrentSheet().getRow(0); int rowNum = context.getCurrentSheet().getLastRowNum();
if (row == null) { if (rowNum == 0) {
if (context.getExcelHeadProperty() == null || !context.needHead()) { Row row = context.getCurrentSheet().getRow(0);
rowNum = -1; if (row == null) {
} if (context.getExcelHeadProperty() == null || !context.needHead()) {
rowNum = -1;
} }
} }
if (rowNum < startRow) { }
rowNum = startRow; if (rowNum < startRow) {
} rowNum = startRow;
for (int i = 0; i < data.size(); i++) { }
int n = i + rowNum + 1; for (int i = 0; i < data.size(); i++) {
int n = i + rowNum + 1;
addOneRowOfDataToExcel(data.get(i), n); addOneRowOfDataToExcel(data.get(i), n);
}
} }
} }
@Override @Override
public void addContent(List data, Sheet sheetParam) { public void addContent(List data, Sheet sheetParam) {
context.buildCurrentSheet(sheetParam); context.currentSheet(sheetParam);
addContent(data, sheetParam.getStartRow()); addContent(data, sheetParam.getStartRow());
} }
@Override @Override
public void addContent(List data, Sheet sheetParam, Table table) { public void addContent(List data, Sheet sheetParam, Table table) {
context.buildCurrentSheet(sheetParam); context.currentSheet(sheetParam);
context.buildTable(table); context.currentTable(table);
addContent(data, sheetParam.getStartRow()); addContent(data, sheetParam.getStartRow());
} }
@Override
public void merge(int firstRow, int lastRow, int firstCol, int lastCol) {
CellRangeAddress cra = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
context.getCurrentSheet().addMergedRegion(cra);
}
@Override @Override
public void finish() { public void finish() {
try { try {
context.getWorkbook().write(context.getOutputStream()); context.getWorkbook().write(context.getOutputStream());
context.getWorkbook().close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); throw new ExcelGenerateException("IO error", e);
} }
} }
private void addOneRowOfDataToExcel(List<Object> oneRowData, Row row) { private void addBasicTypeToExcel(List<Object> oneRowData, Row row) {
if (oneRowData != null && oneRowData.size() > 0) { if (CollectionUtils.isEmpty(oneRowData)) {
for (int i = 0; i < oneRowData.size(); i++) { return;
Cell cell = row.createCell(i); }
cell.setCellStyle(context.getCurrentContentStyle()); for (int i = 0; i < oneRowData.size(); i++) {
Object cellValue = oneRowData.get(i); Object cellValue = oneRowData.get(i);
if (cellValue != null) { WorkBookUtil.createCell(row, i, context.getCurrentContentStyle(), cellValue, TypeUtil.isNum(cellValue));
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);
}
}
} }
} }
private void addOneRowOfDataToExcel(Object oneRowData, Row row) {
private void addJavaObjectToExcel(Object oneRowData, Row row) {
int i = 0; int i = 0;
BeanMap beanMap = BeanMap.create(oneRowData);
for (ExcelColumnProperty excelHeadProperty : context.getExcelHeadProperty().getColumnPropertyList()) { for (ExcelColumnProperty excelHeadProperty : context.getExcelHeadProperty().getColumnPropertyList()) {
Cell cell = row.createCell(i);
BaseRowModel baseRowModel = (BaseRowModel)oneRowData; BaseRowModel baseRowModel = (BaseRowModel)oneRowData;
if (baseRowModel.getStyle(i) != null) { String cellValue = TypeUtil.getFieldStringValue(beanMap, excelHeadProperty.getField().getName(),
cell.setCellStyle(baseRowModel.getStyle(i)); excelHeadProperty.getFormat());
} else { CellStyle cellStyle = baseRowModel.getStyle(i) != null ? baseRowModel.getStyle(i)
cell.setCellStyle(context.getCurrentContentStyle()); : context.getCurrentContentStyle();
} WorkBookUtil.createCell(row, i, cellStyle, cellValue, TypeUtil.isNum(excelHeadProperty.getField()));
String cellValue = null;
try {
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) {
e.printStackTrace();
}
if (TypeUtil.isNotEmpty(cellValue)) {
if (TypeUtil.isNum(excelHeadProperty.getField())) {
cell.setCellValue(Double.parseDouble(cellValue));
} else {
cell.setCellValue(cellValue);
}
} else {
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 = WorkBookUtil.createRow(context.getCurrentSheet(), n);
if (oneRowData instanceof List) { if (oneRowData instanceof List) {
addOneRowOfDataToExcel((List)oneRowData, row); addBasicTypeToExcel((List)oneRowData, row);
} else { } else {
addOneRowOfDataToExcel(oneRowData, row); addJavaObjectToExcel(oneRowData, row);
} }
} }
} }

187
src/test/java/com/alibaba/easyexcel/test/ReadTest.java

@ -0,0 +1,187 @@
package com.alibaba.easyexcel.test;
import com.alibaba.easyexcel.test.listen.ExcelListener;
import com.alibaba.easyexcel.test.model.JavaModel;
import com.alibaba.easyexcel.test.model.JavaModel2;
import com.alibaba.easyexcel.test.util.FileUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class ReadTest {
/**
* 07版本excel读数据量少于1千行数据内部采用回调方法.
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void simpleReadListStringV2007() throws IOException {
InputStream inputStream = FileUtil.getResourcesFileInputStream("2007.xlsx");
List<Object> data = EasyExcelFactory.read(inputStream, new Sheet(1, 0));
inputStream.close();
print(data);
}
/**
* 07版本excel读数据量少于1千行数据自动转成javamodel内部采用回调方法.
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void simpleReadJavaModelV2007() throws IOException {
InputStream inputStream = FileUtil.getResourcesFileInputStream("2007.xlsx");
List<Object> data = EasyExcelFactory.read(inputStream, new Sheet(2, 1,JavaModel.class));
inputStream.close();
print(data);
}
/**
* 07版本excel读数据量大于1千行内部采用回调方法.
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void saxReadListStringV2007() throws IOException {
InputStream inputStream = FileUtil.getResourcesFileInputStream("2007.xlsx");
ExcelListener excelListener = new ExcelListener();
EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1), excelListener);
inputStream.close();
}
/**
* 07版本excel读数据量大于1千行内部采用回调方法.
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void saxReadJavaModelV2007() throws IOException {
InputStream inputStream = FileUtil.getResourcesFileInputStream("2007.xlsx");
ExcelListener excelListener = new ExcelListener();
EasyExcelFactory.readBySax(inputStream, new Sheet(2, 1,JavaModel.class), excelListener);
inputStream.close();
}
/**
* 07版本excel读取sheet
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void saxReadSheetsV2007() throws IOException {
InputStream inputStream = FileUtil.getResourcesFileInputStream("2007.xlsx");
ExcelListener excelListener = new ExcelListener();
ExcelReader excelReader = EasyExcelFactory.getReader(inputStream,excelListener);
List<Sheet> sheets = excelReader.getSheets();
System.out.println();
for (Sheet sheet:sheets) {
if(sheet.getSheetNo() ==1) {
excelReader.read(sheet);
}else if(sheet.getSheetNo() ==2){
sheet.setHeadLineMun(1);
sheet.setClazz(JavaModel.class);
excelReader.read(sheet);
}else if(sheet.getSheetNo() ==3){
sheet.setHeadLineMun(1);
sheet.setClazz(JavaModel2.class);
excelReader.read(sheet);
}
}
inputStream.close();
}
/**
* 03版本excel读数据量少于1千行数据内部采用回调方法.
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void simpleReadListStringV2003() throws IOException {
InputStream inputStream = FileUtil.getResourcesFileInputStream("2003.xls");
List<Object> data = EasyExcelFactory.read(inputStream, new Sheet(1, 0));
inputStream.close();
print(data);
}
/**
* 03版本excel读数据量少于1千行数据转成javamodel内部采用回调方法.
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void simpleReadJavaModelV2003() throws IOException {
InputStream inputStream = FileUtil.getResourcesFileInputStream("2003.xls");
List<Object> data = EasyExcelFactory.read(inputStream, new Sheet(2, 1, JavaModel.class));
inputStream.close();
print(data);
}
/**
* 03版本excel读数据量大于1千行数据内部采用回调方法.
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void saxReadListStringV2003() throws IOException {
InputStream inputStream = FileUtil.getResourcesFileInputStream("2003.xls");
ExcelListener excelListener = new ExcelListener();
EasyExcelFactory.readBySax(inputStream, new Sheet(2, 1), excelListener);
inputStream.close();
}
/**
* 03版本excel读数据量大于1千行数据转成javamodel内部采用回调方法.
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void saxReadJavaModelV2003() throws IOException {
InputStream inputStream = FileUtil.getResourcesFileInputStream("2003.xls");
ExcelListener excelListener = new ExcelListener();
EasyExcelFactory.readBySax(inputStream, new Sheet(2, 1, JavaModel.class), excelListener);
inputStream.close();
}
/**
* 00版本excel读取sheet
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void saxReadSheetsV2003() throws IOException {
InputStream inputStream = FileUtil.getResourcesFileInputStream("2003.xls");
ExcelListener excelListener = new ExcelListener();
ExcelReader excelReader = EasyExcelFactory.getReader(inputStream,excelListener);
List<Sheet> sheets = excelReader.getSheets();
System.out.println();
for (Sheet sheet:sheets) {
if(sheet.getSheetNo() == 1) {
excelReader.read(sheet);
}else {
sheet.setHeadLineMun(2);
sheet.setClazz(JavaModel.class);
excelReader.read(sheet);
}
}
inputStream.close();
}
public void print(List<Object> datas){
int i=0;
for (Object ob:datas) {
System.out.println(i++);
System.out.println(ob);
}
}
}

155
src/test/java/com/alibaba/easyexcel/test/WriteTest.java

@ -0,0 +1,155 @@
package com.alibaba.easyexcel.test;
import com.alibaba.easyexcel.test.model.JavaModel1;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.junit.Test;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import static com.alibaba.easyexcel.test.util.DataUtil.*;
public class WriteTest {
@Test
public void writeV2007() throws IOException {
OutputStream out = new FileOutputStream("/Users/jipengfei/2007.xlsx");
ExcelWriter writer = EasyExcelFactory.getWriter(out);
//写第一个sheet, sheet1 数据全是List<String> 无模型映射关系
Sheet sheet1 = new Sheet(1, 3);
sheet1.setSheetName("第一个sheet");
//设置列宽 设置每列的宽度
Map columnWidth = new HashMap();
columnWidth.put(0,10000);columnWidth.put(1,40000);columnWidth.put(2,10000);columnWidth.put(3,10000);
sheet1.setColumnWidthMap(columnWidth);
sheet1.setHead(createTestListStringHead());
//or 设置自适应宽度
//sheet1.setAutoWidth(Boolean.TRUE);
writer.write1(createTestListObject(), sheet1);
//写第二个sheet sheet2 模型上打有表头的注解,合并单元格
Sheet sheet2 = new Sheet(2, 3, JavaModel1.class, "第二个sheet", null);
sheet2.setTableStyle(createTableStyle());
writer.write(createTestListJavaMode(), sheet2);
//写第三个sheet包含多个table情况
Sheet sheet3 = new Sheet(3, 0);
sheet3.setSheetName("第三个sheet");
Table table1 = new Table(1);
table1.setHead(createTestListStringHead());
writer.write1(createTestListObject(), sheet3, table1);
//写sheet2 模型上打有表头的注解
Table table2 = new Table(2);
table2.setTableStyle(createTableStyle());
table2.setClazz(JavaModel1.class);
writer.write(createTestListJavaMode(), sheet3, table2);
writer.finish();
out.close();
}
@Test
public void writeV2007WithTemplate() throws IOException {
InputStream inputStream = new BufferedInputStream(new FileInputStream("/Users/jipengfei/temp.xlsx"));
OutputStream out = new FileOutputStream("/Users/jipengfei/2007.xlsx");
ExcelWriter writer = EasyExcelFactory.getWriterWithTemp(inputStream,out,ExcelTypeEnum.XLSX,true);
//写第一个sheet, sheet1 数据全是List<String> 无模型映射关系
Sheet sheet1 = new Sheet(1, 3);
sheet1.setSheetName("第一个sheet");
sheet1.setStartRow(20);
//设置列宽 设置每列的宽度
Map columnWidth = new HashMap();
columnWidth.put(0,10000);columnWidth.put(1,40000);columnWidth.put(2,10000);columnWidth.put(3,10000);
sheet1.setColumnWidthMap(columnWidth);
sheet1.setHead(createTestListStringHead());
//or 设置自适应宽度
//sheet1.setAutoWidth(Boolean.TRUE);
writer.write1(createTestListObject(), sheet1);
//写第二个sheet sheet2 模型上打有表头的注解,合并单元格
Sheet sheet2 = new Sheet(2, 3, JavaModel1.class, "第二个sheet", null);
sheet2.setTableStyle(createTableStyle());
sheet2.setStartRow(20);
writer.write(createTestListJavaMode(), sheet2);
//写第三个sheet包含多个table情况
Sheet sheet3 = new Sheet(3, 0);
sheet3.setSheetName("第三个sheet");
sheet3.setStartRow(30);
Table table1 = new Table(1);
table1.setHead(createTestListStringHead());
writer.write1(createTestListObject(), sheet3, table1);
//写sheet2 模型上打有表头的注解
Table table2 = new Table(2);
table2.setTableStyle(createTableStyle());
table2.setClazz(JavaModel1.class);
writer.write(createTestListJavaMode(), sheet3, table2);
writer.finish();
out.close();
}
@Test
public void writeV2003() throws IOException {
OutputStream out = new FileOutputStream("/Users/jipengfei/2003.xls");
ExcelWriter writer = EasyExcelFactory.getWriter(out, ExcelTypeEnum.XLS,true);
//写第一个sheet, sheet1 数据全是List<String> 无模型映射关系
Sheet sheet1 = new Sheet(1, 3);
sheet1.setSheetName("第一个sheet");
//设置列宽 设置每列的宽度
Map columnWidth = new HashMap();
columnWidth.put(0,10000);columnWidth.put(1,40000);columnWidth.put(2,10000);columnWidth.put(3,10000);
sheet1.setColumnWidthMap(columnWidth);
sheet1.setHead(createTestListStringHead());
//or 设置自适应宽度
//sheet1.setAutoWidth(Boolean.TRUE);
writer.write1(createTestListObject(), sheet1);
//写第二个sheet sheet2 模型上打有表头的注解,合并单元格
Sheet sheet2 = new Sheet(2, 3, JavaModel1.class, "第二个sheet", null);
sheet2.setTableStyle(createTableStyle());
writer.write(createTestListJavaMode(), sheet2);
//写第三个sheet包含多个table情况
Sheet sheet3 = new Sheet(3, 0);
sheet3.setSheetName("第三个sheet");
Table table1 = new Table(1);
table1.setHead(createTestListStringHead());
writer.write1(createTestListObject(), sheet3, table1);
//写sheet2 模型上打有表头的注解
Table table2 = new Table(2);
table2.setTableStyle(createTableStyle());
table2.setClazz(JavaModel1.class);
writer.write(createTestListJavaMode(), sheet3, table2);
writer.finish();
out.close();
}
}

34
src/test/java/com/alibaba/easyexcel/test/listen/ExcelListener.java

@ -0,0 +1,34 @@
package com.alibaba.easyexcel.test.listen;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.ArrayList;
import java.util.List;
public class ExcelListener extends AnalysisEventListener {
private List<Object> data = new ArrayList<Object>();
@Override
public void invoke(Object object, AnalysisContext context) {
System.out.println(context.getCurrentSheet());
if(data.size()<=100){
data.add(object);
}else {
doSomething();
data = new ArrayList<Object>();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
doSomething();
}
public void doSomething(){
for (Object o:data) {
System.out.println(o);
}
}
}

136
src/test/java/com/alibaba/easyexcel/test/model/JavaModel.java

@ -0,0 +1,136 @@
package com.alibaba.easyexcel.test.model;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import java.math.BigDecimal;
import java.util.Date;
public class JavaModel extends BaseRowModel {
@ExcelProperty(index = 0)
private String str;
@ExcelProperty(index = 1)
private Float ff;
@ExcelProperty(index = 2)
private Integer mm;
@ExcelProperty(index = 3)
private BigDecimal money;
@ExcelProperty(index = 4)
private Long times;
@ExcelProperty(index = 5)
private Double activityCode;
@ExcelProperty(index = 6,format = "yyyy-MM-dd")
private Date date;
@ExcelProperty(index = 7)
private String lx;
@ExcelProperty(index = 8)
private String name;
@ExcelProperty(index = 18)
private String kk;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public Float getFf() {
return ff;
}
public void setFf(Float ff) {
this.ff = ff;
}
public Integer getMm() {
return mm;
}
public void setMm(Integer mm) {
this.mm = mm;
}
public BigDecimal getMoney() {
return money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
public Long getTimes() {
return times;
}
public void setTimes(Long times) {
this.times = times;
}
public Double getActivityCode() {
return activityCode;
}
public void setActivityCode(Double activityCode) {
this.activityCode = activityCode;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getLx() {
return lx;
}
public void setLx(String lx) {
this.lx = lx;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKk() {
return kk;
}
public void setKk(String kk) {
this.kk = kk;
}
@Override
public String toString() {
return "JavaModel{" +
"str='" + str + '\'' +
", ff=" + ff +
", mm=" + mm +
", money=" + money +
", times=" + times +
", activityCode=" + activityCode +
", date=" + date +
", lx='" + lx + '\'' +
", name='" + name + '\'' +
", kk='" + kk + '\'' +
'}';
}
}

71
src/test/java/function/model/MultiLineHeadExcelModel.java → src/test/java/com/alibaba/easyexcel/test/model/JavaModel1.java

@ -1,17 +1,12 @@
package function.model; package com.alibaba.easyexcel.test.model;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel; import com.alibaba.excel.metadata.BaseRowModel;
/** import java.math.BigDecimal;
* Created by jipengfei on 17/2/19. import java.util.Date;
*/
public class MultiLineHeadExcelModel extends BaseRowModel { public class JavaModel1 extends BaseRowModel {
@ExcelProperty(value = {"表头1","表头1","表头31"},index = 0) @ExcelProperty(value = {"表头1","表头1","表头31"},index = 0)
private String p1; private String p1;
@ -22,24 +17,27 @@ public class MultiLineHeadExcelModel extends BaseRowModel {
@ExcelProperty(value = {"表头3","表头3","表头3"},index = 2) @ExcelProperty(value = {"表头3","表头3","表头3"},index = 2)
private int p3; private int p3;
@ExcelProperty(value = {"表头4","表头4","表头4"},index = 3) @ExcelProperty(value = {"表头1","表头4","表头4"},index = 3)
private long p4; private long p4;
@ExcelProperty(value = {"表头5","表头51","表头52"},index = 4) @ExcelProperty(value = {"表头5","表头51","表头52"},index = 4)
private String p5; private String p5;
@ExcelProperty(value = {"表头6","表头61","表头611"},index = 5) @ExcelProperty(value = {"表头6","表头61","表头611"},index = 5)
private String p6; private float p6;
@ExcelProperty(value = {"表头6","表头61","表头612"},index = 6) @ExcelProperty(value = {"表头6","表头61","表头612"},index = 6)
private String p7; private BigDecimal p7;
@ExcelProperty(value = {"表头6","表头62","表头621"},index = 7) @ExcelProperty(value = {"表头6","表头62","表头621"},index = 7)
private String p8; private Date p8;
@ExcelProperty(value = {"表头6","表头62","表头622"},index = 8) @ExcelProperty(value = {"表头6","表头62","表头622"},index = 8)
private String p9; private String p9;
@ExcelProperty(value = {"表头6","表头62","表头622"},index = 9)
private double p10;
public String getP1() { public String getP1() {
return p1; return p1;
} }
@ -80,27 +78,27 @@ public class MultiLineHeadExcelModel extends BaseRowModel {
this.p5 = p5; this.p5 = p5;
} }
public String getP6() { public float getP6() {
return p6; return p6;
} }
public void setP6(String p6) { public void setP6(float p6) {
this.p6 = p6; this.p6 = p6;
} }
public String getP7() { public BigDecimal getP7() {
return p7; return p7;
} }
public void setP7(String p7) { public void setP7(BigDecimal p7) {
this.p7 = p7; this.p7 = p7;
} }
public String getP8() { public Date getP8() {
return p8; return p8;
} }
public void setP8(String p8) { public void setP8(Date p8) {
this.p8 = p8; this.p8 = p8;
} }
@ -112,16 +110,27 @@ public class MultiLineHeadExcelModel extends BaseRowModel {
this.p9 = p9; this.p9 = p9;
} }
public static void main(String[] args) { public double getP10() {
Class<?> clazz = MultiLineHeadExcelModel.class; return p10;
Field[] fields = clazz.getDeclaredFields(); }
List<List<String>> head = new ArrayList<List<String>>();
for (int i = 0; i < fields.length ; i++) { public void setP10(double p10) {
Field f = fields[i]; this.p10 = p10;
ExcelProperty p = f.getAnnotation(ExcelProperty.class); }
String[] value =p.value();
head.add(Arrays.asList(value)); @Override
} public String toString() {
System.out.println(head); return "JavaModel1{" +
"p1='" + p1 + '\'' +
", p2='" + p2 + '\'' +
", p3=" + p3 +
", p4=" + p4 +
", p5='" + p5 + '\'' +
", p6=" + p6 +
", p7=" + p7 +
", p8=" + p8 +
", p9='" + p9 + '\'' +
", p10=" + p10 +
'}';
} }
} }

136
src/test/java/com/alibaba/easyexcel/test/model/JavaModel2.java

@ -0,0 +1,136 @@
package com.alibaba.easyexcel.test.model;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import java.math.BigDecimal;
import java.util.Date;
public class JavaModel2 extends BaseRowModel {
@ExcelProperty(index = 0)
private String str;
@ExcelProperty(index = 1)
private Float ff;
@ExcelProperty(index = 2)
private Integer mm;
@ExcelProperty(index = 3)
private BigDecimal money;
@ExcelProperty(index = 4)
private Long times;
@ExcelProperty(index = 5)
private Double activityCode;
@ExcelProperty(index = 6,format = "yyyy-MM-dd")
private Date date;
@ExcelProperty(index = 7)
private String lx;
@ExcelProperty(index = 8)
private String name;
@ExcelProperty(index = 18)
private String kk;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public Float getFf() {
return ff;
}
public void setFf(Float ff) {
this.ff = ff;
}
public Integer getMm() {
return mm;
}
public void setMm(Integer mm) {
this.mm = mm;
}
public BigDecimal getMoney() {
return money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
public Long getTimes() {
return times;
}
public void setTimes(Long times) {
this.times = times;
}
public Double getActivityCode() {
return activityCode;
}
public void setActivityCode(Double activityCode) {
this.activityCode = activityCode;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getLx() {
return lx;
}
public void setLx(String lx) {
this.lx = lx;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKk() {
return kk;
}
public void setKk(String kk) {
this.kk = kk;
}
@Override
public String toString() {
return "JavaModel2{" +
"str='" + str + '\'' +
", ff=" + ff +
", mm=" + mm +
", money=" + money +
", times=" + times +
", activityCode=" + activityCode +
", date=" + date +
", lx='" + lx + '\'' +
", name='" + name + '\'' +
", kk='" + kk + '\'' +
'}';
}
}

93
src/test/java/com/alibaba/easyexcel/test/util/DataUtil.java

@ -0,0 +1,93 @@
package com.alibaba.easyexcel.test.util;
import com.alibaba.easyexcel.test.model.JavaModel1;
import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.metadata.TableStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DataUtil {
public static List<List<Object>> createTestListObject() {
List<List<Object>> object = new ArrayList<List<Object>>();
for (int i = 0; i < 1000; i++) {
List<Object> da = new ArrayList<Object>();
da.add("字符串"+i);
da.add(Long.valueOf(187837834l+i));
da.add(Integer.valueOf(2233+i));
da.add(Double.valueOf(2233.00+i));
da.add(Float.valueOf(2233.0f+i));
da.add(new Date());
da.add(new BigDecimal("3434343433554545"+i));
da.add(Short.valueOf((short)i));
object.add(da);
}
return object;
}
public static List<List<String>> createTestListStringHead(){
//写sheet3 模型上没有注解,表头数据动态传入
List<List<String>> head = new ArrayList<List<String>>();
List<String> headCoulumn1 = new ArrayList<String>();
List<String> headCoulumn2 = new ArrayList<String>();
List<String> headCoulumn3 = new ArrayList<String>();
List<String> headCoulumn4 = new ArrayList<String>();
List<String> headCoulumn5 = new ArrayList<String>();
headCoulumn1.add("第一列");headCoulumn1.add("第一列");headCoulumn1.add("第一列");
headCoulumn2.add("第一列");headCoulumn2.add("第一列");headCoulumn2.add("第一列");
headCoulumn3.add("第二列");headCoulumn3.add("第二列");headCoulumn3.add("第二列");
headCoulumn4.add("第三列");headCoulumn4.add("第三列2");headCoulumn4.add("第三列2");
headCoulumn5.add("第一列");headCoulumn5.add("第3列");headCoulumn5.add("第4列");
head.add(headCoulumn1);
head.add(headCoulumn2);
head.add(headCoulumn3);
head.add(headCoulumn4);
head.add(headCoulumn5);
return head;
}
public static List<JavaModel1> createTestListJavaMode(){
List<JavaModel1> model1s = new ArrayList<JavaModel1>();
for (int i = 0; i <10000 ; i++) {
JavaModel1 model1 = new JavaModel1();
model1.setP1("第一列,第"+i+"行");
model1.setP2("222"+i);
model1.setP3(33+i);
model1.setP4(44);
model1.setP5("555");
model1.setP6(666.2f);
model1.setP7(new BigDecimal("454545656343434"+i));
model1.setP8(new Date());
model1.setP9("llll9999>&&&&&6666^^^^");
model1.setP10(1111.77+i);
model1s.add(model1);
}
return model1s;
}
public static TableStyle createTableStyle() {
TableStyle tableStyle = new TableStyle();
Font headFont = new Font();
headFont.setBold(true);
headFont.setFontHeightInPoints((short)22);
headFont.setFontName("楷体");
tableStyle.setTableHeadFont(headFont);
tableStyle.setTableHeadBackGroundColor(IndexedColors.BLUE);
Font contentFont = new Font();
contentFont.setBold(true);
contentFont.setFontHeightInPoints((short)22);
contentFont.setFontName("黑体");
tableStyle.setTableContentFont(contentFont);
tableStyle.setTableContentBackGroundColor(IndexedColors.GREEN);
return tableStyle;
}
}

10
src/test/java/com/alibaba/easyexcel/test/util/FileUtil.java

@ -0,0 +1,10 @@
package com.alibaba.easyexcel.test.util;
import java.io.InputStream;
public class FileUtil {
public static InputStream getResourcesFileInputStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
}
}

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

@ -1,93 +0,0 @@
package function.listener;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jipengfei on 17/3/14.
* 解析监听器
* 每解析一行会回调invoke()方法
* 整个excel解析结束会执行doAfterAllAnalysed()方法
*
* 下面只是我写的一个样例而已可以根据自己的逻辑修改该类
*
* @author jipengfei
* @date 2017/03/14
*/
public class ExcelListener extends AnalysisEventListener {
//自定义用于暂时存储data。
//可以通过实例获取该值
private List<Object> datas = new ArrayList<Object>();
Sheet sheet;
private ExcelWriter writer;
public void invoke(Object object, AnalysisContext context) {
// context.interrupt();
System.out.println("当前表格数" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum());
System.out.println(object);
datas.add(object);//数据存储到list,供批量处理,或后续自己业务逻辑处理。
List<List<String>> ll = new ArrayList<List<String>>();
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(byteOut);
out.writeObject(object);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
List<String> dest = (List<String>)in.readObject();
ll.add(dest);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// writer.write0(ll, sheet);
doSomething(object);//根据自己业务做处理
}
private void doSomething(Object object) {
//1、入库调用接口
}
public void doAfterAllAnalysed(AnalysisContext context) {
// writer.finish();
// datas.clear();//解析结束销毁不用的资源
}
public List<Object> getDatas() {
return datas;
}
public void setDatas(List<Object> datas) {
this.datas = datas;
}
public Sheet getSheet() {
return sheet;
}
public void setSheet(Sheet sheet) {
this.sheet = sheet;
}
public ExcelWriter getWriter() {
return writer;
}
public void setWriter(ExcelWriter writer) {
this.writer = writer;
}
}

87
src/test/java/function/model/ExcelPropertyIndexModel.java

@ -1,87 +0,0 @@
package function.model;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
/**
* @author jipengfei
*/
public class ExcelPropertyIndexModel extends BaseRowModel {
@ExcelProperty(value = "姓名" ,index = 0)
private String name;
@ExcelProperty(value = "年龄",index = 1)
private String age;
@ExcelProperty(value = "邮箱",index = 2)
private String email;
@ExcelProperty(value = "地址",index = 3)
private String address;
@ExcelProperty(value = "性别",index = 4)
private String sax;
@ExcelProperty(value = "高度",index = 5)
private String heigh;
@ExcelProperty(value = "备注",index = 6)
private String last;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSax() {
return sax;
}
public void setSax(String sax) {
this.sax = sax;
}
public String getHeigh() {
return heigh;
}
public void setHeigh(String heigh) {
this.heigh = heigh;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
}

132
src/test/java/function/model/LoanInfo.java

@ -1,132 +0,0 @@
package function.model;
import java.math.BigDecimal;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
/**
* Created by jipengfei on 17/3/28.
*
* @author jipengfei
* @date 2017/03/28
*/
public class LoanInfo extends BaseRowModel implements Comparable<LoanInfo> {
@ExcelProperty(index = 0)
private String bankLoanId;
@ExcelProperty(index = 1)
private Long customerId;
@ExcelProperty(index = 2,format = "yyyy/MM/dd")
private Date loanDate;
@ExcelProperty(index = 3)
private BigDecimal quota;
@ExcelProperty(index = 4)
private String bankInterestRate;
@ExcelProperty(index = 5)
private Integer loanTerm;
@ExcelProperty(index = 6,format = "yyyy/MM/dd")
private Date loanEndDate;
@ExcelProperty(index = 7)
private Date interestPerMonth;
// public String getLoanName() {
// return loanName;
// }
//
// public void setLoanName(String loanName) {
// this.loanName = loanName;
// }
public Date getLoanDate() {
return loanDate;
}
public void setLoanDate(Date loanDate) {
this.loanDate = loanDate;
}
public BigDecimal getQuota() {
return quota;
}
public void setQuota(BigDecimal quota) {
this.quota = quota;
}
public String getBankInterestRate() {
return bankInterestRate;
}
public void setBankInterestRate(String bankInterestRate) {
this.bankInterestRate = bankInterestRate;
}
public Integer getLoanTerm() {
return loanTerm;
}
public void setLoanTerm(Integer loanTerm) {
this.loanTerm = loanTerm;
}
public Date getLoanEndDate() {
return loanEndDate;
}
public void setLoanEndDate(Date loanEndDate) {
this.loanEndDate = loanEndDate;
}
public Date getInterestPerMonth() {
return interestPerMonth;
}
public void setInterestPerMonth(Date interestPerMonth) {
this.interestPerMonth = interestPerMonth;
}
public String getBankLoanId() {
return bankLoanId;
}
public void setBankLoanId(String bankLoanId) {
this.bankLoanId = bankLoanId;
}
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
@Override
public String toString() {
return "ExcelLoanInfo{" +
"bankLoanId='" + bankLoanId + '\'' +
", customerId='" + customerId + '\'' +
", loanDate=" + loanDate +
", quota=" + quota +
", bankInterestRate=" + bankInterestRate +
", loanTerm=" + loanTerm +
", loanEndDate=" + loanEndDate +
", interestPerMonth=" + interestPerMonth +
'}';
}
public int compareTo(LoanInfo info) {
boolean before = this.getLoanDate().before(info.getLoanDate());
return before ? 1 : 0;
}
}

44
src/test/java/function/model/NoAnnModel.java

@ -1,44 +0,0 @@
package function.model;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
/**
* @author jipengfei
* @date 2017/05/16
*/
public class NoAnnModel extends BaseRowModel {
@ExcelProperty(index = 0)
private String p1;
@ExcelProperty(index = 1)
private String p2;
@ExcelProperty(index = 2)
private String p3;
public String getP1() {
return p1;
}
public void setP1(String p1) {
this.p1 = p1;
}
public String getP2() {
return p2;
}
public void setP2(String p2) {
this.p2 = p2;
}
public String getP3() {
return p3;
}
public void setP3(String p3) {
this.p3 = p3;
}
}

270
src/test/java/function/model/OneRowHeadExcelModel.java

@ -1,270 +0,0 @@
package function.model;
import com.alibaba.excel.annotation.ExcelColumnNum;
import com.alibaba.excel.metadata.BaseRowModel;
/**
* Created by jipengfei on 17/2/18.
*/
public class OneRowHeadExcelModel extends BaseRowModel {
@ExcelColumnNum(value = 0)
private String p1;
@ExcelColumnNum(1)
private String p2;
@ExcelColumnNum(2)
private int p3;
@ExcelColumnNum(3)
private long p4;
@ExcelColumnNum(4)
private String p5;
@ExcelColumnNum(5)
private String p6;
@ExcelColumnNum(6)
private String p7;
@ExcelColumnNum(7)
private String p8;
@ExcelColumnNum(8)
private String p9;
@ExcelColumnNum(9)
private String p10;
@ExcelColumnNum(10)
private String p11;
@ExcelColumnNum(11)
private String p12;
@ExcelColumnNum(12)
private String p13;
@ExcelColumnNum(13)
private String p14;
@ExcelColumnNum(14)
private String p15;
@ExcelColumnNum(15)
private String p16;
@ExcelColumnNum(16)
private String p17;
@ExcelColumnNum(17)
private String p18;
@ExcelColumnNum(18)
private String p19;
@ExcelColumnNum(19)
private String p20;
@ExcelColumnNum(20)
private String p21;
public String getP2() {
return p2;
}
public void setP2(String p2) {
this.p2 = p2;
}
public int getP3() {
return p3;
}
public void setP3(int p3) {
this.p3 = p3;
}
public long getP4() {
return p4;
}
public void setP4(long p4) {
this.p4 = p4;
}
public String getP5() {
return p5;
}
public void setP5(String p5) {
this.p5 = p5;
}
public String getP6() {
return p6;
}
public void setP6(String p6) {
this.p6 = p6;
}
public String getP7() {
return p7;
}
public void setP7(String p7) {
this.p7 = p7;
}
public String getP8() {
return p8;
}
public void setP8(String p8) {
this.p8 = p8;
}
public String getP9() {
return p9;
}
public void setP9(String p9) {
this.p9 = p9;
}
public String getP10() {
return p10;
}
public void setP10(String p10) {
this.p10 = p10;
}
public String getP11() {
return p11;
}
public void setP11(String p11) {
this.p11 = p11;
}
public String getP12() {
return p12;
}
public void setP12(String p12) {
this.p12 = p12;
}
public String getP13() {
return p13;
}
public void setP13(String p13) {
this.p13 = p13;
}
public String getP14() {
return p14;
}
public void setP14(String p14) {
this.p14 = p14;
}
public String getP15() {
return p15;
}
public void setP15(String p15) {
this.p15 = p15;
}
public String getP16() {
return p16;
}
public void setP16(String p16) {
this.p16 = p16;
}
public String getP17() {
return p17;
}
public void setP17(String p17) {
this.p17 = p17;
}
public String getP18() {
return p18;
}
public void setP18(String p18) {
this.p18 = p18;
}
public String getP19() {
return p19;
}
public void setP19(String p19) {
this.p19 = p19;
}
public String getP20() {
return p20;
}
public void setP20(String p20) {
this.p20 = p20;
}
public String getP21() {
return p21;
}
public void setP21(String p21) {
this.p21 = p21;
}
public String getP1() {
return p1;
}
public void setP1(String p1) {
this.p1 = p1;
}
@Override
public String toString() {
return "OneRowHeadExcelModel{" +
"p1='" + p1 + '\'' +
", p2='" + p2 + '\'' +
", p3=" + p3 +
", p4=" + p4 +
", p5='" + p5 + '\'' +
", p6='" + p6 + '\'' +
", p7='" + p7 + '\'' +
", p8='" + p8 + '\'' +
", p9='" + p9 + '\'' +
", p10='" + p10 + '\'' +
", p11='" + p11 + '\'' +
", p12='" + p12 + '\'' +
", p13='" + p13 + '\'' +
", p14='" + p14 + '\'' +
", p15='" + p15 + '\'' +
", p16='" + p16 + '\'' +
", p17='" + p17 + '\'' +
", p18='" + p18 + '\'' +
", p19='" + p19 + '\'' +
", p20='" + p20 + '\'' +
", p21='" + p21 + '\'' +
'}';
}
}

354
src/test/java/function/model/TestModel3.java

@ -1,354 +0,0 @@
package function.model;
import com.alibaba.excel.annotation.ExcelColumnNum;
import com.alibaba.excel.metadata.BaseRowModel;
/**
* Created by jipengfei on 17/3/19.
*
* @author jipengfei
* @date 2017/03/19
*/
public class TestModel3 extends BaseRowModel {
@ExcelColumnNum(0)
private String p1;
@ExcelColumnNum(1)
private String p2;
@ExcelColumnNum(2)
private String p3;
@ExcelColumnNum(3)
private String p4;
@ExcelColumnNum(4)
private String p5;
@ExcelColumnNum(5)
private String p6;
@ExcelColumnNum(6)
private String p7;
@ExcelColumnNum(7)
private String p8;
@ExcelColumnNum(8)
private String p9;
@ExcelColumnNum(9)
private String p10;
@ExcelColumnNum(10)
private String p11;
@ExcelColumnNum(11)
private String p12;
@ExcelColumnNum(12)
private String p13;
@ExcelColumnNum(13)
private String p14;
@ExcelColumnNum(14)
private String p15;
@ExcelColumnNum(15)
private String p16;
@ExcelColumnNum(16)
private String p17;
@ExcelColumnNum(17)
private String p18;
@ExcelColumnNum(18)
private String p19;
@ExcelColumnNum(19)
private String p20;
@ExcelColumnNum(20)
private String p21;
@ExcelColumnNum(21)
private String p22;
@ExcelColumnNum(22)
private String p23;
@ExcelColumnNum(23)
private String p24;
@ExcelColumnNum(24)
private String p25;
@ExcelColumnNum(25)
private String p26;
@ExcelColumnNum(26)
private String p27;
@ExcelColumnNum(27)
private String p28;
@ExcelColumnNum(28)
private String p29;
@ExcelColumnNum(29)
private String p30;
@ExcelColumnNum(30)
private String p31;
public String getP28() {
return p28;
}
public String getP30() {
return p30;
}
public void setP30(String p30) {
this.p30 = p30;
}
public String getP31() {
return p31;
}
public void setP31(String p31) {
this.p31 = p31;
}
public void setP28(String p28) {
this.p28 = p28;
}
public String getP29() {
return p29;
}
public void setP29(String p29) {
this.p29 = p29;
}
public String getP1() {
return p1;
}
public void setP1(String p1) {
this.p1 = p1;
}
public String getP2() {
return p2;
}
public void setP2(String p2) {
this.p2 = p2;
}
public String getP3() {
return p3;
}
public void setP3(String p3) {
this.p3 = p3;
}
public String getP4() {
return p4;
}
public void setP4(String p4) {
this.p4 = p4;
}
public String getP5() {
return p5;
}
public void setP5(String p5) {
this.p5 = p5;
}
public String getP6() {
return p6;
}
public void setP6(String p6) {
this.p6 = p6;
}
public String getP7() {
return p7;
}
public void setP7(String p7) {
this.p7 = p7;
}
public String getP8() {
return p8;
}
public void setP8(String p8) {
this.p8 = p8;
}
public String getP9() {
return p9;
}
public void setP9(String p9) {
this.p9 = p9;
}
public String getP10() {
return p10;
}
public void setP10(String p10) {
this.p10 = p10;
}
public String getP11() {
return p11;
}
public void setP11(String p11) {
this.p11 = p11;
}
public String getP12() {
return p12;
}
public void setP12(String p12) {
this.p12 = p12;
}
public String getP13() {
return p13;
}
public void setP13(String p13) {
this.p13 = p13;
}
public String getP14() {
return p14;
}
public void setP14(String p14) {
this.p14 = p14;
}
public String getP15() {
return p15;
}
public void setP15(String p15) {
this.p15 = p15;
}
public String getP16() {
return p16;
}
public void setP16(String p16) {
this.p16 = p16;
}
public String getP17() {
return p17;
}
public void setP17(String p17) {
this.p17 = p17;
}
public String getP18() {
return p18;
}
public void setP18(String p18) {
this.p18 = p18;
}
public String getP19() {
return p19;
}
public void setP19(String p19) {
this.p19 = p19;
}
public String getP20() {
return p20;
}
public void setP20(String p20) {
this.p20 = p20;
}
public String getP21() {
return p21;
}
public void setP21(String p21) {
this.p21 = p21;
}
public String getP22() {
return p22;
}
public void setP22(String p22) {
this.p22 = p22;
}
public String getP23() {
return p23;
}
public void setP23(String p23) {
this.p23 = p23;
}
public String getP24() {
return p24;
}
public void setP24(String p24) {
this.p24 = p24;
}
public String getP25() {
return p25;
}
public void setP25(String p25) {
this.p25 = p25;
}
public String getP26() {
return p26;
}
public void setP26(String p26) {
this.p26 = p26;
}
public String getP27() {
return p27;
}
public void setP27(String p27) {
this.p27 = p27;
}
}

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

@ -1,46 +0,0 @@
package function.read;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import function.listener.ExcelListener;
import junit.framework.TestCase;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by jipengfei on 17/3/15.
*
* @author jipengfei
* @date 2017/03/15
*/
public class ExelAllDataTypeTest extends TestCase {
// 创建没有自定义模型,没有sheet的解析器,默认解析所有sheet解析结果以List<String>的方式通知监听者
@Test
public void testExcel2007WithReflectModel() {
InputStream inputStream = getInputStream("test2.xlsx");
try {
// 解析每行结果在listener中处理
AnalysisEventListener listener = new ExcelListener();
new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener).read(new Sheet(1, 1,null));
}catch (Exception e){
}finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private InputStream getInputStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
}
}

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

@ -1,45 +0,0 @@
package function.read;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import function.listener.ExcelListener;
import function.model.TestModel3;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by jipengfei on 17/3/19.
*
* @author jipengfei
* @date 2017/03/19
*/
public class NumTest3 {
@Test
public void testExcel2007WithReflectModel() {
InputStream inputStream = getInputStream("test3.xlsx");
try {
AnalysisEventListener listener = new ExcelListener();
new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener).read(new Sheet(1, 1, TestModel3.class));
} catch (Exception e) {
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private InputStream getInputStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
}
}

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

@ -1,82 +0,0 @@
package function.read;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import function.listener.ExcelListener;
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.
*
* @author jipengfei
* @date 2017/03/22
*/
public class ReadSheets {
@Test
public void ReadSheets2007() {
InputStream inputStream = getInputStream("2007NoModelMultipleSheet.xlsx");
try {
ExcelListener listener = new ExcelListener();
listener.setSheet(new Sheet(1));
ExcelWriter excelWriter = new ExcelWriter(new FileOutputStream("/Users/jipengfei/77.xlsx"), ExcelTypeEnum.XLSX,false);
listener.setWriter(excelWriter);
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener);
List<Sheet> sheets = reader.getSheets();
System.out.println(sheets);
for (Sheet sheet:sheets) {
sheet.setHeadLineMun(1);
reader.read(sheet);
}
// reader.read(new Sheet(1));
excelWriter.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void ReadSheets2003() {
InputStream inputStream = getInputStream("2003.xls");
try {
AnalysisEventListener listener = new ExcelListener();
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
reader.read();
List<Sheet> sheets = reader.getSheets();
System.out.println(sheets);
for (Sheet sheet:sheets) {
sheet.setHeadLineMun(1);
reader.read(sheet);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private InputStream getInputStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
}
}

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

@ -1,139 +0,0 @@
package function.read;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import function.listener.ExcelListener;
import function.model.OneRowHeadExcelModel;
import junit.framework.TestCase;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by jipengfei on 17/2/18.
*/
public class XLSX2007FunctionTest extends TestCase {
//创建没有自定义模型,没有sheet的解析器,默认解析所有sheet解析结果以List<String>的方式通知监听者
@Test
public void testExcel2007NoModel() {
InputStream inputStream = getInputStream("2007NoModelBigFile.xlsx");
try {
// 解析每行结果在listener中处理
AnalysisEventListener listener = new ExcelListener();
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener);
reader.read();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testExcel2007NoModel2() {
InputStream inputStream = getInputStream("test4.xlsx");
try {
// 解析每行结果在listener中处理
AnalysisEventListener listener = new ExcelListener();
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener);
reader.read();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//创建没有自定义模型,但有规定sheet解析器,解析结果以List<String>的方式通知监听者
@Test
public void testExcel2007WithSheet() {
InputStream inputStream = getInputStream("111.xlsx");
try {
// 解析每行结果在listener中处理
AnalysisEventListener listener = new ExcelListener();
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener);
reader.read(new Sheet(1, 0));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//创建需要反射映射模型的解析器,解析结果List<Object> Object为自定义的模型
@Test
public void testExcel2007WithReflectModel() {
InputStream inputStream = getInputStream("2007.xlsx");
try {
// 解析每行结果在listener中处理
AnalysisEventListener listener = new ExcelListener();
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener);
reader.read(new Sheet(1, 1, OneRowHeadExcelModel.class));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testExcel2007MultHeadWithReflectModel() {
InputStream inputStream = getInputStream("2007_1.xlsx");
try {
// 解析每行结果在listener中处理
AnalysisEventListener listener = new ExcelListener();
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener);
reader.read(new Sheet(1, 4, OneRowHeadExcelModel.class));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private InputStream getInputStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
}
}

117
src/test/java/function/write/ExcelWriteIndexTest.java

@ -1,117 +0,0 @@
package function.write;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import function.model.ExcelPropertyIndexModel;
import function.model.MultiLineHeadExcelModel;
import org.junit.Test;
/**
* 测试{@link ExcelProperty#index()}
*
* @author jipengfei
* @date 2017/05/31
*/
public class ExcelWriteIndexTest {
@Test
public void test1() throws FileNotFoundException {
OutputStream out = new FileOutputStream("/Users/jipengfei/78.xlsx");
try {
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
//写第一个sheet, sheet1 数据全是List<String> 无模型映射关系
Sheet sheet1 = new Sheet(1, 0,ExcelPropertyIndexModel.class);
writer.write(getData(), sheet1);
writer.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void test2() throws FileNotFoundException {
OutputStream out = new FileOutputStream("/Users/jipengfei/79.xlsx");
try {
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
//写第一个sheet, sheet1 数据全是List<String> 无模型映射关系
Sheet sheet1 = new Sheet(1, 3,MultiLineHeadExcelModel.class);
writer.write(getModeldatas(), sheet1);
writer.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public List<ExcelPropertyIndexModel> getData() {
List<ExcelPropertyIndexModel> datas = new ArrayList<ExcelPropertyIndexModel>();
ExcelPropertyIndexModel model = new ExcelPropertyIndexModel();
model.setAddress("杭州");
model.setAge("11");
model.setEmail("7827323@qq.com");
model.setSax("男");
model.setHeigh("1123");
datas.add(model);
return datas;
}
private List<MultiLineHeadExcelModel> getModeldatas() {
List<MultiLineHeadExcelModel> MODELS = new ArrayList<MultiLineHeadExcelModel>();
MultiLineHeadExcelModel model1 = new MultiLineHeadExcelModel();
model1.setP1("111");
model1.setP2("222");
model1.setP3(33);
model1.setP4(44);
model1.setP5("555");
model1.setP6("666");
model1.setP7("777");
model1.setP8("888");
MultiLineHeadExcelModel model2 = new MultiLineHeadExcelModel();
model2.setP1("111");
model2.setP2("111");
model2.setP3(11);
model2.setP4(9);
model2.setP5("111");
model2.setP6("111");
model2.setP7("111");
model2.setP8("111");
MultiLineHeadExcelModel model3 = new MultiLineHeadExcelModel();
model3.setP1("111");
model3.setP2("111");
model3.setP3(11);
model3.setP4(9);
model3.setP5("111");
model3.setP6("111");
model3.setP7("111");
model3.setP8("111");
MODELS.add(model1);
MODELS.add(model2);
MODELS.add(model3);
return MODELS;
}
}

246
src/test/java/function/write/ExcelWriteTest.java

@ -1,246 +0,0 @@
package function.write;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.support.ExcelTypeEnum;
import function.model.MultiLineHeadExcelModel;
import function.model.NoAnnModel;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.junit.Test;
/**
*
* 测试Excel写多个表格
* @author jipengfei
* @date 2017/05/16
*/
public class ExcelWriteTest {
/**
* 一个sheet一张表
*
* @throws FileNotFoundException
*/
@Test
public void test1() throws FileNotFoundException {
OutputStream out = new FileOutputStream("/Users/jipengfei/77.xlsx");
try {
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
//写第一个sheet, sheet1 数据全是List<String> 无模型映射关系
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(getListString(), sheet1);
//写第二个sheet sheet2 模型上打有表头的注解,合并单元格
Sheet sheet2 = new Sheet(2, 3, MultiLineHeadExcelModel.class, "第二个sheet", null);
sheet2.setTableStyle(getTableStyle1());
writer.write(getModeldatas(), sheet2);
//写sheet3 模型上没有注解,表头数据动态传入
List<List<String>> head = new ArrayList<List<String>>();
List<String> headCoulumn1 = new ArrayList<String>();
List<String> headCoulumn2 = new ArrayList<String>();
List<String> headCoulumn3 = new ArrayList<String>();
headCoulumn1.add("第一列");
headCoulumn2.add("第二列");
headCoulumn3.add("第三列");
head.add(headCoulumn1);
head.add(headCoulumn2);
head.add(headCoulumn3);
Sheet sheet3 = new Sheet(3, 1, NoAnnModel.class, "第三个sheet", head);
writer.write(getNoAnnModels(), sheet3);
writer.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 一个sheet多张表
*
* @throws FileNotFoundException
*/
@Test
public void test2() throws FileNotFoundException {
OutputStream out = new FileOutputStream("/Users/jipengfei/77.xlsx");
try {
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,false);
//写sheet1 数据全是List<String> 无模型映射关系
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
Table table1 = new Table(1);
writer.write0(getListString(), sheet1, table1);
writer.write0(getListString(), sheet1, table1);
//写sheet2 模型上打有表头的注解
Table table2 = new Table(2);
table2.setTableStyle(getTableStyle1());
table2.setClazz(MultiLineHeadExcelModel.class);
writer.write(getModeldatas(), sheet1, table2);
//写sheet3 模型上没有注解,表头数据动态传入,此情况下模型field顺序与excel现实顺序一致
List<List<String>> head = new ArrayList<List<String>>();
List<String> headCoulumn1 = new ArrayList<String>();
List<String> headCoulumn2 = new ArrayList<String>();
List<String> headCoulumn3 = new ArrayList<String>();
headCoulumn1.add("第一列");
headCoulumn2.add("第二列");
headCoulumn3.add("第三列");
head.add(headCoulumn1);
head.add(headCoulumn2);
head.add(headCoulumn3);
Table table3 = new Table(3);
table3.setHead(head);
table3.setClazz(NoAnnModel.class);
table3.setTableStyle(getTableStyle2());
writer.write(getNoAnnModels(), sheet1, table3);
writer.write(getNoAnnModels(), sheet1, table3);
writer.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private List<List<String>> getListString() {
List<String> list = new ArrayList<String>();
list.add("ooo1");
list.add("ooo2");
list.add("ooo3");
list.add("ooo4");
List<String> list1 = new ArrayList<String>();
list1.add("ooo1");
list1.add("ooo2");
list1.add("ooo3");
list1.add("ooo4");
List<List<String>> ll = new ArrayList<List<String>>();
ll.add(list);
ll.add(list1);
return ll;
}
private List<MultiLineHeadExcelModel> getModeldatas() {
List<MultiLineHeadExcelModel> MODELS = new ArrayList<MultiLineHeadExcelModel>();
MultiLineHeadExcelModel model1 = new MultiLineHeadExcelModel();
model1.setP1("111");
model1.setP2("222");
model1.setP3(33);
model1.setP4(44);
model1.setP5("555");
model1.setP6("666");
model1.setP7("777");
model1.setP8("888");
MultiLineHeadExcelModel model2 = new MultiLineHeadExcelModel();
model2.setP1("111");
model2.setP2("111");
model2.setP3(11);
model2.setP4(9);
model2.setP5("111");
model2.setP6("111");
model2.setP7("111");
model2.setP8("111");
MultiLineHeadExcelModel model3 = new MultiLineHeadExcelModel();
model3.setP1("111");
model3.setP2("111");
model3.setP3(11);
model3.setP4(9);
model3.setP5("111");
model3.setP6("111");
model3.setP7("111");
model3.setP8("111");
MODELS.add(model1);
MODELS.add(model2);
MODELS.add(model3);
return MODELS;
}
private List<NoAnnModel> getNoAnnModels() {
List<NoAnnModel> MODELS = new ArrayList<NoAnnModel>();
NoAnnModel model1 = new NoAnnModel();
model1.setP1("111");
model1.setP2("111");
NoAnnModel model2 = new NoAnnModel();
model2.setP1("111");
model2.setP2("111");
model2.setP3("22");
NoAnnModel model3 = new NoAnnModel();
model3.setP1("111");
model3.setP2("111");
model3.setP3("111");
MODELS.add(model1);
MODELS.add(model2);
MODELS.add(model3);
return MODELS;
}
private TableStyle getTableStyle1() {
TableStyle tableStyle = new TableStyle();
Font headFont = new Font();
headFont.setBold(true);
headFont.setFontHeightInPoints((short)22);
headFont.setFontName("楷体");
tableStyle.setTableHeadFont(headFont);
tableStyle.setTableHeadBackGroundColor(IndexedColors.BLUE);
Font contentFont = new Font();
contentFont.setBold(true);
contentFont.setFontHeightInPoints((short)22);
contentFont.setFontName("黑体");
tableStyle.setTableContentFont(contentFont);
tableStyle.setTableContentBackGroundColor(IndexedColors.GREEN);
return tableStyle;
}
private TableStyle getTableStyle2() {
TableStyle tableStyle = new TableStyle();
Font headFont = new Font();
headFont.setBold(true);
headFont.setFontHeightInPoints((short)22);
headFont.setFontName("宋体");
tableStyle.setTableHeadFont(headFont);
tableStyle.setTableHeadBackGroundColor(IndexedColors.BLUE);
Font contentFont = new Font();
contentFont.setBold(true);
contentFont.setFontHeightInPoints((short)10);
contentFont.setFontName("黑体");
tableStyle.setTableContentFont(contentFont);
tableStyle.setTableContentBackGroundColor(IndexedColors.RED);
return tableStyle;
}
}

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

@ -1,103 +0,0 @@
package function.write;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import function.listener.ExcelListener;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.junit.Test;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author jipengfei
* @date 2017/08/15
*/
public class ExcelWriteTest1 {
@Test
public void test(){
OutputStream out = null;
try {
out = new FileOutputStream("/Users/jipengfei/79.xlsx");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, false);
//写sheet1 数据全是List<String> 无模型映射关系
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
List<String> list = new ArrayList<String>();
list.add("1");list.add("2");list.add("3");
List<String> list1 = new ArrayList<String>();
list1.add("1");list1.add("2");list1.add("3");
List<List<String>> lll = new ArrayList<List<String>>();
lll.add(list);
writer.write0(lll,sheet1);
writer.write0(lll,sheet1);
writer.finish();
}catch (Exception e){
e.printStackTrace();
}
}
@Test
public void testWriteAndRead(){
OutputStream out = null;
try {
out = new FileOutputStream("/Users/jipengfei/79.xlsx");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
SXSSFWorkbook wb = new SXSSFWorkbook(10000);
SXSSFSheet sheet = wb.createSheet("11111");
Row row = sheet.createRow(0);
Cell cell1 = row.createCell(0);
cell1.setCellValue("1111");
Cell cell2 = row.createCell(1);
cell2.setCellValue("22222");
Cell cell3 = row.createCell(2);
cell3.setCellValue("33333");
Row row1 = sheet.createRow(1);
Cell cell21 = row1.createCell(0);
cell21.setCellValue("444");
Cell cell22 = row1.createCell(1);
cell22.setCellValue("555");
Cell cell23 = row1.createCell(2);
cell23.setCellValue("666");
wb.write(out);
out.close();
InputStream inputStream = new FileInputStream("/Users/jipengfei/79.xlsx");
AnalysisEventListener listener = new ExcelListener();
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener);
reader.read(new Sheet(1));
}catch (Exception e){
e.printStackTrace();
}
}
private InputStream getInputStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
}
}

128
src/test/java/javamodel/ExcelRowJavaModel.java

@ -1,128 +0,0 @@
package javamodel;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
/**
* Created by jipengfei on 17/3/15.
*
* @author jipengfei
* @date 2017/03/15
*/
public class ExcelRowJavaModel extends BaseRowModel {
@ExcelProperty(index = 0,value = "银行放款编号")
private int num;
@ExcelProperty(index = 1,value = "code")
private Long code;
@ExcelProperty(index = 2,value = "银行存放期期")
private Date endTime;
@ExcelProperty(index = 3,value = "测试1")
private Double money;
@ExcelProperty(index = 4,value = "测试2")
private String times;
@ExcelProperty(index = 5,value = "测试3")
private int activityCode;
@ExcelProperty(index = 6,value = "测试4")
private Date date;
@ExcelProperty(index = 7,value = "测试5")
private Double lx;
@ExcelProperty(index = 8,value = "测试6")
private String name;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public Long getCode() {
return code;
}
public void setCode(Long code) {
this.code = code;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
public String getTimes() {
return times;
}
public void setTimes(String times) {
this.times = times;
}
public int getActivityCode() {
return activityCode;
}
public void setActivityCode(int activityCode) {
this.activityCode = activityCode;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Double getLx() {
return lx;
}
public void setLx(Double lx) {
this.lx = lx;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "ExcelRowJavaModel{" +
"num=" + num +
", code=" + code +
", endTime=" + endTime +
", money=" + money +
", times='" + times + '\'' +
", activityCode=" + activityCode +
", date=" + date +
", lx=" + lx +
", name='" + name + '\'' +
'}';
}
}

45
src/test/java/javamodel/ExcelRowJavaModel1.java

@ -1,45 +0,0 @@
package javamodel;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
/**
* Created by jipengfei on 17/3/15.
*
* @author jipengfei
* @date 2017/03/15
*/
public class ExcelRowJavaModel1 extends BaseRowModel {
@ExcelProperty(index = 0,value = "银行放款编号")
private String num;
@ExcelProperty(index = 1,value = "code")
private String code;
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public String toString() {
return "ExcelRowJavaModel1{" +
"num='" + num + '\'' +
", code='" + code + '\'' +
'}';
}
}

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

@ -1,48 +0,0 @@
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 + '\'' +
'}';
}
}

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

@ -1,87 +0,0 @@
package read.v03;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import function.listener.ExcelListener;
import function.model.LoanInfo;
import junit.framework.TestCase;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by jipengfei on 17/2/19.
*/
public class XLS2003FunctionTest extends TestCase {
@Test
public void testExcel2003NoModel() {
InputStream inputStream = getInputStream("2003.xls");
try {
// 解析每行结果在listener中处理
ExcelListener listener = new ExcelListener();
ExcelReader excelReader = new ExcelReader(inputStream, null, listener);
excelReader.read();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testExcel2003WithSheet() {
InputStream inputStream = getInputStream("loan1.xls");
try {
// 解析每行结果在listener中处理
ExcelListener listener = new ExcelListener();
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
reader.read(new Sheet(1, 1));
System.out.println(listener.getDatas());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testExcel2003WithReflectModel() {
InputStream inputStream = getInputStream("loan1.xls");
try {
// 解析每行结果在listener中处理
AnalysisEventListener listener = new ExcelListener();
ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
excelReader.read(new Sheet(1, 2, LoanInfo.class));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private InputStream getInputStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
}
}

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

@ -1,91 +0,0 @@
package read.v07;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import javamodel.ExcelRowJavaModel;
import javamodel.ExcelRowJavaModel1;
import org.junit.Test;
import read.v07.listener.Excel2007NoJavaModelAnalysisListener;
import read.v07.listener.Excel2007WithJavaModelAnalysisListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @author jipengfei
* @date 2017/08/27
*/
public class Read2007MeanWhileWrite {
@Test
public void noModel() {
InputStream inputStream = getInputStream("2007NoModelMultipleSheet.xlsx");
try {
Excel2007NoJavaModelAnalysisListener listener = new Excel2007NoJavaModelAnalysisListener();
ExcelWriter excelWriter = new ExcelWriter(new FileOutputStream("/Users/jipengfei/77.xlsx"),
ExcelTypeEnum.XLSX, false);
listener.setExcelWriter(excelWriter);
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener);
List<Sheet> sheets = reader.getSheets();
System.out.println(sheets);
for (Sheet sheet : sheets) {
sheet.setHeadLineMun(1);
reader.read(sheet);
}
excelWriter.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void withModel() {
InputStream inputStream = getInputStream("2007WithModelMultipleSheet.xlsx");
try {
Excel2007WithJavaModelAnalysisListener listener = new Excel2007WithJavaModelAnalysisListener();
ExcelWriter excelWriter = new ExcelWriter(new FileOutputStream("/Users/jipengfei/78.xlsx"),
ExcelTypeEnum.XLSX, true);
listener.setExcelWriter(excelWriter);
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener);
List<Sheet> sheets = reader.getSheets();
for (Sheet sheet : sheets) {
sheet.setHeadLineMun(1);
if (sheet.getSheetNo() == 1) {
sheet.setHeadLineMun(2);
sheet.setClazz(ExcelRowJavaModel.class);
}
if (sheet.getSheetNo() == 2) {
sheet.setHeadLineMun(1);
sheet.setClazz(ExcelRowJavaModel1.class);
}
reader.read(sheet);
}
excelWriter.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private InputStream getInputStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
}
}

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

@ -1,398 +0,0 @@
package read.v07;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import javamodel.ExcelRowJavaModel;
import javamodel.ExcelRowJavaModel1;
import javamodel.IdentificationExcel;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @author jipengfei
* @date 2017/08/27
*/
public class Read2007Xlsx {
//创建没有自定义模型,没有sheet的解析器,默认解析所有sheet解析结果以List<String>的方式通知监听者
@Test
public void noModel() {
InputStream inputStream = getInputStream("2007.xlsx");
final List<List<String>> ll = new ArrayList<List<String>>();
try {
ExcelReader reader = new ExcelReader(inputStream, null,
new AnalysisEventListener<List<String>>() {
@Override
public void invoke(List<String> object, AnalysisContext context) {
System.out.println(
"当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum()
+ " data:" + object);
ll.add(object);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
});
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) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void withJavaModel() {
InputStream inputStream = getInputStream("2-拆分标识数据库.xlsx");
try {
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null,
new AnalysisEventListener<IdentificationExcel>() {
@Override
public void invoke(IdentificationExcel object, AnalysisContext context) {
System.out.println(
"当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum()
+ " data:" + object);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
});
reader.read(new Sheet(1, 1, IdentificationExcel.class));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//创建没有自定义模型,没有sheet的解析器,默认解析所有sheet解析结果以List<String>的方式通知监听者
@Test
public void noModelMultipleSheet() {
InputStream inputStream = getInputStream("2007NoModelMultipleSheet.xlsx");
try {
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null,
new AnalysisEventListener<List<String>>() {
@Override
public void invoke(List<String> object, AnalysisContext context) {
System.out.println(
"当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum()
+ " data:" + object);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
});
reader.read();
//reader.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void withModelMultipleSheet() {
InputStream inputStream = getInputStream("2007WithModelMultipleSheet.xlsx");
try {
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null,
new AnalysisEventListener() {
@Override
public void invoke(Object object, AnalysisContext context) {
ExcelRowJavaModel obj = null;
if (context.getCurrentSheet().getSheetNo() == 1) {
obj = (ExcelRowJavaModel)object;
}
if (context.getCurrentSheet().getSheetNo() == 2) {
obj = (ExcelRowJavaModel)object;
}
System.out.println(
"当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum()
+ " data:" + obj);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
});
reader.read(new Sheet(1, 2, ExcelRowJavaModel.class));
reader.read(new Sheet(2, 1, ExcelRowJavaModel1.class));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void withModelMultipleSheet1() {
InputStream inputStream = getInputStream("sss.xlsx");
try {
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null,
new AnalysisEventListener() {
@Override
public void invoke(Object object, AnalysisContext context) {
ExcelRowJavaModel1 obj = null;
if (context.getCurrentSheet().getSheetNo() == 1) {
obj = (ExcelRowJavaModel1)object;
}
//if (context.getCurrentSheet().getSheetNo() == 2) {
// obj = (ExcelRowJavaModel)object;
//}
System.out.println(
"当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum()
+ " data:" + obj);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
});
reader.read(new Sheet(1, 1, ExcelRowJavaModel1.class));
// reader.read(new Sheet(2, 1, ExcelRowJavaModel1.class));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//读取shets
@Test
public void getSheets() {
InputStream inputStream = getInputStream("2007NoModelMultipleSheet.xlsx");
try {
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null,
new AnalysisEventListener<List<String>>() {
@Override
public void invoke(List<String> object, AnalysisContext context) {
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
});
List<Sheet> sheets = reader.getSheets();
System.out.println(sheets);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//获取sheet后再单独一个sheet解析
@Test
public void getSheetsAndAnalysisNoModel() {
InputStream inputStream = getInputStream("2007NoModelMultipleSheet.xlsx");
try {
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null,
new AnalysisEventListener<List<String>>() {
@Override
public void invoke(List<String> object, AnalysisContext context) {
System.out.println(
"当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum()
+ " data:" + object);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
});
List<Sheet> sheets = reader.getSheets();
System.out.println(sheets);
for (Sheet sheet : sheets) {
reader.read(sheet);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取所有sheet后遍历解析解析结果含有java模型
*/
@Test
public void getSheetsAndAnalysisWithModel() {
InputStream inputStream = getInputStream("2007WithModelMultipleSheet.xlsx");
try {
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null,
new AnalysisEventListener<Object>() {
@Override
public void invoke(Object object, AnalysisContext context) {
ExcelRowJavaModel obj = null;
if (context.getCurrentSheet().getSheetNo() == 1) {
obj = (ExcelRowJavaModel)object;
}
if (context.getCurrentSheet().getSheetNo() == 2) {
obj = (ExcelRowJavaModel)object;
}
System.out.println(
"当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum()
+ " data:" + obj);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
});
List<Sheet> sheets = reader.getSheets();
System.out.println(sheets);
for (Sheet sheet : sheets) {
if (sheet.getSheetNo() == 1) {
sheet.setHeadLineMun(2);
sheet.setClazz(ExcelRowJavaModel.class);
}
if (sheet.getSheetNo() == 2) {
sheet.setHeadLineMun(1);
sheet.setClazz(ExcelRowJavaModel1.class);
}
reader.read(sheet);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 解析过程中断不再解析比如解析到某一行出错了后面不需要再解析了
*/
@Test
public void interrupt() {
InputStream inputStream = getInputStream("2007WithModelMultipleSheet.xlsx");
try {
ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null,
new AnalysisEventListener<Object>() {
@Override
public void invoke(Object object, AnalysisContext context) {
context.interrupt();
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
}
});
List<Sheet> sheets = reader.getSheets();
System.out.println(sheets);
for (Sheet sheet : sheets) {
if (sheet.getSheetNo() == 1) {
sheet.setHeadLineMun(2);
sheet.setClazz(ExcelRowJavaModel.class);
}
if (sheet.getSheetNo() == 2) {
sheet.setHeadLineMun(1);
sheet.setClazz(ExcelRowJavaModel1.class);
}
reader.read(sheet);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private InputStream getInputStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName);
}
}

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

@ -1,37 +0,0 @@
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.List;
/**
* @author jipengfei
* @date 2017/08/27
*/
public class Excel2007NoJavaModelAnalysisListener extends AnalysisEventListener {
private ExcelWriter excelWriter;
public ExcelWriter getExcelWriter() {
return excelWriter;
}
public void setExcelWriter(ExcelWriter excelWriter) {
this.excelWriter = excelWriter;
}
public void invoke(Object object, AnalysisContext context) {
List<List<String>> ll = new ArrayList<List<String>>();
ll.add((List<String>)object);
System.out.println(object);
excelWriter.write0(ll, context.getCurrentSheet());
}
public void doAfterAllAnalysed(AnalysisContext context) {
}
}

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

@ -1,40 +0,0 @@
package read.v07.listener;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import javamodel.ExcelRowJavaModel;
import java.util.ArrayList;
import java.util.List;
/**
* @author jipengfei
*/
public class Excel2007WithJavaModelAnalysisListener extends AnalysisEventListener {
private ExcelWriter excelWriter;
public ExcelWriter getExcelWriter() {
return excelWriter;
}
public void setExcelWriter(ExcelWriter excelWriter) {
this.excelWriter = excelWriter;
}
public void invoke(Object object, AnalysisContext context) {
List< BaseRowModel> ll = new ArrayList();
ll.add((BaseRowModel)object);
Sheet sheet = context.getCurrentSheet();
sheet.setClazz(ExcelRowJavaModel.class);
excelWriter.write(ll,sheet);
}
public void doAfterAllAnalysed(AnalysisContext context) {
}
}

BIN
src/test/resources/111.xlsx

Binary file not shown.

BIN
src/test/resources/1111.xlsx

Binary file not shown.

BIN
src/test/resources/2003.xls

Binary file not shown.

BIN
src/test/resources/2007.xlsx

Binary file not shown.

BIN
src/test/resources/2007NoModelBigFile.xlsx

Binary file not shown.

BIN
src/test/resources/2007NoModelMultipleSheet.xlsx

Binary file not shown.

BIN
src/test/resources/2007WithModel.xlsx

Binary file not shown.

BIN
src/test/resources/2007WithModelMultipleSheet.xlsx

Binary file not shown.

BIN
src/test/resources/2007_1.xlsx

Binary file not shown.

BIN
src/test/resources/77.xlsx

Binary file not shown.

BIN
src/test/resources/sss.xlsx

Binary file not shown.

BIN
src/test/resources/temp.xlsx

Binary file not shown.
Loading…
Cancel
Save