diff --git a/src/main/java/com/alibaba/excel/EasyExcelFactory.java b/src/main/java/com/alibaba/excel/EasyExcelFactory.java index 4d73219..3fb8135 100644 --- a/src/main/java/com/alibaba/excel/EasyExcelFactory.java +++ b/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 listRow = new ArrayList(); - for (Object obj : rows) { - Map oneRow = (Map)obj; - listRow.add(new ArrayList(new TreeMap(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' * diff --git a/src/main/java/com/alibaba/excel/ExcelReader.java b/src/main/java/com/alibaba/excel/ExcelReader.java index d512683..07378d2 100644 --- a/src/main/java/com/alibaba/excel/ExcelReader.java +++ b/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 diff --git a/src/main/java/com/alibaba/excel/ExcelWriter.java b/src/main/java/com/alibaba/excel/ExcelWriter.java index 54fd2a3..c99787d 100644 --- a/src/main/java/com/alibaba/excel/ExcelWriter.java +++ b/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()); } diff --git a/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java b/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java index 31362d3..b24a182 100644 --- a/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java +++ b/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); } diff --git a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java index bfed46e..d7aaea9 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java +++ b/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 { diff --git a/src/main/java/com/alibaba/excel/analysis/v07/handlers/DefaultCellHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/handlers/DefaultCellHandler.java index 3f376b4..ba890bd 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/handlers/DefaultCellHandler.java +++ b/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"); diff --git a/src/main/java/com/alibaba/excel/cache/Ehcache.java b/src/main/java/com/alibaba/excel/cache/Ehcache.java index cd844eb..eae731a 100644 --- a/src/main/java/com/alibaba/excel/cache/Ehcache.java +++ b/src/main/java/com/alibaba/excel/cache/Ehcache.java @@ -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 countList = new LinkedList(); diff --git a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java b/src/main/java/com/alibaba/excel/context/WriteContextImpl.java index 5ab62ad..3564cda 100644 --- a/src/main/java/com/alibaba/excel/context/WriteContextImpl.java +++ b/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(); diff --git a/src/main/java/com/alibaba/excel/exception/ExcelAnalysisStopException.java b/src/main/java/com/alibaba/excel/exception/ExcelAnalysisStopException.java new file mode 100644 index 0000000..fdc0dfd --- /dev/null +++ b/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); + } +} diff --git a/src/main/java/com/alibaba/excel/metadata/BaseRowModel.java b/src/main/java/com/alibaba/excel/metadata/BaseRowModel.java index 35f3b27..7df131e 100644 --- a/src/main/java/com/alibaba/excel/metadata/BaseRowModel.java +++ b/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 cellStyleMap = new HashMap(); public void addStyle(Integer row, CellStyle cellStyle) { diff --git a/src/main/java/com/alibaba/excel/parameter/ExcelWriteParam.java b/src/main/java/com/alibaba/excel/parameter/ExcelWriteParam.java deleted file mode 100644 index 9104e83..0000000 --- a/src/main/java/com/alibaba/excel/parameter/ExcelWriteParam.java +++ /dev/null @@ -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; - } -} diff --git a/src/main/java/com/alibaba/excel/read/builder/ExcelReaderBuilder.java b/src/main/java/com/alibaba/excel/read/builder/ExcelReaderBuilder.java index 1000fd0..1219433 100644 --- a/src/main/java/com/alibaba/excel/read/builder/ExcelReaderBuilder.java +++ b/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 - *

- * 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. - *

- * 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. * *

  • 0 - This Sheet has no head ,since the first row are the data *
  • 1 - This Sheet has one row head , this is the default *
  • 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 */ diff --git a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java b/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java index 4ff1c69..bf4a8cf 100644 --- a/src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java +++ b/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 cellDataMap, ReadHolder currentReadHolder) { - Map map = new HashMap(cellDataMap.size() * 4 / 3 + 1); - for (Map.Entry entry : cellDataMap.entrySet()) { - CellData cellData = entry.getValue(); - if (cellData.getType() == CellDataTypeEnum.EMPTY) { - map.put(entry.getKey(), null); - continue; + private Object buildStringList(Map cellDataMap, ReadHolder currentReadHolder, + AnalysisContext context) { + if (context.readWorkbookHolder().getDefaultReturnMap()) { + Map map = new HashMap(cellDataMap.size() * 4 / 3 + 1); + for (Map.Entry 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 list = new ArrayList(); + for (Map.Entry 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 cellDataMap, ReadHolder currentReadHolder) { diff --git a/src/main/java/com/alibaba/excel/read/listener/ReadListener.java b/src/main/java/com/alibaba/excel/read/listener/ReadListener.java index 90b6f39..7335da5 100644 --- a/src/main/java/com/alibaba/excel/read/listener/ReadListener.java +++ b/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 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 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 */ diff --git a/src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java b/src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java index 1ceba75..e465375 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/ReadWorkbook.java +++ b/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. *
  • 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. - * + * * @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; + } } diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java index 9769b39..fcb9cd7 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java +++ b/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; } diff --git a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java b/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java index 18c4d12..385e782 100644 --- a/src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java +++ b/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(); } @@ -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; diff --git a/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java b/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java index 5cd3a93..a267e1d 100644 --- a/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java +++ b/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 { diff --git a/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java b/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java index 566ca84..6f06e11 100644 --- a/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java +++ b/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 fieldList = new ArrayList(); 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 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 fieldList) { WriteHolder currentWriteHolder = context.currentWriteHolder(); BeanMap beanMap = BeanMap.create(oneRowData); Set beanMapHandledSet = new HashSet(); @@ -220,19 +225,38 @@ public class ExcelBuilderImpl implements ExcelBuilder { cellIndex++; } Map ignoreMap = context.currentWriteHolder().excelWriteHeadProperty().getIgnoreMap(); - Set> entrySet = beanMap.entrySet(); - for (Map.Entry 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 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 handlerList = context.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class); if (handlerList == null || handlerList.isEmpty()) { diff --git a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java index 673e81c..bb1c4dd 100644 --- a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java +++ b/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 * diff --git a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java b/src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java index 0f97f03..3b36419 100644 --- a/src/main/java/com/alibaba/excel/write/builder/ExcelWriterTableBuilder.java +++ b/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(); + } + } diff --git a/src/main/java/com/alibaba/excel/write/merge/LoopMergeStrategy.java b/src/main/java/com/alibaba/excel/write/merge/LoopMergeStrategy.java index ad4843f..c2a1577 100644 --- a/src/main/java/com/alibaba/excel/write/merge/LoopMergeStrategy.java +++ b/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); } } diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java index bb6f2be..0c4d240 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java +++ b/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, List> sortAndClearUpHandler( List handlerList, Map, List> parentHandlerMap) { + // add + Set noRepeatSet = new HashSet(); if (parentHandlerMap != null) { for (List parentHandlerList : parentHandlerMap.values()) { - handlerList.addAll(parentHandlerList); + noRepeatSet.addAll(parentHandlerList); } } + handlerList.addAll(noRepeatSet); + // sort Map> orderExcelWriteHandlerMap = new TreeMap>(); for (WriteHandler handler : handlerList) { diff --git a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java b/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java index 76855ae..02ce196 100644 --- a/src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java +++ b/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; diff --git a/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java index 94c4a77..41cabac 100644 --- a/src/main/java/com/alibaba/excel/write/style/AbstractCellStyleStrategy.java +++ b/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 diff --git a/src/test/java/com/alibaba/easyexcel/test/ReadTest.java b/src/test/java/com/alibaba/easyexcel/test/ReadTest.java deleted file mode 100644 index 0e46892..0000000 --- a/src/test/java/com/alibaba/easyexcel/test/ReadTest.java +++ /dev/null @@ -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 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 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 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 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 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 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 datas){ - int i=0; - for (Object ob:datas) { - System.out.println(i++); - System.out.println(ob); - } - } - -} diff --git a/src/test/java/com/alibaba/easyexcel/test/WriteTest.java b/src/test/java/com/alibaba/easyexcel/test/WriteTest.java deleted file mode 100644 index 902e956..0000000 --- a/src/test/java/com/alibaba/easyexcel/test/WriteTest.java +++ /dev/null @@ -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 无模型映射关系 - 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 无模型映射关系 - 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 无模型映射关系 - 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 无模型映射关系 - 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(); - } -} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java index a01693d..2adb905 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java +++ b/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 data() throws Exception { diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/AnnotationDataListener.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataListener.java similarity index 50% rename from src/test/java/com/alibaba/easyexcel/test/core/compatibility/AnnotationDataListener.java rename to src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataListener.java index 35acfa7..c63426f 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/AnnotationDataListener.java +++ b/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 { +public class CompatibilityDataListener extends AnalysisEventListener> { private static final Logger LOGGER = LoggerFactory.getLogger(AnnotationDataListener.class); - List list = new ArrayList(); + List> list = new ArrayList>(); @Override - public void invoke(AnnotationData data, AnalysisContext context) { + public void invoke(List 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 data = list.get(0); + Assert.assertEquals(data.get(0), "字符串00"); LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0))); } } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java index 9122822..aaab178 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java +++ b/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 data = EasyExcelFactory.read(inputStream, new Sheet(1, 1)); + Assert.assertEquals(data.size(), 1); + List dataList = (List)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> head() { @@ -96,8 +123,8 @@ public class CompatibilityDataTest { private List> listData() { List> list = new ArrayList>(); List data0 = new ArrayList(); - data0.add("字符串0"); - data0.add(1); + data0.add("字符串00"); + data0.add(11); list.add(data0); return list; } diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityParameterDataTest.java new file mode 100644 index 0000000..8d3b50b --- /dev/null +++ b/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 data() { + List list = new ArrayList(); + for (int i = 0; i < 10; i++) { + CompatibilityData data = new CompatibilityData(); + data.setString0("字符串0" + i); + data.setString1("字符串1" + i); + list.add(data); + } + return list; + } + +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java b/src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityReadData.java new file mode 100644 index 0000000..931cb00 --- /dev/null +++ b/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; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/exception/ExceptionData.java b/src/test/java/com/alibaba/easyexcel/test/core/exception/ExceptionData.java new file mode 100644 index 0000000..9f2667d --- /dev/null +++ b/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; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/exception/ExceptionDataListener.java b/src/test/java/com/alibaba/easyexcel/test/core/exception/ExceptionDataListener.java new file mode 100644 index 0000000..87a519f --- /dev/null +++ b/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 { + private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionData.class); + List list = new ArrayList(); + + @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))); + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/exception/ExceptionDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/exception/ExceptionDataTest.java new file mode 100644 index 0000000..880e9ab --- /dev/null +++ b/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 data() { + List list = new ArrayList(); + for (int i = 0; i < 10; i++) { + ExceptionData simpleData = new ExceptionData(); + simpleData.setName("姓名" + i); + list.add(simpleData); + } + return list; + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterData.java b/src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterData.java new file mode 100644 index 0000000..e596670 --- /dev/null +++ b/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; +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterDataListener.java b/src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterDataListener.java new file mode 100644 index 0000000..5258727 --- /dev/null +++ b/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 { + private static final Logger LOGGER = LoggerFactory.getLogger(ParameterDataListener.class); + List list = new ArrayList(); + + @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))); + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/parameter/ParameterDataTest.java new file mode 100644 index 0000000..34d0fad --- /dev/null +++ b/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 data() { + List list = new ArrayList(); + for (int i = 0; i < 10; i++) { + ParameterData simpleData = new ParameterData(); + simpleData.setName("姓名" + i); + list.add(simpleData); + } + return list; + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataTest.java index 446d68c..a424730 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataTest.java +++ b/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(); diff --git a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java b/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java index 37e6659..823dff6 100644 --- a/src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java +++ b/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 data10() { + List list = new ArrayList(); + for (int i = 0; i < 10; i++) { + StyleData data = new StyleData(); + data.setString("字符串0"); + data.setString1("字符串01"); + list.add(data); + } + return list; + } } diff --git a/src/test/java/com/alibaba/easyexcel/test/listen/AfterExcelWriteHandlerImpl.java b/src/test/java/com/alibaba/easyexcel/test/listen/AfterExcelWriteHandlerImpl.java deleted file mode 100644 index a83c282..0000000 --- a/src/test/java/com/alibaba/easyexcel/test/listen/AfterExcelWriteHandlerImpl.java +++ /dev/null @@ -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); - } - } -} diff --git a/src/test/java/com/alibaba/easyexcel/test/listen/ExcelListener.java b/src/test/java/com/alibaba/easyexcel/test/listen/ExcelListener.java deleted file mode 100644 index 0f17a39..0000000 --- a/src/test/java/com/alibaba/easyexcel/test/listen/ExcelListener.java +++ /dev/null @@ -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 data = new ArrayList(); - - @Override - public void invoke(Object object, AnalysisContext context) { - System.out.println(context.getCurrentSheet()); - data.add(object); - if(data.size()>=100){ - doSomething(); - data = new ArrayList(); - } - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - doSomething(); - } - public void doSomething(){ - for (Object o:data) { - System.out.println(o); - } - } -} diff --git a/src/test/java/com/alibaba/easyexcel/test/model/BaseReadModel.java b/src/test/java/com/alibaba/easyexcel/test/model/BaseReadModel.java deleted file mode 100644 index be65aa7..0000000 --- a/src/test/java/com/alibaba/easyexcel/test/model/BaseReadModel.java +++ /dev/null @@ -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; - } -} diff --git a/src/test/java/com/alibaba/easyexcel/test/model/BaseWriteModel.java b/src/test/java/com/alibaba/easyexcel/test/model/BaseWriteModel.java deleted file mode 100644 index 8688216..0000000 --- a/src/test/java/com/alibaba/easyexcel/test/model/BaseWriteModel.java +++ /dev/null @@ -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; - } -} diff --git a/src/test/java/com/alibaba/easyexcel/test/model/ReadModel.java b/src/test/java/com/alibaba/easyexcel/test/model/ReadModel.java deleted file mode 100644 index fe90171..0000000 --- a/src/test/java/com/alibaba/easyexcel/test/model/ReadModel.java +++ /dev/null @@ -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 + '\'' + - '}'; - } -} diff --git a/src/test/java/com/alibaba/easyexcel/test/model/ReadModel2.java b/src/test/java/com/alibaba/easyexcel/test/model/ReadModel2.java deleted file mode 100644 index a64f701..0000000 --- a/src/test/java/com/alibaba/easyexcel/test/model/ReadModel2.java +++ /dev/null @@ -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 + '\'' + - '}'; - } -} diff --git a/src/test/java/com/alibaba/easyexcel/test/model/WriteModel.java b/src/test/java/com/alibaba/easyexcel/test/model/WriteModel.java deleted file mode 100644 index c3e306b..0000000 --- a/src/test/java/com/alibaba/easyexcel/test/model/WriteModel.java +++ /dev/null @@ -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 + - '}'; - } -} diff --git a/src/test/java/com/alibaba/easyexcel/test/util/DataUtil.java b/src/test/java/com/alibaba/easyexcel/test/util/DataUtil.java deleted file mode 100644 index 505dab5..0000000 --- a/src/test/java/com/alibaba/easyexcel/test/util/DataUtil.java +++ /dev/null @@ -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> createTestListObject() { - List> object = new ArrayList>(); - for (int i = 0; i < 1000; i++) { - List da = new ArrayList(); - 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> createTestListStringHead(){ - //写sheet3 模型上没有注解,表头数据动态传入 - List> head = new ArrayList>(); - List headCoulumn1 = new ArrayList(); - List headCoulumn2 = new ArrayList(); - List headCoulumn3 = new ArrayList(); - List headCoulumn4 = new ArrayList(); - List headCoulumn5 = new ArrayList(); - - 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 createTestListJavaMode(){ - List model1s = new ArrayList(); - 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; - } -} diff --git a/src/test/resources/2003.xls b/src/test/resources/2003.xls deleted file mode 100644 index 3c2fa34..0000000 Binary files a/src/test/resources/2003.xls and /dev/null differ diff --git a/src/test/resources/2007.xlsx b/src/test/resources/2007.xlsx deleted file mode 100644 index 1c17101..0000000 Binary files a/src/test/resources/2007.xlsx and /dev/null differ diff --git a/src/test/resources/temp.xlsx b/src/test/resources/temp.xlsx deleted file mode 100644 index 2149a23..0000000 Binary files a/src/test/resources/temp.xlsx and /dev/null differ