Browse Source

优化读写逻辑

bugfix
zhuangjiaju 5 years ago
parent
commit
5421722c24
  1. 80
      src/main/java/com/alibaba/excel/EasyExcelFactory.java
  2. 9
      src/main/java/com/alibaba/excel/ExcelReader.java
  3. 7
      src/main/java/com/alibaba/excel/ExcelWriter.java
  4. 17
      src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java
  5. 2
      src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java
  6. 14
      src/main/java/com/alibaba/excel/analysis/v07/handlers/DefaultCellHandler.java
  7. 4
      src/main/java/com/alibaba/excel/cache/Ehcache.java
  8. 4
      src/main/java/com/alibaba/excel/context/WriteContextImpl.java
  9. 23
      src/main/java/com/alibaba/excel/exception/ExcelAnalysisStopException.java
  10. 3
      src/main/java/com/alibaba/excel/metadata/BaseRowModel.java
  11. 44
      src/main/java/com/alibaba/excel/parameter/ExcelWriteParam.java
  12. 37
      src/main/java/com/alibaba/excel/read/builder/ExcelReaderBuilder.java
  13. 40
      src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java
  14. 6
      src/main/java/com/alibaba/excel/read/listener/ReadListener.java
  15. 16
      src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java
  16. 4
      src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java
  17. 28
      src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java
  18. 1
      src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java
  19. 46
      src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java
  20. 9
      src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java
  21. 10
      src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java
  22. 6
      src/main/java/com/alibaba/excel/write/merge/LoopMergeStrategy.java
  23. 7
      src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java
  24. 9
      src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java
  25. 26
      src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java
  26. 189
      src/test/java/com/alibaba/easyexcel/test/ReadTest.java
  27. 194
      src/test/java/com/alibaba/easyexcel/test/WriteTest.java
  28. 5
      src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java
  29. 22
      src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataListener.java
  30. 39
      src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java
  31. 143
      src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java
  32. 14
      src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java
  33. 14
      src/test/java/com/alibaba/easyexcel/test/core/exception/ExceptionData.java
  34. 48
      src/test/java/com/alibaba/easyexcel/test/core/exception/ExceptionDataListener.java
  35. 58
      src/test/java/com/alibaba/easyexcel/test/core/exception/ExceptionDataTest.java
  36. 14
      src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterData.java
  37. 35
      src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterDataListener.java
  38. 135
      src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterDataTest.java
  39. 2
      src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataTest.java
  40. 87
      src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java
  41. 59
      src/test/java/com/alibaba/easyexcel/test/listen/AfterExcelWriteHandlerImpl.java
  42. 33
      src/test/java/com/alibaba/easyexcel/test/listen/ExcelListener.java
  43. 28
      src/test/java/com/alibaba/easyexcel/test/model/BaseReadModel.java
  44. 28
      src/test/java/com/alibaba/easyexcel/test/model/BaseWriteModel.java
  45. 114
      src/test/java/com/alibaba/easyexcel/test/model/ReadModel.java
  46. 136
      src/test/java/com/alibaba/easyexcel/test/model/ReadModel2.java
  47. 131
      src/test/java/com/alibaba/easyexcel/test/model/WriteModel.java
  48. 93
      src/test/java/com/alibaba/easyexcel/test/util/DataUtil.java
  49. BIN
      src/test/resources/2003.xls
  50. BIN
      src/test/resources/2007.xlsx
  51. BIN
      src/test/resources/temp.xlsx

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

@ -3,11 +3,8 @@ package com.alibaba.excel;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
@ -64,15 +61,7 @@ public class EasyExcelFactory {
@Override
public void doAfterAllAnalysed(AnalysisContext context) {}
}, false).read(sheet);
if (rows.size() == 0 || !(rows.get(0) instanceof Map)) {
return rows;
}
List<Object> listRow = new ArrayList<Object>();
for (Object obj : rows) {
Map<Integer, String> oneRow = (Map<Integer, String>)obj;
listRow.add(new ArrayList<String>(new TreeMap<Integer, String>(oneRow).values()));
}
return listRow;
return rows;
}
/**
@ -267,32 +256,6 @@ public class EasyExcelFactory {
return excelWriterBuilder;
}
/**
* Build excel the write
*
* @param uri
* @return
*/
public static ExcelWriterBuilder write(URI uri) {
return write(uri, null);
}
/**
* Build excel the write
*
* @param uri
* @param head
* @return
*/
public static ExcelWriterBuilder write(URI uri, Class head) {
ExcelWriterBuilder excelWriterBuilder = new ExcelWriterBuilder();
excelWriterBuilder.file(uri);
if (head != null) {
excelWriterBuilder.head(head);
}
return excelWriterBuilder;
}
/**
* Build excel the 'writerSheet'
*
@ -495,47 +458,6 @@ public class EasyExcelFactory {
return excelReaderBuilder;
}
/**
* Build excel the read
*
* @param uri
* @return
*/
public static ExcelReaderBuilder read(URI uri) {
return read(uri, null, null);
}
/**
* Build excel the read
*
* @param uri
* @param readListener
* @return
*/
public static ExcelReaderBuilder read(URI uri, ReadListener readListener) {
return read(uri, null, readListener);
}
/**
* Build excel the read
*
* @param uri
* @param head
* @param readListener
* @return
*/
public static ExcelReaderBuilder read(URI uri, Class head, ReadListener readListener) {
ExcelReaderBuilder excelReaderBuilder = new ExcelReaderBuilder();
excelReaderBuilder.file(uri);
if (head != null) {
excelReaderBuilder.head(head);
}
if (readListener != null) {
excelReaderBuilder.registerReadListener(readListener);
}
return excelReaderBuilder;
}
/**
* Build excel the 'readSheet'
*

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

@ -137,6 +137,7 @@ public class ExcelReader {
readWorkbook.setMandatoryUseInputStream(Boolean.TRUE);
readWorkbook.setReadCache(new MapCache());
readWorkbook.setConvertAllFiled(Boolean.FALSE);
readWorkbook.setDefaultReturnMap(Boolean.FALSE);
excelAnalyser = new ExcelAnalyserImpl(readWorkbook);
}
@ -211,7 +212,7 @@ public class ExcelReader {
/**
* Context for the entire execution process
*
*
* @return
*/
public AnalysisContext analysisContext() {
@ -221,7 +222,7 @@ public class ExcelReader {
/**
* Current executor
*
*
* @return
*/
public ExcelExecutor excelExecutor() {
@ -252,7 +253,7 @@ public class ExcelReader {
}
/**
*
*
* @return
* @deprecated please use {@link #analysisContext()}
*/
@ -274,7 +275,7 @@ public class ExcelReader {
/**
* Prevents calls to {@link #finish} from freeing the cache
*
*
* @throws Throwable
*/
@Override

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

@ -5,7 +5,6 @@ import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.parameter.GenerateParam;
@ -187,17 +186,13 @@ public class ExcelWriter {
public ExcelWriter write(List data, Sheet sheet, Table table) {
WriteSheet writeSheet = null;
if (sheet != null) {
if (sheet.getStartRow() != 0) {
throw new ExcelGenerateException(
"Specifying a line to start is no longer supported.Please 'WriteSheet.relativeHeadRowIndex' him instead.");
}
writeSheet = new WriteSheet();
writeSheet.setSheetNo(sheet.getSheetNo() - 1);
writeSheet.setSheetName(sheet.getSheetName());
writeSheet.setClazz(sheet.getClazz());
writeSheet.setHead(sheet.getHead());
writeSheet.setTableStyle(sheet.getTableStyle());
writeSheet.setRelativeHeadRowIndex(sheet.getHeadLineMun());
writeSheet.setRelativeHeadRowIndex(sheet.getStartRow());
writeSheet.setColumnWidthMap(sheet.getColumnWidthMap());
}

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

@ -2,11 +2,15 @@ package com.alibaba.excel.analysis;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.analysis.v03.XlsSaxAnalyser;
import com.alibaba.excel.analysis.v07.XlsxSaxAnalyser;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.context.AnalysisContextImpl;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelAnalysisStopException;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.ReadWorkbook;
import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder;
@ -17,6 +21,7 @@ import com.alibaba.excel.util.FileUtils;
* @author jipengfei
*/
public class ExcelAnalyserImpl implements ExcelAnalyser {
private static final Logger LOGGER = LoggerFactory.getLogger(ExcelAnalyserImpl.class);
private AnalysisContext analysisContext;
@ -29,7 +34,7 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
} catch (RuntimeException e) {
finish();
throw e;
} catch (Throwable e) {
} catch (Exception e) {
finish();
throw new ExcelAnalysisException(e);
}
@ -56,12 +61,18 @@ public class ExcelAnalyserImpl implements ExcelAnalyser {
public void analysis(ReadSheet readSheet) {
try {
analysisContext.currentSheet(excelExecutor, readSheet);
excelExecutor.execute();
try {
excelExecutor.execute();
} catch (ExcelAnalysisStopException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Custom stop!");
}
}
analysisContext.readSheetHolder().notifyAfterAllAnalysed(analysisContext);
} catch (RuntimeException e) {
finish();
throw e;
} catch (Throwable e) {
} catch (Exception e) {
finish();
throw new ExcelAnalysisException(e);
}

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

@ -160,6 +160,8 @@ public class XlsxSaxAnalyser implements ExcelExecutor {
xmlReader.setContentHandler(handler);
xmlReader.parse(inputSource);
inputStream.close();
} catch (ExcelAnalysisException e) {
throw e;
} catch (Exception e) {
throw new ExcelAnalysisException(e);
} finally {

14
src/main/java/com/alibaba/excel/analysis/v07/handlers/DefaultCellHandler.java

@ -127,15 +127,23 @@ public class DefaultCellHandler implements XlsxCellHandler, XlsxRowResultHolder
case DIRECT_STRING:
case STRING:
case ERROR:
currentCellData.setStringValue(currentCellValue);
if (currentCellData.getStringValue() == null) {
currentCellData.setStringValue(currentCellValue);
} else {
currentCellData.setStringValue(currentCellData.getStringValue() + currentCellValue);
}
break;
case BOOLEAN:
currentCellData.setBooleanValue(BooleanUtils.valueOf(currentCellValue));
if (currentCellData.getBooleanValue() == null) {
currentCellData.setBooleanValue(BooleanUtils.valueOf(currentCellValue));
}
break;
case NUMBER:
case EMPTY:
currentCellData.setType(CellDataTypeEnum.NUMBER);
currentCellData.setDoubleValue(Double.valueOf(currentCellValue));
if (currentCellData.getDoubleValue() == null) {
currentCellData.setDoubleValue(Double.valueOf(currentCellValue));
}
break;
default:
throw new IllegalStateException("Cannot set values now");

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

@ -24,7 +24,7 @@ import com.alibaba.excel.util.StringUtils;
/**
* Default cache
*
*
* @author zhuangjiaju
*/
public class Ehcache implements ReadCache {
@ -66,7 +66,7 @@ public class Ehcache implements ReadCache {
private int getCount = 0;
/**
* Count active cache
*
*
*/
private LinkedList<Integer> countList = new LinkedList<Integer>();

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

@ -200,8 +200,8 @@ public class WriteContextImpl implements WriteContext {
}
int lastRowNum = writeSheetHolder.getSheet().getLastRowNum();
// 'lastRowNum' doesn't matter if it has one or zero,is's zero
if (lastRowNum == 0 && WriteLastRowType.HAVE_DATA == writeSheetHolder.getWriteLastRowType()) {
lastRowNum = 1;
if (WriteLastRowType.HAVE_DATA == writeSheetHolder.getWriteLastRowType()) {
lastRowNum++;
}
writeSheetHolder.setWriteLastRowType(WriteLastRowType.HAVE_DATA);
int rowIndex = lastRowNum + currentWriteHolder.relativeHeadRowIndex();

23
src/main/java/com/alibaba/excel/exception/ExcelAnalysisStopException.java

@ -0,0 +1,23 @@
package com.alibaba.excel.exception;
/**
* Throw the exception when you need to stop
*
* @author zhuangjiaju
*/
public class ExcelAnalysisStopException extends ExcelAnalysisException {
public ExcelAnalysisStopException() {}
public ExcelAnalysisStopException(String message) {
super(message);
}
public ExcelAnalysisStopException(String message, Throwable cause) {
super(message, cause);
}
public ExcelAnalysisStopException(Throwable cause) {
super(cause);
}
}

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

@ -5,6 +5,8 @@ import java.util.Map;
import org.apache.poi.ss.usermodel.CellStyle;
import com.alibaba.excel.annotation.ExcelIgnore;
/**
* Excel基础模型
*
@ -17,6 +19,7 @@ public class BaseRowModel {
/**
* 每列样式
*/
@ExcelIgnore
private Map<Integer, CellStyle> cellStyleMap = new HashMap<Integer, CellStyle>();
public void addStyle(Integer row, CellStyle cellStyle) {

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

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

37
src/main/java/com/alibaba/excel/read/builder/ExcelReaderBuilder.java

@ -2,7 +2,6 @@ package com.alibaba.excel.read.builder;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
@ -17,7 +16,7 @@ import com.alibaba.excel.support.ExcelTypeEnum;
/**
* Build ExcelWriter
*
*
* @author zhuangjiaju
*/
public class ExcelReaderBuilder {
@ -64,14 +63,6 @@ public class ExcelReaderBuilder {
return file(new File(pathName));
}
/**
* Read file
* <p>
* If 'inputStream' and 'file' all not empty,file first
*/
public ExcelReaderBuilder file(URI uri) {
return file(new File(uri));
}
/**
* Mandatory use 'inputStream' .Default is false.
@ -96,7 +87,7 @@ public class ExcelReaderBuilder {
/**
* This object can be read in the Listener {@link AnalysisEventListener#invoke(Object, AnalysisContext)}
* {@link AnalysisContext#getCustom()}
*
*
* @param customObject
* @return
*/
@ -107,7 +98,7 @@ public class ExcelReaderBuilder {
/**
* A cache that stores temp data to save memory.Default use {@link com.alibaba.excel.cache.Ehcache}
*
*
* @param readCache
* @return
*/
@ -116,29 +107,13 @@ public class ExcelReaderBuilder {
return this;
}
/**
* The default is all excel objects.if true , you can use {@link com.alibaba.excel.annotation.ExcelIgnore} ignore a
* field. if false , you must use {@link com.alibaba.excel.annotation.ExcelProperty} to use a filed.
* <p>
* Default true
*
* @param convertAllFiled
* @return
* @deprecated Just to be compatible with historical data, The default is always going to be convert all filed.
*/
@Deprecated
public ExcelReaderBuilder convertAllFiled(Boolean convertAllFiled) {
readWorkbook.setConvertAllFiled(convertAllFiled);
return this;
}
/**
* Count the number of added heads when read sheet.
*
* <li>0 - This Sheet has no head ,since the first row are the data
* <li>1 - This Sheet has one row head , this is the default
* <li>2 - This Sheet has two row head ,since the third row is the data
*
*
* @param headRowNumber
* @return
*/
@ -201,7 +176,7 @@ public class ExcelReaderBuilder {
* true if date uses 1904 windowing, or false if using 1900 date windowing.
*
* default is false
*
*
* @param use1904windowing
* @return
*/
@ -212,7 +187,7 @@ public class ExcelReaderBuilder {
/**
* Automatic trim includes sheet name and content
*
*
* @param autoTrim
* @return
*/

40
src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java

@ -1,6 +1,8 @@
package com.alibaba.excel.read.listener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.context.AnalysisContext;
@ -33,21 +35,37 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener
context.readRowHolder().setCurrentRowAnalysisResult(buildUserModel(cellDataMap, currentReadHolder));
return;
}
context.readRowHolder().setCurrentRowAnalysisResult(buildStringList(cellDataMap, currentReadHolder));
context.readRowHolder().setCurrentRowAnalysisResult(buildStringList(cellDataMap, currentReadHolder, context));
}
private Object buildStringList(Map<Integer, CellData> cellDataMap, ReadHolder currentReadHolder) {
Map<Integer, String> map = new HashMap<Integer, String>(cellDataMap.size() * 4 / 3 + 1);
for (Map.Entry<Integer, CellData> entry : cellDataMap.entrySet()) {
CellData cellData = entry.getValue();
if (cellData.getType() == CellDataTypeEnum.EMPTY) {
map.put(entry.getKey(), null);
continue;
private Object buildStringList(Map<Integer, CellData> cellDataMap, ReadHolder currentReadHolder,
AnalysisContext context) {
if (context.readWorkbookHolder().getDefaultReturnMap()) {
Map<Integer, String> map = new HashMap<Integer, String>(cellDataMap.size() * 4 / 3 + 1);
for (Map.Entry<Integer, CellData> entry : cellDataMap.entrySet()) {
CellData cellData = entry.getValue();
if (cellData.getType() == CellDataTypeEnum.EMPTY) {
map.put(entry.getKey(), null);
continue;
}
map.put(entry.getKey(), (String)convertValue(cellData, String.class, null,
currentReadHolder.converterMap(), currentReadHolder.globalConfiguration()));
}
return map;
} else {
// Compatible with the old code the old code returns a list
List<String> list = new ArrayList<String>();
for (Map.Entry<Integer, CellData> entry : cellDataMap.entrySet()) {
CellData cellData = entry.getValue();
if (cellData.getType() == CellDataTypeEnum.EMPTY) {
list.add(null);
continue;
}
list.add((String)convertValue(cellData, String.class, null, currentReadHolder.converterMap(),
currentReadHolder.globalConfiguration()));
}
map.put(entry.getKey(), (String)convertValue(cellData, String.class, null, currentReadHolder.converterMap(),
currentReadHolder.globalConfiguration()));
return list;
}
return map;
}
private Object buildUserModel(Map<Integer, CellData> cellDataMap, ReadHolder currentReadHolder) {

6
src/main/java/com/alibaba/excel/read/listener/ReadListener.java

@ -5,14 +5,14 @@ import com.alibaba.excel.event.Listener;
/**
* Interface to listen for read results
*
*
* @author zhuangjiaju
*/
public interface ReadListener<T> extends Listener {
/**
* All listeners receive this method when any one Listener does an error report. If an exception is thrown here, the
* entire read will terminate.
*
*
* @param exception
* @param context
* @throws Exception
@ -23,7 +23,7 @@ public interface ReadListener<T> extends Listener {
* when analysis one row trigger invoke function.
*
* @param data
* one row value. Is is same as {@link AnalysisContext#currentRowAnalysisResult()}
* one row value. Is is same as {@link AnalysisContext#readRowHolder()}
* @param context
* analysis context
*/

16
src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java

@ -53,12 +53,18 @@ public class ReadWorkbook extends ReadBasicParameter {
* The default is all excel objects.Default is true.
* <li>if true , you can use {@link com.alibaba.excel.annotation.ExcelIgnore} ignore a field.
* <li>if false , you must use {@link com.alibaba.excel.annotation.ExcelProperty} to use a filed.
*
*
* @deprecated Just to be compatible with historical data, The default is always going to be convert all filed.
*/
@Deprecated
private Boolean convertAllFiled;
/**
* List is returned by default, now map is returned by default
*/
@Deprecated
private Boolean defaultReturnMap;
public ExcelTypeEnum getExcelType() {
return excelType;
}
@ -122,4 +128,12 @@ public class ReadWorkbook extends ReadBasicParameter {
public void setConvertAllFiled(Boolean convertAllFiled) {
this.convertAllFiled = convertAllFiled;
}
public Boolean getDefaultReturnMap() {
return defaultReturnMap;
}
public void setDefaultReturnMap(Boolean defaultReturnMap) {
this.defaultReturnMap = defaultReturnMap;
}
}

4
src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java

@ -14,6 +14,7 @@ import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelAnalysisStopException;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.AbstractHolder;
import com.alibaba.excel.metadata.CellData;
@ -128,6 +129,9 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
}
}
}
if (!readListener.hasNext(analysisContext)) {
throw new ExcelAnalysisStopException();
}
}
return;
}

28
src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java

@ -1,5 +1,6 @@
package com.alibaba.excel.read.metadata.holder;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.HashSet;
@ -78,6 +79,12 @@ public class ReadWorkbookHolder extends AbstractReadHolder {
@Deprecated
private Boolean convertAllFiled;
/**
* List is returned by default, now map is returned by default
*/
@Deprecated
private Boolean defaultReturnMap;
/**
* Prevent repeating sheet
*/
@ -86,7 +93,13 @@ public class ReadWorkbookHolder extends AbstractReadHolder {
public ReadWorkbookHolder(ReadWorkbook readWorkbook) {
super(readWorkbook, null, readWorkbook.getConvertAllFiled());
this.readWorkbook = readWorkbook;
this.inputStream = readWorkbook.getInputStream();
if (readWorkbook.getInputStream() != null) {
if (readWorkbook.getInputStream().markSupported()) {
this.inputStream = readWorkbook.getInputStream();
} else {
this.inputStream = new BufferedInputStream(readWorkbook.getInputStream());
}
}
this.file = readWorkbook.getFile();
if (file == null && inputStream == null) {
throw new ExcelAnalysisException("File and inputStream must be a non-null.");
@ -114,6 +127,11 @@ public class ReadWorkbookHolder extends AbstractReadHolder {
if (readCache != null && ExcelTypeEnum.XLS == excelType) {
LOGGER.warn("Xls not support 'readCache'!");
}
if (readWorkbook.getDefaultReturnMap() == null) {
this.defaultReturnMap = Boolean.TRUE;
} else {
this.defaultReturnMap = readWorkbook.getDefaultReturnMap();
}
this.hasReadSheet = new HashSet<Integer>();
}
@ -205,6 +223,14 @@ public class ReadWorkbookHolder extends AbstractReadHolder {
this.hasReadSheet = hasReadSheet;
}
public Boolean getDefaultReturnMap() {
return defaultReturnMap;
}
public void setDefaultReturnMap(Boolean defaultReturnMap) {
this.defaultReturnMap = defaultReturnMap;
}
@Override
public HolderEnum holderType() {
return HolderEnum.WORKBOOK;

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

@ -36,7 +36,6 @@ public enum ExcelTypeEnum {
String fileName = file.getName();
if (fileName.endsWith(XLSX.getValue())) {
return XLSX;
} else if (fileName.endsWith(XLS.getValue())) {
return XLS;
} else {

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

@ -1,6 +1,8 @@
package com.alibaba.excel.write;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@ -18,6 +20,7 @@ import com.alibaba.excel.converters.ConverterKeyBuild;
import com.alibaba.excel.enums.WriteLastRowType;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
@ -50,7 +53,7 @@ public class ExcelBuilderImpl implements ExcelBuilder {
} catch (RuntimeException e) {
finish();
throw e;
} catch (Throwable e) {
} catch (Exception e) {
finish();
throw new ExcelGenerateException(e);
}
@ -73,9 +76,11 @@ public class ExcelBuilderImpl implements ExcelBuilder {
if (writeSheetHolder.isNew() && !writeSheetHolder.getExcelWriteHeadProperty().hasHead()) {
lastRowNum += context.currentWriteHolder().relativeHeadRowIndex();
}
// Beanmap is out of order,so use fieldList
List<Field> fieldList = new ArrayList<Field>();
for (int relativeRowIndex = 0; relativeRowIndex < data.size(); relativeRowIndex++) {
int n = relativeRowIndex + lastRowNum + 1;
addOneRowOfDataToExcel(data.get(relativeRowIndex), n, relativeRowIndex);
addOneRowOfDataToExcel(data.get(relativeRowIndex), n, relativeRowIndex, fieldList);
}
}
@ -93,7 +98,7 @@ public class ExcelBuilderImpl implements ExcelBuilder {
} catch (RuntimeException e) {
finish();
throw e;
} catch (Throwable e) {
} catch (Exception e) {
finish();
throw new ExcelGenerateException(e);
}
@ -112,14 +117,14 @@ public class ExcelBuilderImpl implements ExcelBuilder {
context.writeSheetHolder().getSheet().addMergedRegion(cra);
}
private void addOneRowOfDataToExcel(Object oneRowData, int n, int relativeRowIndex) {
private void addOneRowOfDataToExcel(Object oneRowData, int n, int relativeRowIndex, List<Field> fieldList) {
beforeRowCreate(n, relativeRowIndex);
Row row = WorkBookUtil.createRow(context.writeSheetHolder().getSheet(), n);
afterRowCreate(row, relativeRowIndex);
if (oneRowData instanceof List) {
addBasicTypeToExcel((List)oneRowData, row, relativeRowIndex);
} else {
addJavaObjectToExcel(oneRowData, row, relativeRowIndex);
addJavaObjectToExcel(oneRowData, row, relativeRowIndex, fieldList);
}
}
@ -188,7 +193,7 @@ public class ExcelBuilderImpl implements ExcelBuilder {
afterCellCreate(head, cell, relativeRowIndex);
}
private void addJavaObjectToExcel(Object oneRowData, Row row, int relativeRowIndex) {
private void addJavaObjectToExcel(Object oneRowData, Row row, int relativeRowIndex, List<Field> fieldList) {
WriteHolder currentWriteHolder = context.currentWriteHolder();
BeanMap beanMap = BeanMap.create(oneRowData);
Set<String> beanMapHandledSet = new HashSet<String>();
@ -220,19 +225,38 @@ public class ExcelBuilderImpl implements ExcelBuilder {
cellIndex++;
}
Map<String, Field> ignoreMap = context.currentWriteHolder().excelWriteHeadProperty().getIgnoreMap();
Set<Map.Entry<String, Object>> entrySet = beanMap.entrySet();
for (Map.Entry<String, Object> entry : entrySet) {
if (entry.getValue() == null || beanMapHandledSet.contains(entry.getKey())
|| ignoreMap.containsKey(entry.getKey())) {
initFieldList(oneRowData.getClass(), fieldList);
for (Field field : fieldList) {
String filedName = field.getName();
boolean uselessData = !beanMap.containsKey(filedName) || beanMapHandledSet.contains(filedName)
|| ignoreMap.containsKey(filedName);
if (uselessData) {
continue;
}
Object value = beanMap.get(filedName);
if (value == null) {
continue;
}
beforeCellCreate(row, null, relativeRowIndex);
Cell cell = WorkBookUtil.createCell(row, cellIndex++);
converterAndSet(currentWriteHolder, entry.getValue().getClass(), cell, entry.getValue(), null);
converterAndSet(currentWriteHolder, value.getClass(), cell, value, null);
afterCellCreate(null, cell, relativeRowIndex);
}
}
private void initFieldList(Class clazz, List<Field> fieldList) {
if (!fieldList.isEmpty()) {
return;
}
Class tempClass = clazz;
while (tempClass != null) {
if (tempClass != BaseRowModel.class) {
Collections.addAll(fieldList, tempClass.getDeclaredFields());
}
tempClass = tempClass.getSuperclass();
}
}
private void beforeCellCreate(Row row, Head head, int relativeRowIndex) {
List<WriteHandler> handlerList = context.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class);
if (handlerList == null || handlerList.isEmpty()) {

9
src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java

@ -3,7 +3,6 @@ package com.alibaba.excel.write.builder;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
@ -143,10 +142,6 @@ public class ExcelWriterBuilder {
return file(new File(outputPathName));
}
public ExcelWriterBuilder file(URI outputUri) {
return file(new File(outputUri));
}
public ExcelWriterBuilder withTemplate(InputStream templateInputStream) {
writeWorkbook.setTemplateInputStream(templateInputStream);
return this;
@ -161,10 +156,6 @@ public class ExcelWriterBuilder {
return withTemplate(new File(pathName));
}
public ExcelWriterBuilder withTemplate(URI uri) {
return withTemplate(new File(uri));
}
/**
* Write handler
*

10
src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java

@ -12,7 +12,7 @@ import com.alibaba.excel.write.metadata.WriteTable;
/**
* Build sheet
*
*
* @author zhuangjiaju
*/
public class ExcelWriterTableBuilder {
@ -32,6 +32,7 @@ public class ExcelWriterTableBuilder {
public ExcelWriterTableBuilder(ExcelWriter excelWriter, WriteSheet writeSheet) {
this.excelWriter = excelWriter;
this.writeSheet = writeSheet;
this.writeTable = new WriteTable();
}
/**
@ -128,4 +129,11 @@ public class ExcelWriterTableBuilder {
return new ExcelWriterTableBuilder(excelWriter, writeSheet);
}
public void finish() {
if (excelWriter == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.write().sheet()' to call this method");
}
excelWriter.finish();
}
}

6
src/main/java/com/alibaba/excel/write/merge/LoopMergeStrategy.java

@ -8,7 +8,7 @@ import com.alibaba.excel.metadata.Head;
/**
* The regions of the loop merge
*
*
* @author zhuangjiaju
*/
public class LoopMergeStrategy extends AbstractMergeStrategy {
@ -26,8 +26,8 @@ public class LoopMergeStrategy extends AbstractMergeStrategy {
@Override
protected void merge(Sheet sheet, Cell cell, Head head, int relativeRowIndex) {
if (relativeRowIndex % eachRow == 0 && head.getColumnIndex() % eachColumn == 0) {
CellRangeAddress cellRangeAddress = new CellRangeAddress(cell.getRowIndex(), cell.getRowIndex() + eachRow,
cell.getColumnIndex(), cell.getColumnIndex() + eachColumn);
CellRangeAddress cellRangeAddress = new CellRangeAddress(cell.getRowIndex(),
cell.getRowIndex() + eachRow - 1, cell.getColumnIndex(), cell.getColumnIndex() + eachColumn - 1);
sheet.addMergedRegion(cellRangeAddress);
}
}

7
src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java

@ -183,6 +183,7 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ
writeFont.setFontName(font.getFontName());
writeFont.setFontHeightInPoints(font.getFontHeightInPoints());
writeFont.setBold(font.isBold());
writeCellStyle.setWriteFont(writeFont);
}
return writeCellStyle;
}
@ -263,12 +264,16 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ
protected Map<Class<? extends WriteHandler>, List<WriteHandler>> sortAndClearUpHandler(
List<WriteHandler> handlerList, Map<Class<? extends WriteHandler>, List<WriteHandler>> parentHandlerMap) {
// add
Set<WriteHandler> noRepeatSet = new HashSet<WriteHandler>();
if (parentHandlerMap != null) {
for (List<WriteHandler> parentHandlerList : parentHandlerMap.values()) {
handlerList.addAll(parentHandlerList);
noRepeatSet.addAll(parentHandlerList);
}
}
handlerList.addAll(noRepeatSet);
// sort
Map<Integer, List<WriteHandler>> orderExcelWriteHandlerMap = new TreeMap<Integer, List<WriteHandler>>();
for (WriteHandler handler : handlerList) {

9
src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java

@ -1,5 +1,6 @@
package com.alibaba.excel.write.metadata.holder;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
@ -85,7 +86,13 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
} else {
this.outputStream = writeWorkbook.getOutputStream();
}
this.templateInputStream = writeWorkbook.getTemplateInputStream();
if (writeWorkbook.getTemplateInputStream() != null) {
if (writeWorkbook.getTemplateInputStream().markSupported()) {
this.templateInputStream = writeWorkbook.getTemplateInputStream();
} else {
this.templateInputStream = new BufferedInputStream(writeWorkbook.getTemplateInputStream());
}
}
this.templateFile = writeWorkbook.getTemplateFile();
if (writeWorkbook.getAutoCloseStream() == null) {
this.autoCloseStream = Boolean.TRUE;

26
src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java

@ -7,34 +7,42 @@ import org.apache.poi.ss.usermodel.Workbook;
import com.alibaba.excel.event.NotRepeatExecutor;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* Cell style strategy
*
*
* @author zhuangjiaju
*/
public abstract class AbstractCellStyleStrategy implements CellWriteHandler, WorkbookWriteHandler, NotRepeatExecutor {
public abstract class AbstractCellStyleStrategy implements CellWriteHandler, SheetWriteHandler, NotRepeatExecutor {
boolean hasInitialized = false;
@Override
public String uniqueValue() {
return "CellStyleStrategy";
}
@Override
public void beforeWorkbookCreate() {}
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
@Override
public void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) {
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
initCellStyle(writeWorkbookHolder.getWorkbook());
hasInitialized = true;
}
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Head head, int relativeRowIndex, boolean isHead) {
if (!hasInitialized) {
initCellStyle(writeSheetHolder.getParentWriteWorkbookHolder().getWorkbook());
hasInitialized = true;
}
}
@Override
@ -49,14 +57,14 @@ public abstract class AbstractCellStyleStrategy implements CellWriteHandler, Wor
/**
* Initialization cell style
*
*
* @param workbook
*/
protected abstract void initCellStyle(Workbook workbook);
/**
* Sets the cell style of header
*
*
* @param cell
* @param head
* @param relativeRowIndex
@ -65,7 +73,7 @@ public abstract class AbstractCellStyleStrategy implements CellWriteHandler, Wor
/**
* Sets the cell style of content
*
*
* @param cell
* @param head
* @param relativeRowIndex

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

@ -1,189 +0,0 @@
package com.alibaba.easyexcel.test;
import com.alibaba.easyexcel.test.listen.ExcelListener;
import com.alibaba.easyexcel.test.model.ReadModel;
import com.alibaba.easyexcel.test.model.ReadModel2;
import com.alibaba.easyexcel.test.util.TestFileUtil;
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 = TestFileUtil.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 = TestFileUtil.getResourcesFileInputStream("2007.xlsx");
List<Object> data = EasyExcelFactory.read(inputStream, new Sheet(2, 1, ReadModel.class));
inputStream.close();
print(data);
}
/**
* 07版本excel读数据量大于1千行内部采用回调方法.
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void saxReadListStringV2007() throws IOException {
InputStream inputStream = TestFileUtil.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 = TestFileUtil.getResourcesFileInputStream("2007.xlsx");
ExcelListener excelListener = new ExcelListener();
EasyExcelFactory.readBySax(inputStream, new Sheet(2, 1, ReadModel.class), excelListener);
inputStream.close();
}
/**
* 07版本excel读取sheet
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void saxReadSheetsV2007() throws IOException {
InputStream inputStream = TestFileUtil.getResourcesFileInputStream("2007.xlsx");
ExcelListener excelListener = new ExcelListener();
ExcelReader excelReader = EasyExcelFactory.getReader(inputStream,excelListener);
List<Sheet> sheets = excelReader.getSheets();
System.out.println("llll****"+sheets);
System.out.println();
for (Sheet sheet:sheets) {
if(sheet.getSheetNo() ==1) {
excelReader.read(sheet);
}else if(sheet.getSheetNo() ==2){
sheet.setHeadLineMun(1);
sheet.setClazz(ReadModel.class);
excelReader.read(sheet);
}else if(sheet.getSheetNo() ==3){
sheet.setHeadLineMun(1);
sheet.setClazz(ReadModel2.class);
excelReader.read(sheet);
}
}
inputStream.close();
}
/**
* 03版本excel读数据量少于1千行数据内部采用回调方法.
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void simpleReadListStringV2003() throws IOException {
InputStream inputStream = TestFileUtil.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 = TestFileUtil.getResourcesFileInputStream("2003.xls");
List<Object> data = EasyExcelFactory.read(inputStream, new Sheet(2, 1, ReadModel.class));
inputStream.close();
print(data);
}
/**
* 03版本excel读数据量大于1千行数据内部采用回调方法.
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void saxReadListStringV2003() throws IOException {
InputStream inputStream = TestFileUtil.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 = TestFileUtil.getResourcesFileInputStream("2003.xls");
ExcelListener excelListener = new ExcelListener();
EasyExcelFactory.readBySax(inputStream, new Sheet(2, 1, ReadModel.class), excelListener);
inputStream.close();
}
/**
* 00版本excel读取sheet
*
* @throws IOException 简单抛出异常真实环境需要catch异常,同时在finally中关闭流
*/
@Test
public void saxReadSheetsV2003() throws IOException {
InputStream inputStream = TestFileUtil.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(ReadModel.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);
}
}
}

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

@ -1,194 +0,0 @@
package com.alibaba.easyexcel.test;
import com.alibaba.easyexcel.test.listen.AfterExcelWriteHandlerImpl;
import com.alibaba.easyexcel.test.model.WriteModel;
import com.alibaba.easyexcel.test.util.TestFileUtil;
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, WriteModel.class, "第二个sheet", null);
sheet2.setTableStyle(createTableStyle());
//writer.write1(null, sheet2);
writer.write(createTestListJavaMode(), sheet2);
//需要合并单元格
writer.merge(5,20,1,1);
//写第三个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(WriteModel.class);
writer.write(createTestListJavaMode(), sheet3, table2);
writer.finish();
out.close();
}
@Test
public void writeV2007WithTemplate() throws IOException {
InputStream inputStream = TestFileUtil.getResourcesFileInputStream("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, WriteModel.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(WriteModel.class);
writer.write(createTestListJavaMode(), sheet3, table2);
writer.finish();
out.close();
}
@Test
public void writeV2007WithTemplateAndHandler() throws IOException {
InputStream inputStream = TestFileUtil.getResourcesFileInputStream("temp.xlsx");
OutputStream out = new FileOutputStream("/Users/jipengfei/2007.xlsx");
ExcelWriter writer = EasyExcelFactory.getWriterWithTempAndHandler(inputStream,out,ExcelTypeEnum.XLSX,true,
new AfterExcelWriteHandlerImpl());
//写第一个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, WriteModel.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(WriteModel.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, WriteModel.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(WriteModel.class);
writer.write(createTestListJavaMode(), sheet3, table2);
writer.finish();
out.close();
}
}

5
src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java

@ -37,8 +37,9 @@ public class AnnotationDataTest {
}
private void readAndWrite(File file) throws Exception {
EasyExcelFactory.write(file, AnnotationData.class).sheet().doWrite(data()).finish();
EasyExcelFactory.read(file, AnnotationData.class, new AnnotationDataListener()).sheet().doRead().finish();
EasyExcelFactory.write().file(file).head(AnnotationData.class).sheet().doWrite(data()).finish();
EasyExcelFactory.read().file(file).head(AnnotationData.class).registerReadListener(new AnnotationDataListener())
.sheet().doRead().finish();
}
private List<AnnotationData> data() throws Exception {

22
src/test/java/com/alibaba/easyexcel/test/core/compatibility/AnnotationDataListener.java → src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataListener.java

@ -1,6 +1,5 @@
package com.alibaba.easyexcel.test.core.compatibility;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
@ -8,35 +7,28 @@ import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.easyexcel.test.core.annotation.AnnotationData;
import com.alibaba.easyexcel.test.core.annotation.AnnotationDataListener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelCommonException;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class AnnotationDataListener extends AnalysisEventListener<AnnotationData> {
public class CompatibilityDataListener extends AnalysisEventListener<List<String>> {
private static final Logger LOGGER = LoggerFactory.getLogger(AnnotationDataListener.class);
List<AnnotationData> list = new ArrayList<AnnotationData>();
List<List<String>> list = new ArrayList<List<String>>();
@Override
public void invoke(AnnotationData data, AnalysisContext context) {
public void invoke(List<String> data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 1);
AnnotationData data = list.get(0);
try {
Assert.assertEquals(data.getDate(), DateUtils.parseDate("2020-01-01 01:01:01"));
} catch (ParseException e) {
throw new ExcelCommonException("Test Exception", e);
}
Assert.assertEquals(data.getNumber(), 99.99, 0.00);
Assert.assertEquals(list.size(), 10);
List<String> data = list.get(0);
Assert.assertEquals(data.get(0), "字符串00");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

39
src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java

@ -1,7 +1,9 @@
package com.alibaba.easyexcel.test.core.compatibility;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
@ -9,16 +11,20 @@ import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
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.parameter.AnalysisParam;
import com.alibaba.excel.parameter.GenerateParam;
/**
*
@ -47,8 +53,12 @@ public class CompatibilityDataTest {
private void readAndWrite(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = EasyExcelFactory.getWriter(out);
// sheet1 width,string head,stirng data
GenerateParam generateParam = new GenerateParam("", null, out);
generateParam.setSheetName("");
generateParam.setOutputStream(out);
generateParam.setClazz(null);
ExcelWriter writer = new ExcelWriter(generateParam);
// sheet1 width,string head,string data
Sheet sheet1 = new Sheet(1, 3);
sheet1.setSheetName("第一个sheet");
Map columnWidth = new HashMap();
@ -60,8 +70,10 @@ public class CompatibilityDataTest {
// sheet2 style,class head
Sheet sheet2 = new Sheet(2, 3, CompatibilityData.class, "第二个sheet", null);
sheet2.setStartRow(5);
sheet2.setTableStyle(style());
writer.write(data(), sheet2);
writer.merge(8, 8, 0, 1);
// sheet3 table
Sheet sheet3 = new Sheet(3, 0);
@ -78,8 +90,23 @@ public class CompatibilityDataTest {
writer.finish();
out.close();
// EasyExcelFactory.write(file, AnnotationData.class).sheet().doWrite(data()).finish();
// EasyExcelFactory.read(file, AnnotationData.class, new AnnotationDataListener()).sheet().doRead().finish();
InputStream inputStream = new FileInputStream(file);
List<Object> data = EasyExcelFactory.read(inputStream, new Sheet(1, 1));
Assert.assertEquals(data.size(), 1);
List<String> dataList = (List<String>)data.get(0);
Assert.assertEquals(dataList.get(0), "字符串00");
inputStream.close();
inputStream = new FileInputStream(file);
AnalysisParam param = new AnalysisParam(inputStream, null, new Object());
param.setIn(inputStream);
param.setExcelTypeEnum(null);
param.setCustomContent(null);
ExcelReader excelReader = new ExcelReader(param, new CompatibilityDataListener());
excelReader.read(new Sheet(2, 6));
Assert.assertEquals(excelReader.getSheets().size(), 3);
Assert.assertTrue(excelReader.getAnalysisContext() != null);
inputStream.close();
}
private List<List<String>> head() {
@ -96,8 +123,8 @@ public class CompatibilityDataTest {
private List<List<Object>> listData() {
List<List<Object>> list = new ArrayList<List<Object>>();
List<Object> data0 = new ArrayList<Object>();
data0.add("字符串0");
data0.add(1);
data0.add("字符串00");
data0.add(11);
list.add(data0);
return list;
}

143
src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java

@ -0,0 +1,143 @@
package com.alibaba.easyexcel.test.core.compatibility;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
/**
*
* @author zhuangjiaju
*/
public class CompatibilityParameterDataTest {
private static File file;
@BeforeClass
public static void init() {
file = TestFileUtil.createNewFile("compatibilityParameter.xlsx");
}
@Test
public void T01ReadAndWrite() throws Exception {
readAndWrite1(file);
readAndWrite2(file);
readAndWrite3(file);
readAndWrite4(file);
readAndWrite5(file);
readAndWrite6(file);
}
private void readAndWrite1(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = EasyExcelFactory.getWriter(out);
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(data(), sheet1);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
EasyExcelFactory.readBySax(inputStream, new Sheet(1, 0), new CompatibilityDataListener());
inputStream.close();
}
private void readAndWrite2(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = EasyExcelFactory.getWriter(out, null, false);
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(data(), sheet1);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
EasyExcelFactory.readBySax(inputStream, new Sheet(1, 0), new CompatibilityDataListener());
inputStream.close();
}
private void readAndWrite3(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = new ExcelWriter(out, null);
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(data(), sheet1);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
ExcelReader excelReader = new ExcelReader(inputStream, null, null, new CompatibilityDataListener());
excelReader.read(new Sheet(1, 0));
inputStream.close();
}
private void readAndWrite4(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = new ExcelWriter(null, out, null, null);
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(data(), sheet1, null);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
ExcelReader excelReader = new ExcelReader(inputStream, null, new CompatibilityDataListener());
excelReader.read(new Sheet(1, 0));
inputStream.close();
}
private void readAndWrite5(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = EasyExcelFactory.getWriterWithTemp(null, out, null, false);
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(data(), sheet1, null);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
ExcelReader excelReader = EasyExcelFactory.getReader(inputStream, new CompatibilityDataListener());
excelReader.read(new Sheet(1, 0));
inputStream.close();
}
private void readAndWrite6(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = EasyExcelFactory.getWriterWithTempAndHandler(null, out, null, false, null);
Sheet sheet1 = new Sheet(1, 0);
sheet1.setSheetName("第一个sheet");
writer.write0(data(), sheet1, null);
writer.finish();
out.close();
InputStream inputStream = new FileInputStream(file);
ExcelReader excelReader = EasyExcelFactory.getReader(inputStream, new CompatibilityDataListener());
excelReader.read(new Sheet(1, 0));
inputStream.close();
}
private List<CompatibilityData> data() {
List<CompatibilityData> list = new ArrayList<CompatibilityData>();
for (int i = 0; i < 10; i++) {
CompatibilityData data = new CompatibilityData();
data.setString0("字符串0" + i);
data.setString1("字符串1" + i);
list.add(data);
}
return list;
}
}

14
src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java

@ -0,0 +1,14 @@
package com.alibaba.easyexcel.test.core.compatibility;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class CompatibilityReadData extends BaseRowModel {
private String string0;
private String string1;
}

14
src/test/java/com/alibaba/easyexcel/test/core/exception/ExceptionData.java

@ -0,0 +1,14 @@
package com.alibaba.easyexcel.test.core.exception;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class ExceptionData {
@ExcelProperty("姓名")
private String name;
}

48
src/test/java/com/alibaba/easyexcel/test/core/exception/ExceptionDataListener.java

@ -0,0 +1,48 @@
package com.alibaba.easyexcel.test.core.exception;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class ExceptionDataListener extends AnalysisEventListener<ExceptionData> {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionData.class);
List<ExceptionData> list = new ArrayList<ExceptionData>();
@Override
public void onException(Exception exception, AnalysisContext context) {
LOGGER.info("抛出异常,忽略:{}", exception.getMessage());
}
@Override
public boolean hasNext(AnalysisContext context) {
return list.size() != 8;
}
@Override
public void invoke(ExceptionData data, AnalysisContext context) {
list.add(data);
if (list.size() == 5) {
int i = 5 / 0;
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 8);
Assert.assertEquals(list.get(0).getName(), "姓名0");
Assert.assertEquals((int)(context.readSheetHolder().getSheetNo()), 0);
Assert.assertEquals(
context.readSheetHolder().getExcelReadHeadProperty().getHeadMap().get(0).getHeadNameList().get(0), "姓名");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

58
src/test/java/com/alibaba/easyexcel/test/core/exception/ExceptionDataTest.java

@ -0,0 +1,58 @@
package com.alibaba.easyexcel.test.core.exception;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
/**
*
* @author zhuangjiaju
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ExceptionDataTest {
private static File file07;
private static File file03;
@BeforeClass
public static void init() {
file07 = TestFileUtil.createNewFile("simple07.xlsx");
file03 = TestFileUtil.createNewFile("simple03.xls");
}
@Test
public void T01ReadAndWrite07() throws Exception {
readAndWrite(file07);
}
@Test
public void T02ReadAndWrite03() throws Exception {
readAndWrite(file03);
}
private void readAndWrite(File file) throws Exception {
EasyExcelFactory.write(new FileOutputStream(file), ExceptionData.class).sheet().doWrite(data()).finish();
EasyExcelFactory.read(new FileInputStream(file), ExceptionData.class, new ExceptionDataListener()).sheet()
.doRead().finish();
}
private List<ExceptionData> data() {
List<ExceptionData> list = new ArrayList<ExceptionData>();
for (int i = 0; i < 10; i++) {
ExceptionData simpleData = new ExceptionData();
simpleData.setName("姓名" + i);
list.add(simpleData);
}
return list;
}
}

14
src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterData.java

@ -0,0 +1,14 @@
package com.alibaba.easyexcel.test.core.parameter;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class ParameterData {
@ExcelProperty("姓名")
private String name;
}

35
src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterDataListener.java

@ -0,0 +1,35 @@
package com.alibaba.easyexcel.test.core.parameter;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class ParameterDataListener extends AnalysisEventListener<ParameterData> {
private static final Logger LOGGER = LoggerFactory.getLogger(ParameterDataListener.class);
List<ParameterData> list = new ArrayList<ParameterData>();
@Override
public void invoke(ParameterData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 10);
Assert.assertEquals(list.get(0).getName(), "姓名0");
Assert.assertEquals((int)(context.readSheetHolder().getSheetNo()), 0);
Assert.assertEquals(
context.readSheetHolder().getExcelReadHeadProperty().getHeadMap().get(0).getHeadNameList().get(0), "姓名");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

135
src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterDataTest.java

@ -0,0 +1,135 @@
package com.alibaba.easyexcel.test.core.parameter;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.cache.MapCache;
import com.alibaba.excel.converters.string.StringStringConverter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
/**
*
* @author zhuangjiaju
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ParameterDataTest {
private static File file;
@BeforeClass
public static void init() {
file = TestFileUtil.createNewFile("parameter07.xlsx");
}
@Test
public void T01ReadAndWrite() throws Exception {
readAndWrite1();
readAndWrite2();
readAndWrite3();
readAndWrite4();
readAndWrite5();
readAndWrite6();
readAndWrite7();
}
private void readAndWrite1() {
EasyExcelFactory.write(file.getPath()).head(ParameterData.class).sheet().doWrite(data()).finish();
EasyExcelFactory.read(file.getPath()).head(ParameterData.class)
.registerReadListener(new ParameterDataListener()).sheet().doRead().finish();
}
private void readAndWrite2() {
EasyExcelFactory.write(file.getPath(), ParameterData.class).sheet().doWrite(data()).finish();
EasyExcelFactory.read(file.getPath(), ParameterData.class, new ParameterDataListener()).sheet().doRead()
.finish();
}
private void readAndWrite3() throws Exception {
EasyExcelFactory.write(new FileOutputStream(file)).head(ParameterData.class).sheet().doWrite(data()).finish();
EasyExcelFactory.read(file.getPath()).head(ParameterData.class)
.registerReadListener(new ParameterDataListener()).sheet().doRead().finish();
}
private void readAndWrite4() throws Exception {
EasyExcelFactory.write(new FileOutputStream(file), ParameterData.class).sheet().doWrite(data()).finish();
EasyExcelFactory.read(file.getPath(), new ParameterDataListener()).head(ParameterData.class).sheet().doRead()
.finish();
}
private void readAndWrite5() throws Exception {
ExcelWriter excelWriter = EasyExcelFactory.write(new FileOutputStream(file)).head(ParameterData.class)
.relativeHeadRowIndex(0).build();
WriteSheet writeSheet = EasyExcelFactory.writerSheet(0).relativeHeadRowIndex(0).needHead(Boolean.FALSE).build();
WriteTable writeTable = EasyExcelFactory.writerTable(0).relativeHeadRowIndex(0).needHead(Boolean.TRUE).build();
excelWriter.write(data(), writeSheet, writeTable);
excelWriter.finish();
ExcelReader excelReader =
EasyExcelFactory.read(file.getPath(), new ParameterDataListener()).head(ParameterData.class)
.mandatoryUseInputStream(Boolean.FALSE).autoCloseStream(Boolean.TRUE).readCache(new MapCache()).build();
ReadSheet readSheet = EasyExcelFactory.readSheet().head(ParameterData.class).use1904windowing(Boolean.FALSE)
.headRowNumber(1).sheetNo(0).sheetName("0").build();
excelReader.read(readSheet);
excelReader.finish();
excelReader = EasyExcelFactory.read(file.getPath(), new ParameterDataListener()).head(ParameterData.class)
.mandatoryUseInputStream(Boolean.FALSE).autoCloseStream(Boolean.TRUE).readCache(new MapCache()).build();
excelReader.read();
excelReader.finish();
}
private void readAndWrite6() throws Exception {
ExcelWriter excelWriter = EasyExcelFactory.write(new FileOutputStream(file)).head(ParameterData.class)
.relativeHeadRowIndex(0).build();
WriteSheet writeSheet = EasyExcelFactory.writerSheet(0).relativeHeadRowIndex(0).needHead(Boolean.FALSE).build();
WriteTable writeTable = EasyExcelFactory.writerTable(0).registerConverter(new StringStringConverter())
.relativeHeadRowIndex(0).needHead(Boolean.TRUE).build();
excelWriter.write(data(), writeSheet, writeTable);
excelWriter.finish();
ExcelReader excelReader =
EasyExcelFactory.read(file.getPath(), new ParameterDataListener()).head(ParameterData.class)
.mandatoryUseInputStream(Boolean.FALSE).autoCloseStream(Boolean.TRUE).readCache(new MapCache()).build();
ReadSheet readSheet = EasyExcelFactory.readSheet("0").head(ParameterData.class).use1904windowing(Boolean.FALSE)
.headRowNumber(1).sheetNo(0).build();
excelReader.read(readSheet);
excelReader.finish();
excelReader = EasyExcelFactory.read(file.getPath(), new ParameterDataListener()).head(ParameterData.class)
.mandatoryUseInputStream(Boolean.FALSE).autoCloseStream(Boolean.TRUE).readCache(new MapCache()).build();
excelReader.read();
excelReader.finish();
}
private void readAndWrite7() throws Exception {
EasyExcelFactory.write(file, ParameterData.class).registerConverter(new StringStringConverter()).sheet()
.registerConverter(new StringStringConverter()).needHead(Boolean.FALSE).table(0).needHead(Boolean.TRUE)
.doWrite(data()).finish();
EasyExcelFactory.read(file.getPath()).head(ParameterData.class)
.registerReadListener(new ParameterDataListener()).sheet().registerConverter(new StringStringConverter())
.doRead().finish();
}
private List<ParameterData> data() {
List<ParameterData> list = new ArrayList<ParameterData>();
for (int i = 0; i < 10; i++) {
ParameterData simpleData = new ParameterData();
simpleData.setName("姓名" + i);
list.add(simpleData);
}
return list;
}
}

2
src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataTest.java

@ -70,7 +70,7 @@ public class RepetitionDataTest {
private void readAndWriteTable(File file) {
ExcelWriter excelWriter = EasyExcelFactory.write(file, RepetitionData.class).build();
WriteSheet writeSheet = EasyExcelFactory.writerSheet(0).build();
WriteTable writeTable = EasyExcelFactory.writerTable(0).build();
WriteTable writeTable = EasyExcelFactory.writerTable(0).relativeHeadRowIndex(0).build();
excelWriter.write(data(), writeSheet, writeTable).write(data(), writeSheet, writeTable).finish();
ExcelReader excelReader =
EasyExcelFactory.read(file, RepetitionData.class, new RepetitionDataListener()).build();

87
src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java

@ -4,8 +4,12 @@ import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
@ -13,8 +17,12 @@ import org.junit.runners.MethodSorters;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
@ -45,6 +53,70 @@ public class StyleDataTest {
readAndWrite(file03);
}
@Test
public void T03AbstractVerticalCellStyleStrategy() {
AbstractVerticalCellStyleStrategy verticalCellStyleStrategy = new AbstractVerticalCellStyleStrategy() {
@Override
protected WriteCellStyle headCellStyle(Head head) {
WriteCellStyle writeCellStyle = new WriteCellStyle();
writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
writeCellStyle.setDataFormat((short)0);
writeCellStyle.setHidden(false);
writeCellStyle.setLocked(true);
writeCellStyle.setQuotePrefix(true);
writeCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
writeCellStyle.setWrapped(true);
writeCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
writeCellStyle.setRotation((short)0);
writeCellStyle.setIndent((short)10);
writeCellStyle.setBorderLeft(BorderStyle.THIN);
writeCellStyle.setBorderRight(BorderStyle.THIN);
writeCellStyle.setBorderTop(BorderStyle.THIN);
writeCellStyle.setBorderBottom(BorderStyle.THIN);
writeCellStyle.setLeftBorderColor(IndexedColors.RED.getIndex());
writeCellStyle.setRightBorderColor(IndexedColors.RED.getIndex());
writeCellStyle.setTopBorderColor(IndexedColors.RED.getIndex());
writeCellStyle.setBottomBorderColor(IndexedColors.RED.getIndex());
writeCellStyle.setFillBackgroundColor(IndexedColors.RED.getIndex());
writeCellStyle.setShrinkToFit(Boolean.TRUE);
if (head.getColumnIndex() == 0) {
writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
WriteFont writeFont = new WriteFont();
writeFont.setItalic(true);
writeFont.setStrikeout(true);
writeFont.setTypeOffset(Font.SS_NONE);
writeFont.setUnderline(Font.U_DOUBLE);
writeFont.setBold(true);
writeFont.setCharset((int)Font.DEFAULT_CHARSET);
} else {
writeCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
}
return writeCellStyle;
}
@Override
protected WriteCellStyle contentCellStyle(Head head) {
WriteCellStyle writeCellStyle = new WriteCellStyle();
writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
if (head.getColumnIndex() == 0) {
writeCellStyle.setFillForegroundColor(IndexedColors.DARK_GREEN.getIndex());
} else {
writeCellStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
}
return writeCellStyle;
}
};
EasyExcelFactory.write(file07, StyleData.class).registerWriteHandler(verticalCellStyleStrategy).sheet()
.doWrite(data()).finish();
}
@Test
public void T04LoopMergeStrategy() {
EasyExcelFactory.write(file07, StyleData.class).sheet().registerWriteHandler(new LoopMergeStrategy(2, 1))
.doWrite(data10()).finish();
}
private void readAndWrite(File file) {
SimpleColumnWidthStyleStrategy simpleColumnWidthStyleStrategy = new SimpleColumnWidthStyleStrategy(50);
SimpleRowHeightStyleStrategy simpleRowHeightStyleStrategy =
@ -63,9 +135,11 @@ public class StyleDataTest {
headWriteCellStyle.setWriteFont(contentWriteFont);
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
OnceAbsoluteMergeStrategy onceAbsoluteMergeStrategy = new OnceAbsoluteMergeStrategy(2, 2, 0, 1);
EasyExcelFactory.write(file, StyleData.class).registerWriteHandler(simpleColumnWidthStyleStrategy)
.registerWriteHandler(simpleRowHeightStyleStrategy).registerWriteHandler(horizontalCellStyleStrategy)
.sheet().doWrite(data()).finish();
.registerWriteHandler(onceAbsoluteMergeStrategy).sheet().doWrite(data()).finish();
EasyExcelFactory.read(file, StyleData.class, new StyleDataListener()).sheet().doRead().finish();
}
@ -81,4 +155,15 @@ public class StyleDataTest {
list.add(data1);
return list;
}
private List<StyleData> data10() {
List<StyleData> list = new ArrayList<StyleData>();
for (int i = 0; i < 10; i++) {
StyleData data = new StyleData();
data.setString("字符串0");
data.setString1("字符串01");
list.add(data);
}
return list;
}
}

59
src/test/java/com/alibaba/easyexcel/test/listen/AfterExcelWriteHandlerImpl.java

@ -1,59 +0,0 @@
package com.alibaba.easyexcel.test.listen;
import com.alibaba.excel.event.WriteHandler;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
public class AfterExcelWriteHandlerImpl implements WriteHandler {
//
CellStyle cellStyle;
@Override
public void sheet(int sheetNo, Sheet sheet) {
Workbook workbook = sheet.getWorkbook();
//要锁定单元格需先为此表单设置保护密码,设置之后此表单默认为所有单元格锁定,可使用setLocked(false)为指定单元格设置不锁定。
//设置表单保护密码
sheet.protectSheet("your password");
//创建样式
cellStyle = workbook.createCellStyle();
//设置是否锁
cellStyle.setLocked(false);
}
@Override
public void row(int rowNum, Row row) {
Workbook workbook = row.getSheet().getWorkbook();
//设置行高
row.setHeight((short)20);
}
@Override
public void cell(int cellNum, Cell cell) {
Workbook workbook = cell.getSheet().getWorkbook();
Sheet currentSheet = cell.getSheet();
if (cellNum == 4 && cell.getRowIndex() == 30) {
//设置样式
//注意:样式最好采用公用样式,样式在创建sheet后创建,如果有多个样式也需要在创建sheet时候创建后面直接使用,不要每个Cell Create 一个样式,不然会导致报错 The maximum number
// of Cell Styles was exceeded.
cell.setCellStyle(cellStyle);
//设置备注
Drawing draw = currentSheet.createDrawingPatriarch();
Comment comment = draw.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, 4, 25, 9, 30));
XSSFRichTextString rtf = new XSSFRichTextString("添加批注内容收到货死的死哦多胡搜idsad是否会杜甫的范德萨发!1111");
Font commentFormatter = workbook.createFont();
commentFormatter.setFontName("宋体");
//设置字体大小
commentFormatter.setFontHeightInPoints((short)9);
rtf.applyFont(commentFormatter);
comment.setString(rtf);
comment.setAuthor("ceshi");
cell.setCellComment(comment);
}
}
}

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

@ -1,33 +0,0 @@
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());
data.add(object);
if(data.size()>=100){
doSomething();
data = new ArrayList<Object>();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
doSomething();
}
public void doSomething(){
for (Object o:data) {
System.out.println(o);
}
}
}

28
src/test/java/com/alibaba/easyexcel/test/model/BaseReadModel.java

@ -1,28 +0,0 @@
package com.alibaba.easyexcel.test.model;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
public class BaseReadModel extends BaseRowModel {
@ExcelProperty(index = 0)
protected String str;
@ExcelProperty(index = 1)
protected Float ff;
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;
}
}

28
src/test/java/com/alibaba/easyexcel/test/model/BaseWriteModel.java

@ -1,28 +0,0 @@
package com.alibaba.easyexcel.test.model;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
public class BaseWriteModel extends BaseRowModel {
@ExcelProperty(value = {"表头1","表头1","表头31"},index = 0)
protected String p1;
@ExcelProperty(value = {"表头1","表头1","表头32"},index = 1)
protected String p2;
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;
}
}

114
src/test/java/com/alibaba/easyexcel/test/model/ReadModel.java

@ -1,114 +0,0 @@
package com.alibaba.easyexcel.test.model;
import com.alibaba.excel.annotation.ExcelProperty;
import java.math.BigDecimal;
import java.util.Date;
public class ReadModel extends BaseReadModel {
@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 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 + '\'' +
'}';
}
}

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

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

131
src/test/java/com/alibaba/easyexcel/test/model/WriteModel.java

@ -1,131 +0,0 @@
package com.alibaba.easyexcel.test.model;
import com.alibaba.excel.annotation.ExcelProperty;
import java.math.BigDecimal;
import java.util.Date;
public class WriteModel extends BaseWriteModel {
@ExcelProperty(value = {"表头3","表头3","表头3"},index = 2)
private int p3;
@ExcelProperty(value = {"表头1","表头4","表头4"},index = 3)
private long p4;
@ExcelProperty(value = {"表头5","表头51","表头52"},index = 4)
private String p5;
@ExcelProperty(value = {"表头6","表头61","表头611"},index = 5)
private float p6;
@ExcelProperty(value = {"表头6","表头61","表头612"},index = 6)
private BigDecimal p7;
@ExcelProperty(value = {"表头6","表头62","表头621"},index = 7, format = "yyyy-MM-dd")
private Date p8;
@ExcelProperty(value = {"表头6","表头62","表头622"},index = 8)
private String p9;
@ExcelProperty(value = {"表头6","表头62","表头622"},index = 9)
private double p10;
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 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 float getP6() {
return p6;
}
public void setP6(float p6) {
this.p6 = p6;
}
public BigDecimal getP7() {
return p7;
}
public void setP7(BigDecimal p7) {
this.p7 = p7;
}
public Date getP8() {
return p8;
}
public void setP8(Date p8) {
this.p8 = p8;
}
public String getP9() {
return p9;
}
public void setP9(String p9) {
this.p9 = p9;
}
public double getP10() {
return p10;
}
public void setP10(double p10) {
this.p10 = p10;
}
@Override
public String toString() {
return "JavaModel1{" +
"p1='" + p1 + '\'' +
", p2='" + p2 + '\'' +
", p3=" + p3 +
", p4=" + p4 +
", p5='" + p5 + '\'' +
", p6=" + p6 +
", p7=" + p7 +
", p8=" + p8 +
", p9='" + p9 + '\'' +
", p10=" + p10 +
'}';
}
}

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

@ -1,93 +0,0 @@
package com.alibaba.easyexcel.test.util;
import com.alibaba.easyexcel.test.model.WriteModel;
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<WriteModel> createTestListJavaMode(){
List<WriteModel> model1s = new ArrayList<WriteModel>();
for (int i = 0; i <10000 ; i++) {
WriteModel model1 = new WriteModel();
model1.setP1("第一列,第行");
model1.setP2("121212jjj");
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;
}
}

BIN
src/test/resources/2003.xls

Binary file not shown.

BIN
src/test/resources/2007.xlsx

Binary file not shown.

BIN
src/test/resources/temp.xlsx

Binary file not shown.
Loading…
Cancel
Save