Browse Source

优化读写逻辑

developing
zhuangjiaju 5 years ago
parent
commit
1026a18bdc
  1. 10
      src/main/java/com/alibaba/excel/EasyExcelFactory.java
  2. 46
      src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java
  3. 2
      src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java
  4. 5
      src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java
  5. 6
      src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java
  6. 6
      src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java
  7. 6
      src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java
  8. 6
      src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java
  9. 6
      src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java
  10. 6
      src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java
  11. 36
      src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java
  12. 17
      src/main/java/com/alibaba/excel/read/listener/ModelBuildEventListener.java
  13. 5
      src/main/java/com/alibaba/excel/read/metadata/ReadSheet.java
  14. 31
      src/main/java/com/alibaba/excel/read/metadata/holder/AbstractReadHolder.java
  15. 1
      src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java
  16. 122
      src/main/java/com/alibaba/excel/util/NumberUtils.java
  17. 7
      src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java
  18. 5
      src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java
  19. 4
      src/main/java/com/alibaba/excel/write/style/row/SimpleRowHeightStyleStrategy.java
  20. 18
      src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationData.java
  21. 41
      src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataListener.java
  22. 64
      src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataTest.java
  23. 20
      src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameData.java
  24. 36
      src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataListener.java
  25. 55
      src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataTest.java
  26. 16
      src/test/java/com/alibaba/easyexcel/test/core/head/NoHeadData07Test.java
  27. 29
      src/test/java/com/alibaba/easyexcel/test/core/order/OrderData.java
  28. 34
      src/test/java/com/alibaba/easyexcel/test/core/order/OrderData07Test.java
  29. 14
      src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataSheetNameListener.java
  30. 6
      src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java
  31. BIN
      src/test/resources/simple/simple07.xlsx

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

@ -6,6 +6,8 @@ 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;
@ -62,8 +64,16 @@ public class EasyExcelFactory {
@Override
public void doAfterAllAnalysed(AnalysisContext context) {}
}, false).read(sheet);
if (rows.size() == 0 || !(rows.get(0) instanceof Map)) {
return rows;
}
List<Object> listRow = new ArrayList<Object>();
for (Object obj : rows) {
Map<Integer, String> oneRow = (Map<Integer, String>)obj;
listRow.add(new ArrayList<String>(new TreeMap<Integer, String>(oneRow).values()));
}
return listRow;
}
/**
* Parsing large file

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

@ -54,27 +54,11 @@ public class XlsxSaxAnalyser implements ExcelExecutor {
ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder();
OPCPackage pkg = readOpcPackage(readWorkbookHolder);
PackagePart sharedStringsTablePackagePart =
pkg.getPartsByContentType(XSSFRelation.SHARED_STRINGS.getContentType()).get(0);
if (readWorkbookHolder.getReadCache() == null) {
long size = sharedStringsTablePackagePart.getSize();
if (size < 0) {
size = sharedStringsTablePackagePart.getInputStream().available();
}
if (size < USE_MAP_CACHE_SIZE) {
if (LOGGER.isDebugEnabled()) {
LOGGER.info("Use map cache.size:{}", size);
}
readWorkbookHolder.setReadCache(new MapCache());
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.info("Use ehcache.size:{}", size);
}
readWorkbookHolder.setReadCache(new Ehcache());
}
}
readWorkbookHolder.getReadCache().init(analysisContext);
// Specify default cache
defaultReadCache(readWorkbookHolder, sharedStringsTablePackagePart);
// Analysis sharedStringsTable.xml
analysisSharedStringsTable(sharedStringsTablePackagePart.getInputStream(), readWorkbookHolder);
@ -98,6 +82,30 @@ public class XlsxSaxAnalyser implements ExcelExecutor {
}
}
private void defaultReadCache(ReadWorkbookHolder readWorkbookHolder, PackagePart sharedStringsTablePackagePart)
throws IOException {
if (readWorkbookHolder.getReadCache() != null) {
readWorkbookHolder.getReadCache().init(analysisContext);
return;
}
long size = sharedStringsTablePackagePart.getSize();
if (size < 0) {
size = sharedStringsTablePackagePart.getInputStream().available();
}
if (size < USE_MAP_CACHE_SIZE) {
if (LOGGER.isDebugEnabled()) {
LOGGER.info("Use map cache.size:{}", size);
}
readWorkbookHolder.setReadCache(new MapCache());
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.info("Use ehcache.size:{}", size);
}
readWorkbookHolder.setReadCache(new Ehcache());
}
readWorkbookHolder.getReadCache().init(analysisContext);
}
private void analysisUse1904WindowDate(XSSFReader xssfReader, ReadWorkbookHolder readWorkbookHolder)
throws Exception {
if (readWorkbookHolder.globalConfiguration().getUse1904windowing() != null) {

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

@ -103,7 +103,7 @@ public class AnalysisContextImpl implements AnalysisContext {
sheetName = sheetName.trim();
}
if (sheetName.equals(readSheetHolder.getSheetName())) {
readSheetHolder.setSheetNo(readSheetHolder.getSheetNo());
readSheetHolder.setSheetNo(readSheetExcel.getSheetNo());
return;
}
}

5
src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java

@ -1,6 +1,7 @@
package com.alibaba.excel.converters.bigdecimal;
import java.math.BigDecimal;
import java.text.ParseException;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
@ -28,8 +29,8 @@ public class BigDecimalStringConverter implements Converter<BigDecimal> {
@Override
public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return new BigDecimal(cellData.getStringValue());
GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseBigDecimal(cellData.getStringValue(), contentProperty);
}
@Override

6
src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java

@ -1,5 +1,7 @@
package com.alibaba.excel.converters.byteconverter;
import java.text.ParseException;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
@ -26,8 +28,8 @@ public class ByteStringConverter implements Converter<Byte> {
@Override
public Byte convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return Byte.valueOf(cellData.getStringValue());
GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseByte(cellData.getStringValue(), contentProperty);
}
@Override

6
src/main/java/com/alibaba/excel/converters/doubleconverter/DoubleStringConverter.java

@ -1,5 +1,7 @@
package com.alibaba.excel.converters.doubleconverter;
import java.text.ParseException;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
@ -26,8 +28,8 @@ public class DoubleStringConverter implements Converter<Double> {
@Override
public Double convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return Double.valueOf(cellData.getStringValue());
GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseDouble(cellData.getStringValue(), contentProperty);
}
@Override

6
src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java

@ -1,5 +1,7 @@
package com.alibaba.excel.converters.floatconverter;
import java.text.ParseException;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
@ -26,8 +28,8 @@ public class FloatStringConverter implements Converter<Float> {
@Override
public Float convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return Float.valueOf(cellData.getStringValue());
GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseFloat(cellData.getStringValue(), contentProperty);
}
@Override

6
src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java

@ -1,5 +1,7 @@
package com.alibaba.excel.converters.integer;
import java.text.ParseException;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
@ -26,8 +28,8 @@ public class IntegerStringConverter implements Converter<Integer> {
@Override
public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return Integer.valueOf(cellData.getStringValue());
GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseInteger(cellData.getStringValue(), contentProperty);
}
@Override

6
src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java

@ -1,5 +1,7 @@
package com.alibaba.excel.converters.longconverter;
import java.text.ParseException;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
@ -26,8 +28,8 @@ public class LongStringConverter implements Converter<Long> {
@Override
public Long convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return Long.valueOf(cellData.getStringValue());
GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseLong(cellData.getStringValue(), contentProperty);
}
@Override

6
src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java

@ -1,5 +1,7 @@
package com.alibaba.excel.converters.shortconverter;
import java.text.ParseException;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
@ -26,8 +28,8 @@ public class ShortStringConverter implements Converter<Short> {
@Override
public Short convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return Short.valueOf(cellData.getStringValue());
GlobalConfiguration globalConfiguration) throws ParseException {
return NumberUtils.parseShort(cellData.getStringValue(), contentProperty);
}
@Override

36
src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java

@ -3,6 +3,7 @@ package com.alibaba.excel.metadata.property;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@ -51,11 +52,16 @@ public class ExcelHeadProperty {
* Configuration column information
*/
private Map<Integer, ExcelContentProperty> contentPropertyMap;
/**
* Fields ignored
*/
private Map<String, Field> ignoreMap;
public ExcelHeadProperty(Class headClazz, List<List<String>> head, Boolean convertAllFiled) {
this.headClazz = headClazz;
headMap = new TreeMap<Integer, Head>();
contentPropertyMap = new TreeMap<Integer, ExcelContentProperty>();
ignoreMap = new HashMap<String, Field>(16);
headKind = HeadKindEnum.NONE;
headRowNumber = 0;
if (head != null && !head.isEmpty()) {
@ -118,10 +124,12 @@ public class ExcelHeadProperty {
for (Field field : fieldList) {
ExcelIgnore excelIgnore = field.getAnnotation(ExcelIgnore.class);
if (excelIgnore != null) {
ignoreMap.put(field.getName(), field);
continue;
}
ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
if (excelProperty == null && convertAllFiled != null && !convertAllFiled) {
ignoreMap.put(field.getName(), field);
continue;
}
if (excelProperty == null || excelProperty.index() < 0) {
@ -146,8 +154,7 @@ public class ExcelHeadProperty {
index++;
}
for (Map.Entry<Integer, Field> entry : customFiledMap.entrySet()) {
initOneColumnProperty(index, entry.getValue(), Boolean.FALSE);
index++;
initOneColumnProperty(entry.getKey(), entry.getValue(), Boolean.TRUE);
}
headKind = HeadKindEnum.CLASS;
}
@ -155,20 +162,16 @@ public class ExcelHeadProperty {
private void initOneColumnProperty(int index, Field field, Boolean forceIndex) {
ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
List<String> tmpHeadList = new ArrayList<String>();
Boolean forceName = Boolean.TRUE;
if (excelProperty != null) {
tmpHeadList = Arrays.asList(excelProperty.value());
} else {
forceName = Boolean.FALSE;
tmpHeadList.add(field.getName());
}
if (tmpHeadList.isEmpty() || StringUtils.isEmpty(tmpHeadList.get(0))) {
forceName = Boolean.FALSE;
boolean notForceName = excelProperty == null || excelProperty.value().length <= 0
|| (excelProperty.value().length == 1 && StringUtils.isEmpty((excelProperty.value())[0]));
if (notForceName) {
tmpHeadList.add(field.getName());
} else {
tmpHeadList = Arrays.asList(excelProperty.value());
}
Head head = new Head(index, field.getName(), tmpHeadList, forceIndex, forceName);
Head head = new Head(index, field.getName(), tmpHeadList, forceIndex, !notForceName);
ExcelContentProperty excelContentProperty = new ExcelContentProperty();
if (excelProperty != null && excelProperty.converter() != null) {
if (excelProperty != null) {
Class<? extends Converter> convertClazz = excelProperty.converter();
if (convertClazz != AutoConverter.class) {
try {
@ -233,4 +236,11 @@ public class ExcelHeadProperty {
this.contentPropertyMap = contentPropertyMap;
}
public Map<String, Field> getIgnoreMap() {
return ignoreMap;
}
public void setIgnoreMap(Map<String, Field> ignoreMap) {
this.ignoreMap = ignoreMap;
}
}

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

@ -1,8 +1,6 @@
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;
@ -39,12 +37,17 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener
}
private Object buildStringList(Map<Integer, CellData> cellDataMap, ReadHolder currentReadHolder) {
List<String> list = new ArrayList<String>();
for (CellData cellData : cellDataMap.values()) {
list.add((String)convertValue(cellData, String.class, null, currentReadHolder.converterMap(),
Map<Integer, String> map = new HashMap<Integer, String>(cellDataMap.size() * 4 / 3 + 1);
for (Map.Entry<Integer, CellData> entry : cellDataMap.entrySet()) {
CellData cellData = entry.getValue();
if (cellData.getType() == CellDataTypeEnum.EMPTY) {
map.put(entry.getKey(), null);
continue;
}
map.put(entry.getKey(), (String)convertValue(cellData, String.class, null, currentReadHolder.converterMap(),
currentReadHolder.globalConfiguration()));
}
return list;
return map;
}
private Object buildUserModel(Map<Integer, CellData> cellDataMap, ReadHolder currentReadHolder) {
@ -61,7 +64,7 @@ public class ModelBuildEventListener extends AbstractIgnoreExceptionReadListener
Map<Integer, ExcelContentProperty> contentPropertyMap = excelReadHeadProperty.getContentPropertyMap();
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
Integer index = entry.getKey();
if (index >= cellDataMap.size()) {
if (!cellDataMap.containsKey(index)) {
continue;
}
CellData cellData = cellDataMap.get(index);

5
src/main/java/com/alibaba/excel/read/metadata/ReadSheet.java

@ -41,4 +41,9 @@ public class ReadSheet extends ReadBasicParameter {
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
@Override
public String toString() {
return "ReadSheet{" + "sheetNo=" + sheetNo + ", sheetName='" + sheetName + '\'' + "} " + super.toString();
}
}

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

@ -9,6 +9,7 @@ import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ConverterKeyBuild;
import com.alibaba.excel.converters.DefaultConverterLoader;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.enums.HeadKindEnum;
import com.alibaba.excel.enums.HolderEnum;
import com.alibaba.excel.event.AnalysisEventListener;
@ -144,7 +145,7 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
if (!HeadKindEnum.CLASS.equals(analysisContext.currentReadHolder().excelReadHeadProperty().getHeadKind())) {
return;
}
List<String> dataList = (List<String>)buildStringList(cellDataMap, analysisContext.currentReadHolder());
Map<Integer, String> dataMap = buildStringMap(cellDataMap, analysisContext.currentReadHolder());
ExcelReadHeadProperty excelHeadPropertyData = analysisContext.readSheetHolder().excelReadHeadProperty();
Map<Integer, Head> headMapData = excelHeadPropertyData.getHeadMap();
Map<Integer, ExcelContentProperty> contentPropertyMapData = excelHeadPropertyData.getContentPropertyMap();
@ -159,8 +160,10 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
continue;
}
String headName = headData.getHeadNameList().get(0);
for (int i = 0; i < dataList.size(); i++) {
String headString = dataList.get(i);
for (Map.Entry<Integer, String> stringEntry : dataMap.entrySet()) {
String headString = stringEntry.getValue();
Integer stringKey = stringEntry.getKey();
if (StringUtils.isEmpty(headString)) {
continue;
}
@ -168,9 +171,9 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
headString = headString.trim();
}
if (headName.equals(headString)) {
headData.setColumnIndex(i);
tmpHeadMap.put(i, headData);
tmpContentPropertyMap.put(i, contentPropertyMapData.get(entry.getKey()));
headData.setColumnIndex(stringKey);
tmpHeadMap.put(stringKey, headData);
tmpContentPropertyMap.put(stringKey, contentPropertyMapData.get(entry.getKey()));
break;
}
}
@ -179,9 +182,14 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
excelHeadPropertyData.setContentPropertyMap(tmpContentPropertyMap);
}
private Object buildStringList(Map<Integer, CellData> cellDataMa, ReadHolder readHolder) {
List<String> list = new ArrayList<String>();
for (CellData cellData : cellDataMa.values()) {
private Map<Integer, String> buildStringMap(Map<Integer, CellData> cellDataMap, ReadHolder readHolder) {
Map<Integer, String> stringMap = new HashMap<Integer, String>(cellDataMap.size() * 4 / 3 + 1);
for (Map.Entry<Integer, CellData> entry : cellDataMap.entrySet()) {
CellData cellData = entry.getValue();
if (cellData.getType() == CellDataTypeEnum.EMPTY) {
stringMap.put(entry.getKey(), null);
continue;
}
Converter converter =
readHolder.converterMap().get(ConverterKeyBuild.buildKey(String.class, cellData.getType()));
if (converter == null) {
@ -189,12 +197,13 @@ public abstract class AbstractReadHolder extends AbstractHolder implements ReadH
"Converter not found, convert " + cellData.getType() + " to String");
}
try {
list.add((String)(converter.convertToJavaData(cellData, null, readHolder.globalConfiguration())));
stringMap.put(entry.getKey(),
(String)(converter.convertToJavaData(cellData, null, readHolder.globalConfiguration())));
} catch (Exception e) {
throw new ExcelDataConvertException("Convert data " + cellData + " to String error ", e);
}
}
return list;
return stringMap;
}
public List<ReadListener> getReadListenerList() {

1
src/main/java/com/alibaba/excel/read/metadata/holder/ReadSheetHolder.java

@ -36,6 +36,7 @@ public class ReadSheetHolder extends AbstractReadHolder {
this.readSheet = readSheet;
this.parentReadWorkbookHolder = readWorkbookHolder;
this.sheetNo = readSheet.getSheetNo();
this.sheetName=readSheet.getSheetName();
}
public ReadSheet getReadSheet() {

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

@ -1,7 +1,9 @@
package com.alibaba.excel.util;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
@ -43,4 +45,124 @@ public class NumberUtils {
public static CellData formatToCellData(Number num, ExcelContentProperty contentProperty) {
return new CellData(format(num, contentProperty));
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static Short parseShort(String string, ExcelContentProperty contentProperty) throws ParseException {
if (!hasFormat(contentProperty)) {
return Short.valueOf(string);
}
return parse(string, contentProperty).shortValue();
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static Long parseLong(String string, ExcelContentProperty contentProperty) throws ParseException {
if (!hasFormat(contentProperty)) {
return Long.valueOf(string);
}
return parse(string, contentProperty).longValue();
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static Integer parseInteger(String string, ExcelContentProperty contentProperty) throws ParseException {
if (!hasFormat(contentProperty)) {
return Integer.valueOf(string);
}
return parse(string, contentProperty).intValue();
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static Float parseFloat(String string, ExcelContentProperty contentProperty) throws ParseException {
if (!hasFormat(contentProperty)) {
return Float.valueOf(string);
}
return parse(string, contentProperty).floatValue();
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static BigDecimal parseBigDecimal(String string, ExcelContentProperty contentProperty)
throws ParseException {
if (!hasFormat(contentProperty)) {
return new BigDecimal(string);
}
return BigDecimal.valueOf(parse(string, contentProperty).doubleValue());
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static Byte parseByte(String string, ExcelContentProperty contentProperty) throws ParseException {
if (!hasFormat(contentProperty)) {
return Byte.valueOf(string);
}
return parse(string, contentProperty).byteValue();
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static Double parseDouble(String string, ExcelContentProperty contentProperty) throws ParseException {
if (!hasFormat(contentProperty)) {
return Double.valueOf(string);
}
return parse(string, contentProperty).doubleValue();
}
private static boolean hasFormat(ExcelContentProperty contentProperty) {
return contentProperty != null && contentProperty.getNumberFormatProperty() != null
&& !StringUtils.isEmpty(contentProperty.getNumberFormatProperty().getFormat());
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
* @throws ParseException
*/
private static Number parse(String string, ExcelContentProperty contentProperty) throws ParseException {
String format = contentProperty.getNumberFormatProperty().getFormat();
RoundingMode roundingMode = contentProperty.getNumberFormatProperty().getRoundingMode();
DecimalFormat decimalFormat = new DecimalFormat(format);
decimalFormat.setRoundingMode(roundingMode);
return decimalFormat.parse(string);
}
}

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

@ -1,5 +1,6 @@
package com.alibaba.excel.write;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@ -90,8 +91,10 @@ public class ExcelBuilderImpl implements ExcelBuilder {
@Override
public void finish() {
if (context != null) {
context.finish();
}
}
@Override
public void merge(int firstRow, int lastRow, int firstCol, int lastCol) {
@ -206,9 +209,11 @@ public class ExcelBuilderImpl implements ExcelBuilder {
if (cellIndex != 0) {
cellIndex++;
}
Map<String, Field> ignoreMap = context.currentWriteHolder().excelWriteHeadProperty().getIgnoreMap();
Set<Map.Entry<String, Object>> entrySet = beanMap.entrySet();
for (Map.Entry<String, Object> entry : entrySet) {
if (entry.getValue() == null || beanMapHandledSet.contains(entry.getKey())) {
if (entry.getValue() == null || beanMapHandledSet.contains(entry.getKey())
|| ignoreMap.containsKey(entry.getKey())) {
continue;
}
beforeCellCreate(row, null, relativeRowIndex);

5
src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java

@ -66,4 +66,9 @@ public class WriteSheet extends WriteBasicParameter {
public void setTableStyle(TableStyle tableStyle) {
this.tableStyle = tableStyle;
}
@Override
public String toString() {
return "WriteSheet{" + "sheetNo=" + sheetNo + ", sheetName='" + sheetName + '\'' + "} " + super.toString();
}
}

4
src/main/java/com/alibaba/excel/write/style/row/SimpleRowHeightStyleStrategy.java

@ -19,14 +19,14 @@ public class SimpleRowHeightStyleStrategy extends AbstractRowHeightStyleStrategy
@Override
protected void setHeadColumnHeight(Row row, int relativeRowIndex) {
if (headRowHeight != null) {
row.setHeight(headRowHeight);
row.setHeightInPoints(headRowHeight);
}
}
@Override
protected void setContentColumnHeight(Row row, int relativeRowIndex) {
if (contentRowHeight != null) {
row.setHeight(contentRowHeight);
row.setHeightInPoints(contentRowHeight);
}
}

18
src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationData.java

@ -2,7 +2,14 @@ package com.alibaba.easyexcel.test.core.annotation;
import java.util.Date;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.format.NumberFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import com.alibaba.excel.converters.doubleconverter.DoubleStringConverter;
import lombok.Data;
@ -10,7 +17,16 @@ import lombok.Data;
* @author zhuangjiaju
*/
@Data
@ColumnWidth(30 * 256)
@HeadRowHeight(15)
@ContentRowHeight(20)
public class AnnotationData {
@ExcelProperty("日期")
private Date name;
@DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")
private Date date;
@ExcelProperty(value = "数字", converter = DoubleStringConverter.class)
@NumberFormat("#.##%")
private Double number;
@ExcelIgnore
private String ignore;
}

41
src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationDataListener.java

@ -0,0 +1,41 @@
package com.alibaba.easyexcel.test.core.annotation;
import java.text.ParseException;
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.excel.exception.ExcelCommonException;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class AnnotationDataListener extends AnalysisEventListener<AnnotationData> {
private static final Logger LOGGER = LoggerFactory.getLogger(AnnotationDataListener.class);
List<AnnotationData> list = new ArrayList<AnnotationData>();
@Override
public void invoke(AnnotationData 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);
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

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

@ -4,13 +4,12 @@ import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.alibaba.easyexcel.test.core.simple.SimpleData;
import com.alibaba.easyexcel.test.core.simple.SimpleDataListener;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.util.DateUtils;
/**
* Annotation data test
@ -19,56 +18,37 @@ import com.alibaba.excel.EasyExcelFactory;
*/
public class AnnotationDataTest {
private File file07 = TestFileUtil.createNewFile("simple07.xlsx");
private File file03 = TestFileUtil.createNewFile("simple03.xls");
private static File file07;
private static File file03;
@Test
public void readAndWrite07() {
EasyExcelFactory.write(file07, com.alibaba.easyexcel.test.core.simple.SimpleData.class).sheet().doWrite(data())
.finish();
EasyExcelFactory.read(file07, com.alibaba.easyexcel.test.core.simple.SimpleData.class,
new com.alibaba.easyexcel.test.core.simple.SimpleDataListener()).sheet().doRead().finish();
@BeforeClass
public static void init() {
file07 = TestFileUtil.createNewFile("annotation07.xlsx");
file03 = TestFileUtil.createNewFile("annotation03.xls");
}
@Test
public void synchronousRead07() {
// Synchronous read file
List<Object> list = EasyExcelFactory.read(file07).head(com.alibaba.easyexcel.test.core.simple.SimpleData.class)
.sheet().doReadSync();
Assert.assertEquals(list.size(), 10);
Assert.assertTrue(list.get(0) instanceof com.alibaba.easyexcel.test.core.simple.SimpleData);
Assert.assertEquals(((com.alibaba.easyexcel.test.core.simple.SimpleData)list.get(0)).getName(), "姓名0");
public void T01ReadAndWrite07() throws Exception {
readAndWrite(file07);
}
@Test
public void readAndWrite03() {
EasyExcelFactory.write(file03, com.alibaba.easyexcel.test.core.simple.SimpleData.class).sheet().doWrite(data())
.finish();
EasyExcelFactory.read(file03, com.alibaba.easyexcel.test.core.simple.SimpleData.class, new SimpleDataListener())
.sheet().doRead().finish();
public void T02ReadAndWrite03() throws Exception {
readAndWrite(file03);
}
@Test
public void synchronousRead03() {
// Synchronous read file
List<Object> list = EasyExcelFactory.read(file03).head(com.alibaba.easyexcel.test.core.simple.SimpleData.class)
.sheet().doReadSync();
Assert.assertEquals(list.size(), 10);
Assert.assertTrue(list.get(0) instanceof com.alibaba.easyexcel.test.core.simple.SimpleData);
Assert.assertEquals(((com.alibaba.easyexcel.test.core.simple.SimpleData)list.get(0)).getName(), "姓名0");
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();
}
private List<com.alibaba.easyexcel.test.core.simple.SimpleData> data() {
List<com.alibaba.easyexcel.test.core.simple.SimpleData> list =
new ArrayList<com.alibaba.easyexcel.test.core.simple.SimpleData>();
for (int i = 0; i < 10; i++) {
com.alibaba.easyexcel.test.core.simple.SimpleData simpleData = new SimpleData();
simpleData.setName("姓名" + i);
list.add(simpleData);
}
private List<AnnotationData> data() throws Exception {
List<AnnotationData> list = new ArrayList<AnnotationData>();
AnnotationData data = new AnnotationData();
data.setDate(DateUtils.parseDate("2020-01-01 01:01:01"));
data.setNumber(99.99);
data.setIgnore("忽略");
list.add(data);
return list;
}
}

20
src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameData.java

@ -0,0 +1,20 @@
package com.alibaba.easyexcel.test.core.annotation;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class AnnotationIndexAndNameData {
@ExcelProperty(value = "第四个", index = 4)
private String index4;
@ExcelProperty(value = "第二个")
private String index2;
@ExcelProperty(index = 0)
private String index0;
@ExcelProperty(value = "第一个", index = 1)
private String index1;
}

36
src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataListener.java

@ -0,0 +1,36 @@
package com.alibaba.easyexcel.test.core.annotation;
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 AnnotationIndexAndNameDataListener extends AnalysisEventListener<AnnotationIndexAndNameData> {
private static final Logger LOGGER = LoggerFactory.getLogger(AnnotationIndexAndNameDataListener.class);
List<AnnotationIndexAndNameData> list = new ArrayList<AnnotationIndexAndNameData>();
@Override
public void invoke(AnnotationIndexAndNameData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 1);
AnnotationIndexAndNameData data = list.get(0);
Assert.assertEquals(data.getIndex0(), "第0个");
Assert.assertEquals(data.getIndex1(), "第1个");
Assert.assertEquals(data.getIndex2(), "第2个");
Assert.assertEquals(data.getIndex4(), "第4个");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

55
src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationIndexAndNameDataTest.java

@ -0,0 +1,55 @@
package com.alibaba.easyexcel.test.core.annotation;
import java.io.File;
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;
/**
* Annotation data test
*
* @author zhuangjiaju
*/
public class AnnotationIndexAndNameDataTest {
private static File file07;
private static File file03;
@BeforeClass
public static void init() {
file07 = TestFileUtil.createNewFile("annotationIndexAndName07.xlsx");
file03 = TestFileUtil.createNewFile("annotationIndexAndName03.xls");
}
@Test
public void T01ReadAndWrite07() {
readAndWrite(file07);
}
@Test
public void T02ReadAndWrite03() {
readAndWrite(file03);
}
private void readAndWrite(File file) {
EasyExcelFactory.write(file, AnnotationIndexAndNameData.class).sheet().doWrite(data()).finish();
EasyExcelFactory.read(file, AnnotationIndexAndNameData.class, new AnnotationIndexAndNameDataListener()).sheet()
.doRead().finish();
}
private List<AnnotationIndexAndNameData> data() {
List<AnnotationIndexAndNameData> list = new ArrayList<AnnotationIndexAndNameData>();
AnnotationIndexAndNameData data = new AnnotationIndexAndNameData();
data.setIndex0("第0个");
data.setIndex1("第1个");
data.setIndex2("第2个");
data.setIndex4("第4个");
list.add(data);
return list;
}
}

16
src/test/java/com/alibaba/easyexcel/test/core/head/NoHeadData07Test.java

@ -1,12 +1,7 @@
package com.alibaba.easyexcel.test.core.head;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.alibaba.easyexcel.test.core.order.OrderData;
/**
* Order data test
*
@ -22,15 +17,4 @@ public class NoHeadData07Test {
// writer.write(createData(10000 * 100), sheet);
// writer.finish();
}
private List<OrderData> createData(int count) {
List<OrderData> list = new ArrayList<OrderData>();
for (int i = 0; i < count; i++) {
OrderData orderData = new OrderData();
orderData.setIndex1("排序1:" + i);
orderData.setIndex10("排序10:" + i);
list.add(orderData);
}
return list;
}
}

29
src/test/java/com/alibaba/easyexcel/test/core/order/OrderData.java

@ -1,29 +0,0 @@
package com.alibaba.easyexcel.test.core.order;
import com.alibaba.excel.annotation.ExcelProperty;
/**
* @author zhuangjiaju
*/
public class OrderData {
@ExcelProperty(value = "第一个", index = 1)
private String index1;
@ExcelProperty(value = "第10个", index = 10)
private String index10;
public String getIndex1() {
return index1;
}
public void setIndex1(String index1) {
this.index1 = index1;
}
public String getIndex10() {
return index10;
}
public void setIndex10(String index10) {
this.index10 = index10;
}
}

34
src/test/java/com/alibaba/easyexcel/test/core/order/OrderData07Test.java

@ -1,34 +0,0 @@
package com.alibaba.easyexcel.test.core.order;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
/**
* Order data test
*
* @author zhuangjiaju
*/
public class OrderData07Test {
@Test
public void simple() {
// ExcelWriter writer = EasyExcelFactory.writerBuilder().outputFile(TestFileUtil.createNewWriteFile("order07.xlsx"))
// .head(OrderData.class).build();
// Sheet sheet = EasyExcelFactory.writerSheetBuilder().sheetNo(0).sheetName("order").build();
// writer.write(createData(10000 * 100), sheet);
// writer.finish();
}
private List<OrderData> createData(int count) {
List<OrderData> list = new ArrayList<OrderData>();
for (int i = 0; i < count; i++) {
OrderData orderData = new OrderData();
orderData.setIndex1("排序1:" + i);
orderData.setIndex10("排序10:" + i);
list.add(orderData);
}
return list;
}
}

14
src/test/java/com/alibaba/easyexcel/test/core/annotation/SimpleDataListener.java → src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataSheetNameListener.java

@ -1,4 +1,4 @@
package com.alibaba.easyexcel.test.core.annotation;
package com.alibaba.easyexcel.test.core.simple;
import java.util.ArrayList;
import java.util.List;
@ -7,7 +7,6 @@ import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.easyexcel.test.core.simple.SimpleData;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
@ -15,8 +14,8 @@ import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class SimpleDataListener extends AnalysisEventListener<SimpleData> {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleDataListener.class);
public class SimpleDataSheetNameListener extends AnalysisEventListener<SimpleData> {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleDataSheetNameListener.class);
List<SimpleData> list = new ArrayList<SimpleData>();
@Override
@ -26,11 +25,8 @@ public class SimpleDataListener extends AnalysisEventListener<SimpleData> {
@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), "姓名");
Assert.assertEquals(list.size(), 1);
Assert.assertEquals(list.get(0).getName(), "张三");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

6
src/test/java/com/alibaba/easyexcel/test/core/simple/SimpleDataTest.java

@ -55,6 +55,12 @@ public class SimpleDataTest {
synchronousRead(file03);
}
@Test
public void T05SheetNameRead07() {
EasyExcelFactory.read(TestFileUtil.readFile("simple" + File.separator + "simple07.xlsx"), SimpleData.class,
new SimpleDataSheetNameListener()).sheet("simple").doRead().finish();
}
private void synchronousRead(File file) {
// Synchronous read file
List<Object> list = EasyExcelFactory.read(file).head(SimpleData.class).sheet().doReadSync();

BIN
src/test/resources/simple/simple07.xlsx

Binary file not shown.
Loading…
Cancel
Save