Browse Source

优化读写逻辑

bugfix
zhuangjiaju 5 years ago
parent
commit
76fbb7828a
  1. 7
      src/main/java/com/alibaba/excel/ExcelWriter.java
  2. 6
      src/main/java/com/alibaba/excel/annotation/write/style/ColumnWidth.java
  3. 8
      src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java
  4. 4
      src/main/java/com/alibaba/excel/metadata/TableStyle.java
  5. 16
      src/main/java/com/alibaba/excel/read/metadata/holder/ReadWorkbookHolder.java
  6. 2
      src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java
  7. 2
      src/main/java/com/alibaba/excel/util/StyleUtil.java
  8. 4
      src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java
  9. 5
      src/main/java/com/alibaba/excel/write/builder/ExcelWriterBuilder.java
  10. 4
      src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java
  11. 4
      src/main/java/com/alibaba/excel/write/metadata/WriteSheet.java
  12. 6
      src/main/java/com/alibaba/excel/write/metadata/WriteTable.java
  13. 19
      src/main/java/com/alibaba/excel/write/metadata/holder/AbstractWriteHolder.java
  14. 3
      src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java
  15. 2
      src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java
  16. 6
      src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java
  17. 7
      src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java
  18. 4
      src/main/java/com/alibaba/excel/write/style/column/SimpleColumnWidthStyleStrategy.java
  19. 2
      src/test/java/com/alibaba/easyexcel/test/core/annotation/AnnotationData.java
  20. 42
      src/test/java/com/alibaba/easyexcel/test/core/compatibility/AnnotationDataListener.java
  21. 17
      src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityData.java
  22. 133
      src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityDataTest.java
  23. 14
      src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionData.java
  24. 34
      src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataListener.java
  25. 88
      src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataTest.java
  26. 16
      src/test/java/com/alibaba/easyexcel/test/core/style/StyleData.java
  27. 34
      src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataListener.java
  28. 84
      src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataTest.java
  29. 16
      src/test/java/com/alibaba/easyexcel/test/core/template/TemplateData.java
  30. 34
      src/test/java/com/alibaba/easyexcel/test/core/template/TemplateDataListener.java
  31. 69
      src/test/java/com/alibaba/easyexcel/test/core/template/TemplateDataTest.java
  32. BIN
      src/test/resources/template/template03.xls
  33. BIN
      src/test/resources/template/template07.xlsx

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

@ -21,12 +21,12 @@ import com.alibaba.excel.write.metadata.WriteWorkbook;
/** /**
* Excel Writer This tool is used to write value out to Excel via POI. This object can perform the following two * Excel Writer This tool is used to write value out to Excel via POI. This object can perform the following two
* functions. * functions.
* *
* <pre> * <pre>
* 1. Create a new empty Excel workbook, write the value to the stream after the value is filled. * 1. Create a new empty Excel workbook, write the value to the stream after the value is filled.
* 2. Edit existing Excel, write the original Excel file, or write it to other places.} * 2. Edit existing Excel, write the original Excel file, or write it to other places.}
* </pre> * </pre>
* *
* @author jipengfei * @author jipengfei
*/ */
public class ExcelWriter { public class ExcelWriter {
@ -34,7 +34,7 @@ public class ExcelWriter {
/** /**
* Create new writer * Create new writer
* *
* @param writeWorkbook * @param writeWorkbook
*/ */
public ExcelWriter(WriteWorkbook writeWorkbook) { public ExcelWriter(WriteWorkbook writeWorkbook) {
@ -197,6 +197,7 @@ public class ExcelWriter {
writeSheet.setClazz(sheet.getClazz()); writeSheet.setClazz(sheet.getClazz());
writeSheet.setHead(sheet.getHead()); writeSheet.setHead(sheet.getHead());
writeSheet.setTableStyle(sheet.getTableStyle()); writeSheet.setTableStyle(sheet.getTableStyle());
writeSheet.setRelativeHeadRowIndex(sheet.getHeadLineMun());
writeSheet.setColumnWidthMap(sheet.getColumnWidthMap()); writeSheet.setColumnWidthMap(sheet.getColumnWidthMap());
} }

6
src/main/java/com/alibaba/excel/annotation/write/style/ColumnWidth.java

@ -8,7 +8,7 @@ import java.lang.annotation.Target;
/** /**
* Set the width of the table * Set the width of the table
* *
* @author zhuangjiaju * @author zhuangjiaju
*/ */
@Target({ElementType.FIELD, ElementType.TYPE}) @Target({ElementType.FIELD, ElementType.TYPE})
@ -16,9 +16,7 @@ import java.lang.annotation.Target;
@Inherited @Inherited
public @interface ColumnWidth { public @interface ColumnWidth {
/** /**
* Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi). If * Column width
* you set a column width to be 8 characters wide, e.g. <code>8*256</code>
*
* <p> * <p>
* -1 mean the auto set width * -1 mean the auto set width
*/ */

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

@ -55,11 +55,15 @@ public class AnalysisContextImpl implements AnalysisContext {
@Override @Override
public void currentSheet(ExcelExecutor excelExecutor, ReadSheet readSheet) { public void currentSheet(ExcelExecutor excelExecutor, ReadSheet readSheet) {
if (readSheet == null) { if (readSheet == null) {
throw new IllegalArgumentException("Sheet argument cannot be null"); throw new IllegalArgumentException("Sheet argument cannot be null.");
} }
readSheetHolder = new ReadSheetHolder(readSheet, readWorkbookHolder); readSheetHolder = new ReadSheetHolder(readSheet, readWorkbookHolder);
currentReadHolder = readSheetHolder; currentReadHolder = readSheetHolder;
selectSheet(excelExecutor); selectSheet(excelExecutor);
if (readWorkbookHolder.getHasReadSheet().contains(readSheetHolder.getSheetNo())) {
throw new ExcelAnalysisException("Cannot read sheet repeatedly.");
}
readWorkbookHolder.getHasReadSheet().add(readSheetHolder.getSheetNo());
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Began to read:{}", readSheetHolder); LOGGER.debug("Began to read:{}", readSheetHolder);
} }
@ -135,7 +139,7 @@ public class AnalysisContextImpl implements AnalysisContext {
@Override @Override
public ReadHolder currentReadHolder() { public ReadHolder currentReadHolder() {
return readSheetHolder; return currentReadHolder;
} }
@Override @Override

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

@ -2,11 +2,11 @@ package com.alibaba.excel.metadata;
import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.IndexedColors;
import com.alibaba.excel.write.style.RowCellStyleStrategy; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
/** /**
* @author jipengfei * @author jipengfei
* @deprecated please use {@link RowCellStyleStrategy} * @deprecated please use {@link HorizontalCellStyleStrategy}
*/ */
@Deprecated @Deprecated
public class TableStyle { public class TableStyle {

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

@ -2,6 +2,8 @@ package com.alibaba.excel.read.metadata.holder;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -76,6 +78,11 @@ public class ReadWorkbookHolder extends AbstractReadHolder {
@Deprecated @Deprecated
private Boolean convertAllFiled; private Boolean convertAllFiled;
/**
* Prevent repeating sheet
*/
private Set<Integer> hasReadSheet;
public ReadWorkbookHolder(ReadWorkbook readWorkbook) { public ReadWorkbookHolder(ReadWorkbook readWorkbook) {
super(readWorkbook, null, readWorkbook.getConvertAllFiled()); super(readWorkbook, null, readWorkbook.getConvertAllFiled());
this.readWorkbook = readWorkbook; this.readWorkbook = readWorkbook;
@ -107,6 +114,7 @@ public class ReadWorkbookHolder extends AbstractReadHolder {
if (readCache != null && ExcelTypeEnum.XLS == excelType) { if (readCache != null && ExcelTypeEnum.XLS == excelType) {
LOGGER.warn("Xls not support 'readCache'!"); LOGGER.warn("Xls not support 'readCache'!");
} }
this.hasReadSheet = new HashSet<Integer>();
} }
public ReadWorkbook getReadWorkbook() { public ReadWorkbook getReadWorkbook() {
@ -189,6 +197,14 @@ public class ReadWorkbookHolder extends AbstractReadHolder {
this.convertAllFiled = convertAllFiled; this.convertAllFiled = convertAllFiled;
} }
public Set<Integer> getHasReadSheet() {
return hasReadSheet;
}
public void setHasReadSheet(Set<Integer> hasReadSheet) {
this.hasReadSheet = hasReadSheet;
}
@Override @Override
public HolderEnum holderType() { public HolderEnum holderType() {
return HolderEnum.WORKBOOK; return HolderEnum.WORKBOOK;

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

@ -29,7 +29,7 @@ public enum ExcelTypeEnum {
public static ExcelTypeEnum valueOf(File file, InputStream inputStream) { public static ExcelTypeEnum valueOf(File file, InputStream inputStream) {
try { try {
FileMagic fileMagic = null; FileMagic fileMagic;
if (file != null) { if (file != null) {
fileMagic = FileMagic.valueOf(file); fileMagic = FileMagic.valueOf(file);
if (!FileMagic.OLE2.equals(fileMagic) && !FileMagic.OOXML.equals(fileMagic)) { if (!FileMagic.OLE2.equals(fileMagic) && !FileMagic.OOXML.equals(fileMagic)) {

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

@ -29,8 +29,10 @@ public class StyleUtil {
newCellStyle.setLocked(true); newCellStyle.setLocked(true);
newCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); newCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
newCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); newCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
newCellStyle.setBorderTop(BorderStyle.THIN);
newCellStyle.setBorderBottom(BorderStyle.THIN); newCellStyle.setBorderBottom(BorderStyle.THIN);
newCellStyle.setBorderLeft(BorderStyle.THIN); newCellStyle.setBorderLeft(BorderStyle.THIN);
newCellStyle.setBorderRight(BorderStyle.THIN);
return newCellStyle; return newCellStyle;
} }

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

@ -68,9 +68,9 @@ public class ExcelBuilderImpl implements ExcelBuilder {
lastRowNum--; lastRowNum--;
} }
if (!data.isEmpty()) { if (!data.isEmpty()) {
context.writeSheetHolder().setWriteLastRowType(WriteLastRowType.HAVE_DATA); writeSheetHolder.setWriteLastRowType(WriteLastRowType.HAVE_DATA);
} }
if (context.currentWriteHolder().isNew()) { if (writeSheetHolder.isNew() && !writeSheetHolder.getExcelWriteHeadProperty().hasHead()) {
lastRowNum += context.currentWriteHolder().relativeHeadRowIndex(); lastRowNum += context.currentWriteHolder().relativeHeadRowIndex();
} }
for (int relativeRowIndex = 0; relativeRowIndex < data.size(); relativeRowIndex++) { for (int relativeRowIndex = 0; relativeRowIndex < data.size(); relativeRowIndex++) {

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

@ -193,14 +193,15 @@ public class ExcelWriterBuilder {
} }
public ExcelWriterSheetBuilder sheet(Integer sheetNo, String sheetName) { public ExcelWriterSheetBuilder sheet(Integer sheetNo, String sheetName) {
ExcelWriterSheetBuilder excelWriterSheetBuilder = new ExcelWriterSheetBuilder(build()); ExcelWriter excelWriter = build();
ExcelWriterSheetBuilder excelWriterSheetBuilder = new ExcelWriterSheetBuilder(excelWriter);
if (sheetNo != null) { if (sheetNo != null) {
excelWriterSheetBuilder.sheetNo(sheetNo); excelWriterSheetBuilder.sheetNo(sheetNo);
} }
if (sheetName != null) { if (sheetName != null) {
excelWriterSheetBuilder.sheetName(sheetName); excelWriterSheetBuilder.sheetName(sheetName);
} }
return new ExcelWriterSheetBuilder(build()); return new ExcelWriterSheetBuilder(excelWriter);
} }
} }

4
src/main/java/com/alibaba/excel/write/handler/DefaultWriteHandlerLoader.java

@ -7,7 +7,7 @@ import org.apache.poi.ss.usermodel.IndexedColors;
import com.alibaba.excel.write.metadata.style.WriteCellStyle; import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont; import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.RowCellStyleStrategy; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
/** /**
* Load default handler * Load default handler
@ -30,7 +30,7 @@ public class DefaultWriteHandlerLoader {
headWriteFont.setFontHeightInPoints((short)14); headWriteFont.setFontHeightInPoints((short)14);
headWriteFont.setBold(true); headWriteFont.setBold(true);
headWriteCellStyle.setWriteFont(headWriteFont); headWriteCellStyle.setWriteFont(headWriteFont);
handlerList.add(new RowCellStyleStrategy(headWriteCellStyle, new ArrayList<WriteCellStyle>())); handlerList.add(new HorizontalCellStyleStrategy(headWriteCellStyle, new ArrayList<WriteCellStyle>()));
return handlerList; return handlerList;
} }

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

@ -4,7 +4,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import com.alibaba.excel.metadata.TableStyle; import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.write.style.RowCellStyleStrategy; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy; import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
/** /**
@ -30,7 +30,7 @@ public class WriteSheet extends WriteBasicParameter {
private Map<Integer, Integer> columnWidthMap = new HashMap<Integer, Integer>(); private Map<Integer, Integer> columnWidthMap = new HashMap<Integer, Integer>();
/** /**
* *
* @deprecated please use{@link RowCellStyleStrategy} * @deprecated please use{@link HorizontalCellStyleStrategy}
*/ */
@Deprecated @Deprecated
private TableStyle tableStyle; private TableStyle tableStyle;

6
src/main/java/com/alibaba/excel/write/metadata/WriteTable.java

@ -1,11 +1,11 @@
package com.alibaba.excel.write.metadata; package com.alibaba.excel.write.metadata;
import com.alibaba.excel.metadata.TableStyle; import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.write.style.RowCellStyleStrategy; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
/** /**
* table * table
* *
* @author jipengfei * @author jipengfei
*/ */
public class WriteTable extends WriteBasicParameter { public class WriteTable extends WriteBasicParameter {
@ -15,7 +15,7 @@ public class WriteTable extends WriteBasicParameter {
private Integer tableNo; private Integer tableNo;
/** /**
* *
* @deprecated please use{@link RowCellStyleStrategy} * @deprecated please use{@link HorizontalCellStyleStrategy}
*/ */
@Deprecated @Deprecated
private TableStyle tableStyle; private TableStyle tableStyle;

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

@ -8,6 +8,7 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.IndexedColors;
import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.Converter;
@ -34,7 +35,7 @@ import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.style.WriteCellStyle; import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont; import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.property.ExcelWriteHeadProperty; import com.alibaba.excel.write.property.ExcelWriteHeadProperty;
import com.alibaba.excel.write.style.RowCellStyleStrategy; import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractHeadColumnWidthStyleStrategy; import com.alibaba.excel.write.style.column.AbstractHeadColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy; import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
@ -102,12 +103,8 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ
compatibleOldCode(writeBasicParameter); compatibleOldCode(writeBasicParameter);
// Set writeHandlerMap // Set writeHandlerMap
List<WriteHandler> handlerList; List<WriteHandler> handlerList = new ArrayList<WriteHandler>();
if (parentAbstractWriteHolder == null) {
handlerList = DefaultWriteHandlerLoader.loadDefaultHandler();
} else {
handlerList = new ArrayList<WriteHandler>();
}
// Initialization Annotation // Initialization Annotation
initAnnotationConfig(handlerList); initAnnotationConfig(handlerList);
@ -119,7 +116,10 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ
Map<Class<? extends WriteHandler>, List<WriteHandler>> parentWriteHandlerMap = null; Map<Class<? extends WriteHandler>, List<WriteHandler>> parentWriteHandlerMap = null;
if (parentAbstractWriteHolder != null) { if (parentAbstractWriteHolder != null) {
parentWriteHandlerMap = parentAbstractWriteHolder.getWriteHandlerMap(); parentWriteHandlerMap = parentAbstractWriteHolder.getWriteHandlerMap();
} else {
handlerList.addAll(DefaultWriteHandlerLoader.loadDefaultHandler());
} }
this.writeHandlerMap = sortAndClearUpHandler(handlerList, parentWriteHandlerMap); this.writeHandlerMap = sortAndClearUpHandler(handlerList, parentWriteHandlerMap);
// Set converterMap // Set converterMap
@ -166,7 +166,7 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ
writeBasicParameter.setCustomWriteHandlerList(new ArrayList<WriteHandler>()); writeBasicParameter.setCustomWriteHandlerList(new ArrayList<WriteHandler>());
} }
writeBasicParameter.getCustomWriteHandlerList() writeBasicParameter.getCustomWriteHandlerList()
.add(new RowCellStyleStrategy( .add(new HorizontalCellStyleStrategy(
buildWriteCellStyle(tableStyle.getTableHeadFont(), tableStyle.getTableHeadBackGroundColor()), buildWriteCellStyle(tableStyle.getTableHeadFont(), tableStyle.getTableHeadBackGroundColor()),
buildWriteCellStyle(tableStyle.getTableContentFont(), tableStyle.getTableContentBackGroundColor()))); buildWriteCellStyle(tableStyle.getTableContentFont(), tableStyle.getTableContentBackGroundColor())));
} }
@ -175,6 +175,7 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ
private WriteCellStyle buildWriteCellStyle(Font font, IndexedColors indexedColors) { private WriteCellStyle buildWriteCellStyle(Font font, IndexedColors indexedColors) {
WriteCellStyle writeCellStyle = new WriteCellStyle(); WriteCellStyle writeCellStyle = new WriteCellStyle();
if (indexedColors != null) { if (indexedColors != null) {
writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
writeCellStyle.setFillForegroundColor(indexedColors.getIndex()); writeCellStyle.setFillForegroundColor(indexedColors.getIndex());
} }
if (font != null) { if (font != null) {
@ -199,7 +200,7 @@ public abstract class AbstractWriteHolder extends AbstractHolder implements Writ
@Override @Override
protected Integer columnWidth(Head head) { protected Integer columnWidth(Head head) {
if (columnWidthMap.containsKey(head.getColumnIndex())) { if (columnWidthMap.containsKey(head.getColumnIndex())) {
columnWidthMap.get(head.getColumnIndex()); return columnWidthMap.get(head.getColumnIndex()) / 256;
} }
return 20; return 20;
} }

3
src/main/java/com/alibaba/excel/write/property/ExcelWriteHeadProperty.java

@ -109,6 +109,9 @@ public class ExcelWriteHeadProperty extends ExcelHeadProperty {
endY = k; endY = k;
alreadyRangeSet.addAll(tempAlreadyRangeSet); alreadyRangeSet.addAll(tempAlreadyRangeSet);
} }
if (j == endY && i == endX) {
continue;
}
cellRangeList.add(new CellRange(j, endY, i, endX)); cellRangeList.add(new CellRange(j, endY, i, endX));
} }
} }

2
src/main/java/com/alibaba/excel/write/style/AbstractColumnCellStyleStrategy.java → src/main/java/com/alibaba/excel/write/style/AbstractVerticalCellStyleStrategy.java

@ -17,7 +17,7 @@ import com.alibaba.excel.write.metadata.style.WriteCellStyle;
* *
* @author zhuangjiaju * @author zhuangjiaju
*/ */
public abstract class AbstractColumnCellStyleStrategy extends AbstractCellStyleStrategy { public abstract class AbstractVerticalCellStyleStrategy extends AbstractCellStyleStrategy {
private Workbook workbook; private Workbook workbook;
private Map<Integer, CellStyle> headCellStyleCache = new HashMap<Integer, CellStyle>(); private Map<Integer, CellStyle> headCellStyleCache = new HashMap<Integer, CellStyle>();

6
src/main/java/com/alibaba/excel/write/style/RowCellStyleStrategy.java → src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java

@ -17,7 +17,7 @@ import com.alibaba.excel.write.metadata.style.WriteCellStyle;
* *
* @author zhuangjiaju * @author zhuangjiaju
*/ */
public class RowCellStyleStrategy extends AbstractCellStyleStrategy { public class HorizontalCellStyleStrategy extends AbstractCellStyleStrategy {
private WriteCellStyle headWriteCellStyle; private WriteCellStyle headWriteCellStyle;
private List<WriteCellStyle> contentWriteCellStyleList; private List<WriteCellStyle> contentWriteCellStyleList;
@ -25,12 +25,12 @@ public class RowCellStyleStrategy extends AbstractCellStyleStrategy {
private CellStyle headCellStyle; private CellStyle headCellStyle;
private List<CellStyle> contentCellStyleList; private List<CellStyle> contentCellStyleList;
public RowCellStyleStrategy(WriteCellStyle headWriteCellStyle, List<WriteCellStyle> contentWriteCellStyleList) { public HorizontalCellStyleStrategy(WriteCellStyle headWriteCellStyle, List<WriteCellStyle> contentWriteCellStyleList) {
this.headWriteCellStyle = headWriteCellStyle; this.headWriteCellStyle = headWriteCellStyle;
this.contentWriteCellStyleList = contentWriteCellStyleList; this.contentWriteCellStyleList = contentWriteCellStyleList;
} }
public RowCellStyleStrategy(WriteCellStyle headWriteCellStyle, WriteCellStyle contentWriteCellStyle) { public HorizontalCellStyleStrategy(WriteCellStyle headWriteCellStyle, WriteCellStyle contentWriteCellStyle) {
this.headWriteCellStyle = headWriteCellStyle; this.headWriteCellStyle = headWriteCellStyle;
contentWriteCellStyleList = new ArrayList<WriteCellStyle>(); contentWriteCellStyleList = new ArrayList<WriteCellStyle>();
contentWriteCellStyleList.add(contentWriteCellStyle); contentWriteCellStyleList.add(contentWriteCellStyle);

7
src/main/java/com/alibaba/excel/write/style/column/AbstractHeadColumnWidthStyleStrategy.java

@ -18,7 +18,8 @@ public abstract class AbstractHeadColumnWidthStyleStrategy extends AbstractColum
} }
Integer width = columnWidth(head); Integer width = columnWidth(head);
if (width != null) { if (width != null) {
sheet.setColumnWidth(cell.getColumnIndex(), columnWidth(head)); width = width * 256;
sheet.setColumnWidth(cell.getColumnIndex(), width);
} }
} }
@ -29,9 +30,7 @@ public abstract class AbstractHeadColumnWidthStyleStrategy extends AbstractColum
* *
* @param head * @param head
* Nullable * Nullable
* @return the width in units of 1/256th of a character width . Using the Calibri font as an example, the maximum * @return
* digit width of 11 point font size is 7 pixels (at 96 dpi). If you set a column width to be eight
* characters wide, e.g. you need return 8*256
*/ */
protected abstract Integer columnWidth(Head head); protected abstract Integer columnWidth(Head head);
} }

4
src/main/java/com/alibaba/excel/write/style/column/SimpleColumnWidthStyleStrategy.java

@ -11,11 +11,9 @@ public class SimpleColumnWidthStyleStrategy extends AbstractHeadColumnWidthStyle
private Integer columnWidth; private Integer columnWidth;
/** /**
* Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi). * If
* you set a column width to be eight characters wide, e.g. <code>SimpleColumnWidthStyleStrategy( 8*256)</code>,
* *
* @param columnWidth * @param columnWidth
* the width in units of 1/256th of a character width *
*/ */
public SimpleColumnWidthStyleStrategy(Integer columnWidth) { public SimpleColumnWidthStyleStrategy(Integer columnWidth) {
this.columnWidth = columnWidth; this.columnWidth = columnWidth;

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

@ -17,7 +17,7 @@ import lombok.Data;
* @author zhuangjiaju * @author zhuangjiaju
*/ */
@Data @Data
@ColumnWidth(30 * 256) @ColumnWidth(30)
@HeadRowHeight(15) @HeadRowHeight(15)
@ContentRowHeight(20) @ContentRowHeight(20)
public class AnnotationData { public class AnnotationData {

42
src/test/java/com/alibaba/easyexcel/test/core/compatibility/AnnotationDataListener.java

@ -0,0 +1,42 @@
package com.alibaba.easyexcel.test.core.compatibility;
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.easyexcel.test.core.annotation.AnnotationData;
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)));
}
}

17
src/test/java/com/alibaba/easyexcel/test/core/compatibility/CompatibilityData.java

@ -0,0 +1,17 @@
package com.alibaba.easyexcel.test.core.compatibility;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class CompatibilityData extends BaseRowModel {
@ExcelProperty("字符串标题0")
private String string0;
@ExcelProperty("字符串标题1")
private String string1;
}

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

@ -0,0 +1,133 @@
package com.alibaba.easyexcel.test.core.compatibility;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.junit.BeforeClass;
import org.junit.Test;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcelFactory;
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;
/**
*
* @author zhuangjiaju
*/
public class CompatibilityDataTest {
private static File file07;
private static File file03;
@BeforeClass
public static void init() {
file07 = TestFileUtil.createNewFile("compatibility07.xlsx");
file03 = TestFileUtil.createNewFile("compatibility03.xls");
}
@Test
public void T01ReadAndWrite07() throws Exception {
readAndWrite(file07);
}
@Test
public void T02ReadAndWrite03() throws Exception {
readAndWrite(file03);
}
private void readAndWrite(File file) throws Exception {
OutputStream out = new FileOutputStream(file);
ExcelWriter writer = EasyExcelFactory.getWriter(out);
// sheet1 width,string head,stirng data
Sheet sheet1 = new Sheet(1, 3);
sheet1.setSheetName("第一个sheet");
Map columnWidth = new HashMap();
columnWidth.put(0, 10000);
columnWidth.put(1, 50000);
sheet1.setColumnWidthMap(columnWidth);
sheet1.setHead(head());
writer.write1(listData(), sheet1);
// sheet2 style,class head
Sheet sheet2 = new Sheet(2, 3, CompatibilityData.class, "第二个sheet", null);
sheet2.setTableStyle(style());
writer.write(data(), sheet2);
// sheet3 table
Sheet sheet3 = new Sheet(3, 0);
sheet3.setSheetName("第三个sheet");
Table table1 = new Table(1);
table1.setHead(head());
writer.write1(listData(), sheet3, table1);
Table table2 = new Table(2);
table2.setClazz(CompatibilityData.class);
writer.write(data(), sheet3, table2);
writer.finish();
out.close();
// EasyExcelFactory.write(file, AnnotationData.class).sheet().doWrite(data()).finish();
// EasyExcelFactory.read(file, AnnotationData.class, new AnnotationDataListener()).sheet().doRead().finish();
}
private List<List<String>> head() {
List<List<String>> list = new ArrayList<List<String>>();
List<String> head0 = new ArrayList<String>();
head0.add("字符串标题0");
List<String> head1 = new ArrayList<String>();
head1.add("字符串标题1");
list.add(head0);
list.add(head1);
return list;
}
private List<List<Object>> listData() {
List<List<Object>> list = new ArrayList<List<Object>>();
List<Object> data0 = new ArrayList<Object>();
data0.add("字符串0");
data0.add(1);
list.add(data0);
return list;
}
private List<CompatibilityData> data() {
List<CompatibilityData> list = new ArrayList<CompatibilityData>();
for (int i = 0; i < 10; i++) {
CompatibilityData data = new CompatibilityData();
data.setString0("字符串0" + i);
data.setString1("字符串1" + i);
list.add(data);
}
return list;
}
public TableStyle style() {
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;
}
}

14
src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionData.java

@ -0,0 +1,14 @@
package com.alibaba.easyexcel.test.core.repetition;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class RepetitionData {
@ExcelProperty("字符串")
private String string;
}

34
src/test/java/com/alibaba/easyexcel/test/core/repetition/RepetitionDataListener.java

@ -0,0 +1,34 @@
package com.alibaba.easyexcel.test.core.repetition;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.easyexcel.test.core.simple.SimpleDataListener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class RepetitionDataListener extends AnalysisEventListener<RepetitionData> {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleDataListener.class);
List<RepetitionData> list = new ArrayList<RepetitionData>();
@Override
public void invoke(RepetitionData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 2);
Assert.assertEquals(list.get(0).getString(), "字符串0");
Assert.assertEquals(list.get(1).getString(), "字符串0");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

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

@ -0,0 +1,88 @@
package com.alibaba.easyexcel.test.core.repetition;
import java.io.File;
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.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 RepetitionDataTest {
private static File file07;
private static File file03;
private static File fileTable07;
private static File fileTable03;
@BeforeClass
public static void init() {
file07 = TestFileUtil.createNewFile("repetition07.xlsx");
file03 = TestFileUtil.createNewFile("repetition03.xls");
fileTable07 = TestFileUtil.createNewFile("repetitionTable07.xlsx");
fileTable03 = TestFileUtil.createNewFile("repetitionTable03.xls");
}
@Test
public void T01ReadAndWrite07() {
readAndWrite(file07);
}
@Test
public void T02ReadAndWrite03() {
readAndWrite(file03);
}
private void readAndWrite(File file) {
ExcelWriter excelWriter = EasyExcelFactory.write(file, RepetitionData.class).build();
WriteSheet writeSheet = EasyExcelFactory.writerSheet(0).build();
excelWriter.write(data(), writeSheet).write(data(), writeSheet).finish();
ExcelReader excelReader =
EasyExcelFactory.read(file, RepetitionData.class, new RepetitionDataListener()).build();
ReadSheet readSheet = EasyExcelFactory.readSheet(0).build();
excelReader.read(readSheet).finish();
}
@Test
public void T03ReadAndWriteTable07() {
readAndWriteTable(fileTable07);
}
@Test
public void T04ReadAndWriteTable03() {
readAndWriteTable(fileTable03);
}
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();
excelWriter.write(data(), writeSheet, writeTable).write(data(), writeSheet, writeTable).finish();
ExcelReader excelReader =
EasyExcelFactory.read(file, RepetitionData.class, new RepetitionDataListener()).build();
ReadSheet readSheet = EasyExcelFactory.readSheet(0).headRowNumber(2).build();
excelReader.read(readSheet).finish();
}
private List<RepetitionData> data() {
List<RepetitionData> list = new ArrayList<RepetitionData>();
RepetitionData data = new RepetitionData();
data.setString("字符串0");
list.add(data);
return list;
}
}

16
src/test/java/com/alibaba/easyexcel/test/core/style/StyleData.java

@ -0,0 +1,16 @@
package com.alibaba.easyexcel.test.core.style;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class StyleData {
@ExcelProperty("字符串")
private String string;
@ExcelProperty("字符串1")
private String string1;
}

34
src/test/java/com/alibaba/easyexcel/test/core/style/StyleDataListener.java

@ -0,0 +1,34 @@
package com.alibaba.easyexcel.test.core.style;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.easyexcel.test.core.simple.SimpleDataListener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class StyleDataListener extends AnalysisEventListener<StyleData> {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleDataListener.class);
List<StyleData> list = new ArrayList<StyleData>();
@Override
public void invoke(StyleData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 2);
Assert.assertEquals(list.get(0).getString(), "字符串0");
Assert.assertEquals(list.get(1).getString(), "字符串1");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

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

@ -0,0 +1,84 @@
package com.alibaba.easyexcel.test.core.style;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
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.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
/**
*
* @author zhuangjiaju
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class StyleDataTest {
private static File file07;
private static File file03;
@BeforeClass
public static void init() {
file07 = TestFileUtil.createNewFile("style07.xlsx");
file03 = TestFileUtil.createNewFile("style03.xls");
}
@Test
public void T01ReadAndWrite07() {
readAndWrite(file07);
}
@Test
public void T02ReadAndWrite03() {
readAndWrite(file03);
}
private void readAndWrite(File file) {
SimpleColumnWidthStyleStrategy simpleColumnWidthStyleStrategy = new SimpleColumnWidthStyleStrategy(50);
SimpleRowHeightStyleStrategy simpleRowHeightStyleStrategy =
new SimpleRowHeightStyleStrategy((short)40, (short)50);
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short)20);
headWriteCellStyle.setWriteFont(headWriteFont);
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
WriteFont contentWriteFont = new WriteFont();
contentWriteFont.setFontHeightInPoints((short)20);
headWriteCellStyle.setWriteFont(contentWriteFont);
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
EasyExcelFactory.write(file, StyleData.class).registerWriteHandler(simpleColumnWidthStyleStrategy)
.registerWriteHandler(simpleRowHeightStyleStrategy).registerWriteHandler(horizontalCellStyleStrategy)
.sheet().doWrite(data()).finish();
EasyExcelFactory.read(file, StyleData.class, new StyleDataListener()).sheet().doRead().finish();
}
private List<StyleData> data() {
List<StyleData> list = new ArrayList<StyleData>();
StyleData data = new StyleData();
data.setString("字符串0");
data.setString1("字符串01");
StyleData data1 = new StyleData();
data1.setString("字符串1");
data1.setString1("字符串11");
list.add(data);
list.add(data1);
return list;
}
}

16
src/test/java/com/alibaba/easyexcel/test/core/template/TemplateData.java

@ -0,0 +1,16 @@
package com.alibaba.easyexcel.test.core.template;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @author zhuangjiaju
*/
@Data
public class TemplateData {
@ExcelProperty("字符串0")
private String string0;
@ExcelProperty("字符串1")
private String string1;
}

34
src/test/java/com/alibaba/easyexcel/test/core/template/TemplateDataListener.java

@ -0,0 +1,34 @@
package com.alibaba.easyexcel.test.core.template;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.easyexcel.test.core.simple.SimpleDataListener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
/**
* @author zhuangjiaju
*/
public class TemplateDataListener extends AnalysisEventListener<TemplateData> {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleDataListener.class);
List<TemplateData> list = new ArrayList<TemplateData>();
@Override
public void invoke(TemplateData data, AnalysisContext context) {
list.add(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
Assert.assertEquals(list.size(), 2);
Assert.assertEquals(list.get(0).getString0(), "字符串0");
Assert.assertEquals(list.get(1).getString0(), "字符串1");
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0)));
}
}

69
src/test/java/com/alibaba/easyexcel/test/core/template/TemplateDataTest.java

@ -0,0 +1,69 @@
package com.alibaba.easyexcel.test.core.template;
import java.io.File;
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 TemplateDataTest {
private static File file07;
private static File file03;
@BeforeClass
public static void init() {
file07 = TestFileUtil.createNewFile("template07.xlsx");
file03 = TestFileUtil.createNewFile("template03.xls");
}
@Test
public void T01ReadAndWrite07() {
readAndWrite07(file07);
}
@Test
public void T02ReadAndWrite03() {
readAndWrite03(file03);
}
private void readAndWrite07(File file) {
EasyExcelFactory.write(file, TemplateData.class)
.withTemplate(TestFileUtil.readFile("template" + File.separator + "template07.xlsx")).sheet()
.doWrite(data()).finish();
EasyExcelFactory.read(file, TemplateData.class, new TemplateDataListener()).headRowNumber(2).sheet().doRead()
.finish();
}
private void readAndWrite03(File file) {
EasyExcelFactory.write(file, TemplateData.class)
.withTemplate(TestFileUtil.readFile("template" + File.separator + "template03.xls")).sheet().doWrite(data())
.finish();
EasyExcelFactory.read(file, TemplateData.class, new TemplateDataListener()).headRowNumber(2).sheet().doRead()
.finish();
}
private List<TemplateData> data() {
List<TemplateData> list = new ArrayList<TemplateData>();
TemplateData data = new TemplateData();
data.setString0("字符串0");
data.setString1("字符串01");
TemplateData data1 = new TemplateData();
data1.setString0("字符串1");
data1.setString1("字符串11");
list.add(data);
list.add(data1);
return list;
}
}

BIN
src/test/resources/template/template03.xls

Binary file not shown.

BIN
src/test/resources/template/template07.xlsx

Binary file not shown.
Loading…
Cancel
Save