After Width: | Height: | Size: 5.3 KiB |
After Width: | Height: | Size: 5.0 KiB |
After Width: | Height: | Size: 1.9 KiB |
After Width: | Height: | Size: 4.8 KiB |
After Width: | Height: | Size: 1.6 KiB |
After Width: | Height: | Size: 4.5 KiB |
After Width: | Height: | Size: 1.5 KiB |
After Width: | Height: | Size: 1.7 KiB |
After Width: | Height: | Size: 811 B |
After Width: | Height: | Size: 1.6 KiB |
After Width: | Height: | Size: 1.8 KiB |
@ -1,116 +0,0 @@
|
||||
# 常见问题汇总 |
||||
|
||||
## 1、系统环境变量缺失或JDK版本不支持 |
||||
|
||||
``` |
||||
java.lang.NullPointerException |
||||
at sun.awt.FontConfiguration.getVersion(FontConfiguration.java:1264) |
||||
at sun.awt.FontConfiguration.readFontConfigFile(FontConfiguration.java:219) |
||||
at sun.awt.FontConfiguration.init(FontConfiguration.java:107) |
||||
at sun.awt.X11FontManager.createFontConfiguration(X11FontManager.java:774) |
||||
at sun.font.SunFontManager$2.run(SunFontManager.java:431) |
||||
at java.security.AccessController.doPrivileged(Native Method) |
||||
at sun.font.SunFontManager.<init>(SunFontManager.java:376) |
||||
at sun.awt.FcFontManager.<init>(FcFontManager.java:35) |
||||
at sun.awt.X11FontManager.<init>(X11FontManager.java:57) |
||||
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) |
||||
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) |
||||
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) |
||||
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) |
||||
at java.lang.Class.newInstance(Class.java:442) |
||||
at sun.font.FontManagerFactory$1.run(FontManagerFactory.java:83) |
||||
at java.security.AccessController.doPrivileged(Native Method) |
||||
at sun.font.FontManagerFactory.getInstance(FontManagerFactory.java:74) |
||||
at java.awt.Font.getFont2D(Font.java:495) |
||||
at java.awt.Font.canDisplayUpTo(Font.java:2080) |
||||
at java.awt.font.TextLayout.singleFont(TextLayout.java:470) |
||||
at java.awt.font.TextLayout.<init>(TextLayout.java:531) |
||||
at org.apache.poi.ss.util.SheetUtil.getDefaultCharWidth(SheetUtil.java:275) |
||||
at org.apache.poi.xssf.streaming.AutoSizeColumnTracker.<init>(AutoSizeColumnTracker.java:117) |
||||
at org.apache.poi.xssf.streaming.SXSSFSheet.<init>(SXSSFSheet.java:79) |
||||
at org.apache.poi.xssf.streaming.SXSSFWorkbook.createAndRegisterSXSSFSheet(SXSSFWorkbook.java:656) |
||||
at org.apache.poi.xssf.streaming.SXSSFWorkbook.createSheet(SXSSFWorkbook.java:677) |
||||
at org.apache.poi.xssf.streaming.SXSSFWorkbook.createSheet(SXSSFWorkbook.java:83) |
||||
at com.alibaba.excel.write.context.GenerateContextImpl.buildCurrentSheet(GenerateContextImpl.java:93) |
||||
at com.alibaba.excel.write.ExcelBuilderImpl.addContent(ExcelBuilderImpl.java:53) |
||||
at com.alibaba.excel.ExcelWriter.write(ExcelWriter.java:44) |
||||
``` |
||||
|
||||
### 解决方法 |
||||
|
||||
该异常由于自己的环境变量缺少swing需要的字体配置,检查自己应用是否有配置-Djava.awt.headless=true,如果没有请加上该系统参数,可以解决问题。如果仍旧不行,在dockerfile中增加字体安装命令: |
||||
![粘贴图片.png](http://ata2-img.cn-hangzhou.img-pub.aliyun-inc.com/a857edfbc8199db7bb35b9e99f1f57d5.png) |
||||
参考: |
||||
https://lark.alipay.com/aone355606/gfqllg/ulptif |
||||
https://stackoverflow.com/questions/30626136/cannot-load-font-in-jre-8 http://www.jianshu.com/p/c05b5fc71bd0 |
||||
## 2、xls格式错用xlsx方式解析 |
||||
|
||||
``` |
||||
org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException: The supplied data appears to be in the OLE2 Format. You are calling the part of POI that deals with OOXML (Office Open XML) Documents. You need to call a different part of POI to process this data (eg HSSF instead of XSSF) |
||||
at org.apache.poi.openxml4j.opc.internal.ZipHelper.verifyZipHeader(ZipHelper.java:172) |
||||
at org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipStream(ZipHelper.java:229) |
||||
at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:97) |
||||
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:342) |
||||
at com.alibaba.excel.read.v07.XlsxSaxAnalyser.<init>(XlsxSaxAnalyser.java:46) |
||||
at com.alibaba.excel.read.ExcelAnalyserImpl.getSaxAnalyser(ExcelAnalyserImpl.java:30) |
||||
at com.alibaba.excel.read.ExcelAnalyserImpl.analysis(ExcelAnalyserImpl.java:51) |
||||
at com.alibaba.excel.ExcelReader.read(ExcelReader.java:55) |
||||
at read.v07.Read2007Xlsx.noModel(Read2007Xlsx.java:42) |
||||
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) |
||||
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) |
||||
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) |
||||
at java.lang.reflect.Method.invoke(Method.java:498) |
||||
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) |
||||
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) |
||||
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) |
||||
at mockit.integration.junit4.internal.BlockJUnit4ClassRunnerDecorator.executeTest(BlockJUnit4ClassRunnerDecorator.java:126) |
||||
at mockit.integration.junit4.internal.BlockJUnit4ClassRunnerDecorator.invokeExplosively(BlockJUnit4ClassRunnerDecorator.java:104) |
||||
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java) |
||||
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) |
||||
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) |
||||
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) |
||||
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) |
||||
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) |
||||
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) |
||||
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) |
||||
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) |
||||
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) |
||||
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) |
||||
at org.junit.runner.JUnitCore.run(JUnitCore.java:137) |
||||
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) |
||||
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51) |
||||
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237) |
||||
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) |
||||
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) |
||||
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) |
||||
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) |
||||
at java.lang.reflect.Method.invoke(Method.java:498) |
||||
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) |
||||
``` |
||||
|
||||
### 解决方法 |
||||
|
||||
该异常时由于03版的xls,文件用07版的方式做解析的报错,请检查excelType是否设置错误。或者是不是手动去修改了excel文件名后缀的xls为xlsx。 |
||||
|
||||
## 3、xlsx错用xls解析 |
||||
|
||||
``` |
||||
org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF) |
||||
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:152) |
||||
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:140) |
||||
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.<init>(NPOIFSFileSystem.java:302) |
||||
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:87) |
||||
at com.alibaba.excel.read.v03.XlsSaxAnalyser.<init>(XlsSaxAnalyser.java:55) |
||||
at com.alibaba.excel.read.ExcelAnalyserImpl.getSaxAnalyser(ExcelAnalyserImpl.java:27) |
||||
at com.alibaba.excel.read.ExcelAnalyserImpl.analysis(ExcelAnalyserImpl.java:51) |
||||
at com.alibaba.excel.ExcelReader.read(ExcelReader.java:55) |
||||
at read.v03.XLS2003FunctionTest.testExcel2003NoModel(XLS2003FunctionTest.java:31) |
||||
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) |
||||
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) |
||||
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) |
||||
at java.lang.reflect.Method.invoke(Method.java:498) |
||||
at mockit.integration.junit3.internal.JUnitTestCaseDecorator.runTest(JUnitTestCaseDecorator.java:142) |
||||
at mockit.integration.junit3.internal.JUnitTestCaseDecorator.originalRunBare(JUnitTestCaseDecorator.java:102) |
||||
at mockit.integration.junit3.internal.JUnitTestCaseDecorator.runBare(JUnitTestCaseDecorator.java:87) |
||||
``` |
||||
原理和原因大致同上 |
@ -1,26 +0,0 @@
|
||||
package com.alibaba.excel.analysis; |
||||
|
||||
import java.util.List; |
||||
|
||||
import com.alibaba.excel.read.metadata.ReadSheet; |
||||
|
||||
/** |
||||
* Excel file Executor |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public interface ExcelExecutor { |
||||
|
||||
/** |
||||
* Returns the actual sheet in excel |
||||
* |
||||
* @return Actual sheet in excel |
||||
*/ |
||||
List<ReadSheet> sheetList(); |
||||
|
||||
/** |
||||
* Read sheet |
||||
*/ |
||||
void execute(); |
||||
|
||||
} |
@ -0,0 +1,30 @@
|
||||
package com.alibaba.excel.analysis; |
||||
|
||||
import java.util.List; |
||||
|
||||
import com.alibaba.excel.read.metadata.ReadSheet; |
||||
|
||||
/** |
||||
* Excel file Executor |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public interface ExcelReadExecutor { |
||||
|
||||
/** |
||||
* Returns the actual sheet in excel |
||||
* |
||||
* @return Actual sheet in excel |
||||
*/ |
||||
List<ReadSheet> sheetList(); |
||||
|
||||
/** |
||||
* Read the sheet. |
||||
* |
||||
* @param readSheetList |
||||
* Which sheets you need to read. |
||||
* @param readAll |
||||
* The <code>readSheetList</code> parameter is ignored, and all sheets are read. |
||||
*/ |
||||
void execute(List<ReadSheet> readSheetList, Boolean readAll); |
||||
} |
@ -0,0 +1,18 @@
|
||||
package com.alibaba.excel.annotation; |
||||
|
||||
import java.lang.annotation.ElementType; |
||||
import java.lang.annotation.Inherited; |
||||
import java.lang.annotation.Retention; |
||||
import java.lang.annotation.RetentionPolicy; |
||||
import java.lang.annotation.Target; |
||||
|
||||
/** |
||||
* Ignore all unannotated fields. |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@Target(ElementType.TYPE) |
||||
@Retention(RetentionPolicy.RUNTIME) |
||||
@Inherited |
||||
public @interface ExcelIgnoreUnannotated { |
||||
} |
@ -0,0 +1,17 @@
|
||||
package com.alibaba.excel.enums; |
||||
|
||||
/** |
||||
* Direction of writing |
||||
* |
||||
* @author Jiaju Zhuang |
||||
**/ |
||||
public enum WriteDirectionEnum { |
||||
/** |
||||
* Vertical write. |
||||
*/ |
||||
VERTICAL, |
||||
/** |
||||
* Horizontal write. |
||||
*/ |
||||
HORIZONTAL,; |
||||
} |
@ -0,0 +1,17 @@
|
||||
package com.alibaba.excel.enums; |
||||
|
||||
/** |
||||
* Type of template to read when writing |
||||
* |
||||
* @author Jiaju Zhuang |
||||
**/ |
||||
public enum WriteTemplateAnalysisCellTypeEnum { |
||||
/** |
||||
* Common field. |
||||
*/ |
||||
COMMON, |
||||
/** |
||||
* A collection of fields. |
||||
*/ |
||||
COLLECTION,; |
||||
} |
@ -0,0 +1,17 @@
|
||||
package com.alibaba.excel.enums; |
||||
|
||||
/** |
||||
* Enumeration of write methods |
||||
* |
||||
* @author Jiaju Zhuang |
||||
**/ |
||||
public enum WriteTypeEnum { |
||||
/** |
||||
* Add. |
||||
*/ |
||||
ADD, |
||||
/** |
||||
* Fill. |
||||
*/ |
||||
FILL,; |
||||
} |
@ -0,0 +1,67 @@
|
||||
package com.alibaba.excel.util; |
||||
|
||||
import java.util.List; |
||||
|
||||
import org.slf4j.Logger; |
||||
import org.slf4j.LoggerFactory; |
||||
|
||||
import com.alibaba.excel.metadata.GlobalConfiguration; |
||||
import com.alibaba.excel.read.metadata.ReadSheet; |
||||
|
||||
/** |
||||
* Sheet utils |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class SheetUtils { |
||||
private static final Logger LOGGER = LoggerFactory.getLogger(SheetUtils.class); |
||||
|
||||
private SheetUtils() {} |
||||
|
||||
/** |
||||
* Match the parameters to the actual sheet |
||||
* |
||||
* @param readSheet |
||||
* actual sheet |
||||
* @param parameterReadSheetList |
||||
* parameters |
||||
* @param readAll |
||||
* @return |
||||
*/ |
||||
public static ReadSheet match(ReadSheet readSheet, List<ReadSheet> parameterReadSheetList, Boolean readAll, |
||||
GlobalConfiguration globalConfiguration) { |
||||
if (readAll) { |
||||
return readSheet; |
||||
} |
||||
for (ReadSheet parameterReadSheet : parameterReadSheetList) { |
||||
if (parameterReadSheet == null) { |
||||
continue; |
||||
} |
||||
if (parameterReadSheet.getSheetNo() == null && parameterReadSheet.getSheetName() == null) { |
||||
if (LOGGER.isDebugEnabled()) { |
||||
LOGGER.debug("The first is read by default."); |
||||
} |
||||
parameterReadSheet.setSheetNo(0); |
||||
} |
||||
boolean match = (parameterReadSheet.getSheetNo() != null |
||||
&& parameterReadSheet.getSheetNo().equals(readSheet.getSheetNo())); |
||||
if (!match) { |
||||
String parameterSheetName = parameterReadSheet.getSheetName(); |
||||
if (!StringUtils.isEmpty(parameterSheetName)) { |
||||
boolean autoTrim = (parameterReadSheet.getAutoTrim() != null && parameterReadSheet.getAutoTrim()) |
||||
|| (parameterReadSheet.getAutoTrim() == null && globalConfiguration.getAutoTrim()); |
||||
if (autoTrim) { |
||||
parameterSheetName = parameterSheetName.trim(); |
||||
} |
||||
match = parameterSheetName.equals(readSheet.getSheetName()); |
||||
} |
||||
} |
||||
if (match) { |
||||
readSheet.copyBasicParameter(parameterReadSheet); |
||||
return readSheet; |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
} |
@ -0,0 +1,196 @@
|
||||
package com.alibaba.excel.util; |
||||
|
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
|
||||
import org.apache.poi.ss.usermodel.Cell; |
||||
import org.apache.poi.ss.usermodel.Row; |
||||
|
||||
import com.alibaba.excel.context.WriteContext; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
import com.alibaba.excel.metadata.Head; |
||||
import com.alibaba.excel.write.handler.CellWriteHandler; |
||||
import com.alibaba.excel.write.handler.RowWriteHandler; |
||||
import com.alibaba.excel.write.handler.SheetWriteHandler; |
||||
import com.alibaba.excel.write.handler.WorkbookWriteHandler; |
||||
import com.alibaba.excel.write.handler.WriteHandler; |
||||
|
||||
/** |
||||
* Write handler utils |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class WriteHandlerUtils { |
||||
|
||||
private WriteHandlerUtils() {} |
||||
|
||||
public static void beforeWorkbookCreate(WriteContext writeContext) { |
||||
List<WriteHandler> handlerList = |
||||
writeContext.writeWorkbookHolder().writeHandlerMap().get(WorkbookWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof WorkbookWriteHandler) { |
||||
((WorkbookWriteHandler)writeHandler).beforeWorkbookCreate(); |
||||
} |
||||
} |
||||
} |
||||
|
||||
public static void afterWorkbookCreate(WriteContext writeContext) { |
||||
List<WriteHandler> handlerList = |
||||
writeContext.writeWorkbookHolder().writeHandlerMap().get(WorkbookWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof WorkbookWriteHandler) { |
||||
((WorkbookWriteHandler)writeHandler).afterWorkbookCreate(writeContext.writeWorkbookHolder()); |
||||
} |
||||
} |
||||
} |
||||
|
||||
public static void afterWorkbookDispose(WriteContext writeContext) { |
||||
List<WriteHandler> handlerList = |
||||
writeContext.writeWorkbookHolder().writeHandlerMap().get(WorkbookWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof WorkbookWriteHandler) { |
||||
((WorkbookWriteHandler)writeHandler).afterWorkbookDispose(writeContext.writeWorkbookHolder()); |
||||
} |
||||
} |
||||
} |
||||
|
||||
public static void beforeSheetCreate(WriteContext writeContext) { |
||||
List<WriteHandler> handlerList = writeContext.writeSheetHolder().writeHandlerMap().get(SheetWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof SheetWriteHandler) { |
||||
((SheetWriteHandler)writeHandler).beforeSheetCreate(writeContext.writeWorkbookHolder(), |
||||
writeContext.writeSheetHolder()); |
||||
} |
||||
} |
||||
} |
||||
|
||||
public static void afterSheetCreate(WriteContext writeContext) { |
||||
List<WriteHandler> handlerList = writeContext.writeSheetHolder().writeHandlerMap().get(SheetWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof SheetWriteHandler) { |
||||
((SheetWriteHandler)writeHandler).afterSheetCreate(writeContext.writeWorkbookHolder(), |
||||
writeContext.writeSheetHolder()); |
||||
} |
||||
} |
||||
if (null != writeContext.writeWorkbookHolder().getWriteWorkbook().getWriteHandler()) { |
||||
writeContext.writeWorkbookHolder().getWriteWorkbook().getWriteHandler() |
||||
.sheet(writeContext.writeSheetHolder().getSheetNo(), writeContext.writeSheetHolder().getSheet()); |
||||
} |
||||
} |
||||
|
||||
public static void beforeCellCreate(WriteContext writeContext, Row row, Head head, Integer columnIndex, |
||||
Integer relativeRowIndex, Boolean isHead) { |
||||
List<WriteHandler> handlerList = |
||||
writeContext.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof CellWriteHandler) { |
||||
((CellWriteHandler)writeHandler).beforeCellCreate(writeContext.writeSheetHolder(), |
||||
writeContext.writeTableHolder(), row, head, columnIndex, relativeRowIndex, isHead); |
||||
} |
||||
} |
||||
} |
||||
|
||||
public static void afterCellCreate(WriteContext writeContext, Cell cell, Head head, Integer relativeRowIndex, |
||||
Boolean isHead) { |
||||
List<WriteHandler> handlerList = |
||||
writeContext.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof CellWriteHandler) { |
||||
((CellWriteHandler)writeHandler).afterCellCreate(writeContext.writeSheetHolder(), |
||||
writeContext.writeTableHolder(), cell, head, relativeRowIndex, isHead); |
||||
} |
||||
} |
||||
} |
||||
|
||||
public static void afterCellDispose(WriteContext writeContext, CellData cellData, Cell cell, Head head, |
||||
Integer relativeRowIndex, Boolean isHead) { |
||||
List<CellData> cellDataList = new ArrayList<CellData>(); |
||||
if (cell != null) { |
||||
cellDataList.add(cellData); |
||||
} |
||||
afterCellDispose(writeContext, cellDataList, cell, head, relativeRowIndex, isHead); |
||||
} |
||||
|
||||
public static void afterCellDispose(WriteContext writeContext, List<CellData> cellDataList, Cell cell, Head head, |
||||
Integer relativeRowIndex, Boolean isHead) { |
||||
List<WriteHandler> handlerList = |
||||
writeContext.currentWriteHolder().writeHandlerMap().get(CellWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof CellWriteHandler) { |
||||
((CellWriteHandler)writeHandler).afterCellDispose(writeContext.writeSheetHolder(), |
||||
writeContext.writeTableHolder(), cellDataList, cell, head, relativeRowIndex, isHead); |
||||
} |
||||
} |
||||
if (null != writeContext.writeWorkbookHolder().getWriteWorkbook().getWriteHandler()) { |
||||
writeContext.writeWorkbookHolder().getWriteWorkbook().getWriteHandler().cell(cell.getRowIndex(), cell); |
||||
} |
||||
} |
||||
|
||||
public static void beforeRowCreate(WriteContext writeContext, Integer rowIndex, Integer relativeRowIndex, |
||||
Boolean isHead) { |
||||
List<WriteHandler> handlerList = writeContext.currentWriteHolder().writeHandlerMap().get(RowWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof RowWriteHandler) { |
||||
((RowWriteHandler)writeHandler).beforeRowCreate(writeContext.writeSheetHolder(), |
||||
writeContext.writeTableHolder(), rowIndex, relativeRowIndex, isHead); |
||||
} |
||||
} |
||||
} |
||||
|
||||
public static void afterRowCreate(WriteContext writeContext, Row row, Integer relativeRowIndex, Boolean isHead) { |
||||
List<WriteHandler> handlerList = writeContext.currentWriteHolder().writeHandlerMap().get(RowWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof RowWriteHandler) { |
||||
((RowWriteHandler)writeHandler).afterRowCreate(writeContext.writeSheetHolder(), |
||||
writeContext.writeTableHolder(), row, relativeRowIndex, isHead); |
||||
} |
||||
} |
||||
|
||||
} |
||||
|
||||
public static void afterRowDispose(WriteContext writeContext, Row row, Integer relativeRowIndex, Boolean isHead) { |
||||
List<WriteHandler> handlerList = writeContext.currentWriteHolder().writeHandlerMap().get(RowWriteHandler.class); |
||||
if (handlerList == null || handlerList.isEmpty()) { |
||||
return; |
||||
} |
||||
for (WriteHandler writeHandler : handlerList) { |
||||
if (writeHandler instanceof RowWriteHandler) { |
||||
((RowWriteHandler)writeHandler).afterRowDispose(writeContext.writeSheetHolder(), |
||||
writeContext.writeTableHolder(), row, relativeRowIndex, isHead); |
||||
} |
||||
} |
||||
if (null != writeContext.writeWorkbookHolder().getWriteWorkbook().getWriteHandler()) { |
||||
writeContext.writeWorkbookHolder().getWriteWorkbook().getWriteHandler().row(row.getRowNum(), row); |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,140 @@
|
||||
package com.alibaba.excel.write.executor; |
||||
|
||||
import org.apache.poi.hssf.usermodel.HSSFWorkbook; |
||||
import org.apache.poi.ss.usermodel.Cell; |
||||
import org.apache.poi.ss.usermodel.ClientAnchor; |
||||
import org.apache.poi.ss.usermodel.CreationHelper; |
||||
import org.apache.poi.ss.usermodel.Drawing; |
||||
import org.apache.poi.ss.usermodel.Sheet; |
||||
|
||||
import com.alibaba.excel.context.WriteContext; |
||||
import com.alibaba.excel.converters.Converter; |
||||
import com.alibaba.excel.converters.ConverterKeyBuild; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.exception.ExcelDataConvertException; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
import com.alibaba.excel.metadata.property.ExcelContentProperty; |
||||
import com.alibaba.excel.write.metadata.holder.WriteHolder; |
||||
|
||||
/** |
||||
* Excel write Executor |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor { |
||||
protected WriteContext writeContext; |
||||
|
||||
public AbstractExcelWriteExecutor(WriteContext writeContext) { |
||||
this.writeContext = writeContext; |
||||
} |
||||
|
||||
protected CellData converterAndSet(WriteHolder currentWriteHolder, Class clazz, Cell cell, Object value, |
||||
ExcelContentProperty excelContentProperty) { |
||||
if (value == null) { |
||||
return new CellData(); |
||||
} |
||||
if (value instanceof String && currentWriteHolder.globalConfiguration().getAutoTrim()) { |
||||
value = ((String)value).trim(); |
||||
} |
||||
CellData cellData = convert(currentWriteHolder, clazz, cell, value, excelContentProperty); |
||||
if (cellData.getFormula() != null && cellData.getFormula()) { |
||||
cell.setCellFormula(cellData.getFormulaValue()); |
||||
} |
||||
switch (cellData.getType()) { |
||||
case STRING: |
||||
cell.setCellValue(cellData.getStringValue()); |
||||
return cellData; |
||||
case BOOLEAN: |
||||
cell.setCellValue(cellData.getBooleanValue()); |
||||
return cellData; |
||||
case NUMBER: |
||||
cell.setCellValue(cellData.getNumberValue().doubleValue()); |
||||
return cellData; |
||||
case IMAGE: |
||||
setImageValue(cellData, cell); |
||||
return cellData; |
||||
case EMPTY: |
||||
return cellData; |
||||
default: |
||||
throw new ExcelDataConvertException("Not supported data:" + value + " return type:" + cell.getCellType() |
||||
+ "at row:" + cell.getRow().getRowNum()); |
||||
} |
||||
} |
||||
|
||||
protected CellData convert(WriteHolder currentWriteHolder, Class clazz, Cell cell, Object value, |
||||
ExcelContentProperty excelContentProperty) { |
||||
if (value == null) { |
||||
return new CellData(); |
||||
} |
||||
// This means that the user has defined the data.
|
||||
if (value instanceof CellData) { |
||||
CellData cellDataValue = (CellData)value; |
||||
if (cellDataValue.getType() != null) { |
||||
return cellDataValue; |
||||
} else { |
||||
if (cellDataValue.getData() == null) { |
||||
cellDataValue.setType(CellDataTypeEnum.EMPTY); |
||||
return cellDataValue; |
||||
} |
||||
} |
||||
CellData cellDataReturn = doConvert(currentWriteHolder, cellDataValue.getData().getClass(), cell, |
||||
cellDataValue.getData(), excelContentProperty); |
||||
// The formula information is subject to user input
|
||||
if (cellDataValue.getFormula() != null) { |
||||
cellDataReturn.setFormula(cellDataValue.getFormula()); |
||||
cellDataReturn.setFormulaValue(cellDataValue.getFormulaValue()); |
||||
} |
||||
return cellDataReturn; |
||||
} |
||||
return doConvert(currentWriteHolder, clazz, cell, value, excelContentProperty); |
||||
} |
||||
|
||||
private CellData doConvert(WriteHolder currentWriteHolder, Class clazz, Cell cell, Object value, |
||||
ExcelContentProperty excelContentProperty) { |
||||
Converter converter = null; |
||||
if (excelContentProperty != null) { |
||||
converter = excelContentProperty.getConverter(); |
||||
} |
||||
if (converter == null) { |
||||
converter = currentWriteHolder.converterMap().get(ConverterKeyBuild.buildKey(clazz)); |
||||
} |
||||
if (converter == null) { |
||||
throw new ExcelDataConvertException( |
||||
"Can not find 'Converter' support class " + clazz.getSimpleName() + "."); |
||||
} |
||||
CellData cellData; |
||||
try { |
||||
cellData = |
||||
converter.convertToExcelData(value, excelContentProperty, currentWriteHolder.globalConfiguration()); |
||||
} catch (Exception e) { |
||||
throw new ExcelDataConvertException("Convert data:" + value + " error,at row:" + cell.getRow().getRowNum(), |
||||
e); |
||||
} |
||||
if (cellData == null || cellData.getType() == null) { |
||||
throw new ExcelDataConvertException( |
||||
"Convert data:" + value + " return null,at row:" + cell.getRow().getRowNum()); |
||||
} |
||||
return cellData; |
||||
} |
||||
|
||||
private void setImageValue(CellData cellData, Cell cell) { |
||||
Sheet sheet = cell.getSheet(); |
||||
int index = sheet.getWorkbook().addPicture(cellData.getImageValue(), HSSFWorkbook.PICTURE_TYPE_PNG); |
||||
Drawing drawing = sheet.getDrawingPatriarch(); |
||||
if (drawing == null) { |
||||
drawing = sheet.createDrawingPatriarch(); |
||||
} |
||||
CreationHelper helper = sheet.getWorkbook().getCreationHelper(); |
||||
ClientAnchor anchor = helper.createClientAnchor(); |
||||
anchor.setDx1(0); |
||||
anchor.setDx2(0); |
||||
anchor.setDy1(0); |
||||
anchor.setDy2(0); |
||||
anchor.setCol1(cell.getColumnIndex()); |
||||
anchor.setCol2(cell.getColumnIndex() + 1); |
||||
anchor.setRow1(cell.getRowIndex()); |
||||
anchor.setRow2(cell.getRowIndex() + 1); |
||||
anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE); |
||||
drawing.createPicture(anchor, index); |
||||
} |
||||
} |
@ -0,0 +1,179 @@
|
||||
package com.alibaba.excel.write.executor; |
||||
|
||||
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; |
||||
import java.util.Set; |
||||
|
||||
import org.apache.poi.ss.usermodel.Cell; |
||||
import org.apache.poi.ss.usermodel.Row; |
||||
|
||||
import com.alibaba.excel.context.WriteContext; |
||||
import com.alibaba.excel.enums.HeadKindEnum; |
||||
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; |
||||
import com.alibaba.excel.util.CollectionUtils; |
||||
import com.alibaba.excel.util.WorkBookUtil; |
||||
import com.alibaba.excel.util.WriteHandlerUtils; |
||||
import com.alibaba.excel.write.metadata.holder.WriteHolder; |
||||
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; |
||||
|
||||
import net.sf.cglib.beans.BeanMap; |
||||
|
||||
/** |
||||
* Add the data into excel |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor { |
||||
|
||||
public ExcelWriteAddExecutor(WriteContext writeContext) { |
||||
super(writeContext); |
||||
} |
||||
|
||||
public void add(List data) { |
||||
if (CollectionUtils.isEmpty(data)) { |
||||
return; |
||||
} |
||||
WriteSheetHolder writeSheetHolder = writeContext.writeSheetHolder(); |
||||
int newRowIndex = writeSheetHolder.getNewRowIndexAndStartDoWrite(); |
||||
if (writeSheetHolder.isNew() && !writeSheetHolder.getExcelWriteHeadProperty().hasHead()) { |
||||
newRowIndex += writeContext.currentWriteHolder().relativeHeadRowIndex(); |
||||
} |
||||
// BeanMap is out of order,so use fieldList
|
||||
List<Field> fieldList = new ArrayList<Field>(); |
||||
for (int relativeRowIndex = 0; relativeRowIndex < data.size(); relativeRowIndex++) { |
||||
int n = relativeRowIndex + newRowIndex; |
||||
addOneRowOfDataToExcel(data.get(relativeRowIndex), n, relativeRowIndex, fieldList); |
||||
} |
||||
} |
||||
|
||||
private void addOneRowOfDataToExcel(Object oneRowData, int n, int relativeRowIndex, List<Field> fieldList) { |
||||
if (oneRowData == null) { |
||||
return; |
||||
} |
||||
WriteHandlerUtils.beforeRowCreate(writeContext, n, relativeRowIndex, Boolean.FALSE); |
||||
Row row = WorkBookUtil.createRow(writeContext.writeSheetHolder().getSheet(), n); |
||||
WriteHandlerUtils.afterRowCreate(writeContext, row, relativeRowIndex, Boolean.FALSE); |
||||
if (oneRowData instanceof List) { |
||||
addBasicTypeToExcel((List)oneRowData, row, relativeRowIndex); |
||||
} else { |
||||
addJavaObjectToExcel(oneRowData, row, relativeRowIndex, fieldList); |
||||
} |
||||
WriteHandlerUtils.afterRowDispose(writeContext, row, relativeRowIndex, Boolean.FALSE); |
||||
} |
||||
|
||||
private void addBasicTypeToExcel(List<Object> oneRowData, Row row, int relativeRowIndex) { |
||||
if (CollectionUtils.isEmpty(oneRowData)) { |
||||
return; |
||||
} |
||||
Map<Integer, Head> headMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadMap(); |
||||
int dataIndex = 0; |
||||
int cellIndex = 0; |
||||
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) { |
||||
if (dataIndex >= oneRowData.size()) { |
||||
return; |
||||
} |
||||
cellIndex = entry.getKey(); |
||||
Head head = entry.getValue(); |
||||
doAddBasicTypeToExcel(oneRowData, head, row, relativeRowIndex, dataIndex++, cellIndex); |
||||
} |
||||
// Finish
|
||||
if (dataIndex >= oneRowData.size()) { |
||||
return; |
||||
} |
||||
if (cellIndex != 0) { |
||||
cellIndex++; |
||||
} |
||||
int size = oneRowData.size() - dataIndex; |
||||
for (int i = 0; i < size; i++) { |
||||
doAddBasicTypeToExcel(oneRowData, null, row, relativeRowIndex, dataIndex++, cellIndex++); |
||||
} |
||||
} |
||||
|
||||
private void doAddBasicTypeToExcel(List<Object> oneRowData, Head head, Row row, int relativeRowIndex, int dataIndex, |
||||
int cellIndex) { |
||||
WriteHandlerUtils.beforeCellCreate(writeContext, row, head, cellIndex, relativeRowIndex, Boolean.FALSE); |
||||
Cell cell = WorkBookUtil.createCell(row, cellIndex); |
||||
WriteHandlerUtils.afterCellCreate(writeContext, cell, head, relativeRowIndex, Boolean.FALSE); |
||||
Object value = oneRowData.get(dataIndex); |
||||
CellData cellData = converterAndSet(writeContext.currentWriteHolder(), value == null ? null : value.getClass(), |
||||
cell, value, null); |
||||
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE); |
||||
} |
||||
|
||||
private void addJavaObjectToExcel(Object oneRowData, Row row, int relativeRowIndex, List<Field> fieldList) { |
||||
WriteHolder currentWriteHolder = writeContext.currentWriteHolder(); |
||||
BeanMap beanMap = BeanMap.create(oneRowData); |
||||
Set<String> beanMapHandledSet = new HashSet<String>(); |
||||
int cellIndex = 0; |
||||
// If it's a class it needs to be cast by type
|
||||
if (HeadKindEnum.CLASS.equals(writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadKind())) { |
||||
Map<Integer, Head> headMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadMap(); |
||||
Map<Integer, ExcelContentProperty> contentPropertyMap = |
||||
writeContext.currentWriteHolder().excelWriteHeadProperty().getContentPropertyMap(); |
||||
for (Map.Entry<Integer, ExcelContentProperty> entry : contentPropertyMap.entrySet()) { |
||||
cellIndex = entry.getKey(); |
||||
ExcelContentProperty excelContentProperty = entry.getValue(); |
||||
String name = excelContentProperty.getField().getName(); |
||||
if (!beanMap.containsKey(name)) { |
||||
continue; |
||||
} |
||||
Head head = headMap.get(cellIndex); |
||||
WriteHandlerUtils.beforeCellCreate(writeContext, row, head, cellIndex, relativeRowIndex, Boolean.FALSE); |
||||
Cell cell = WorkBookUtil.createCell(row, cellIndex); |
||||
WriteHandlerUtils.afterCellCreate(writeContext, cell, head, relativeRowIndex, Boolean.FALSE); |
||||
Object value = beanMap.get(name); |
||||
CellData cellData = converterAndSet(currentWriteHolder, excelContentProperty.getField().getType(), cell, |
||||
value, excelContentProperty); |
||||
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE); |
||||
beanMapHandledSet.add(name); |
||||
} |
||||
} |
||||
// Finish
|
||||
if (beanMapHandledSet.size() == beanMap.size()) { |
||||
return; |
||||
} |
||||
if (cellIndex != 0) { |
||||
cellIndex++; |
||||
} |
||||
Map<String, Field> ignoreMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getIgnoreMap(); |
||||
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; |
||||
} |
||||
WriteHandlerUtils.beforeCellCreate(writeContext, row, null, cellIndex, relativeRowIndex, Boolean.FALSE); |
||||
Cell cell = WorkBookUtil.createCell(row, cellIndex++); |
||||
WriteHandlerUtils.afterCellCreate(writeContext, cell, null, relativeRowIndex, Boolean.FALSE); |
||||
CellData cellData = converterAndSet(currentWriteHolder, value.getClass(), cell, value, null); |
||||
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, relativeRowIndex, Boolean.FALSE); |
||||
} |
||||
} |
||||
|
||||
private void initFieldList(Class clazz, List<Field> fieldList) { |
||||
if (!fieldList.isEmpty()) { |
||||
return; |
||||
} |
||||
Class tempClass = clazz; |
||||
while (tempClass != null) { |
||||
if (tempClass != BaseRowModel.class) { |
||||
Collections.addAll(fieldList, tempClass.getDeclaredFields()); |
||||
} |
||||
tempClass = tempClass.getSuperclass(); |
||||
} |
||||
} |
||||
|
||||
} |
@ -0,0 +1,9 @@
|
||||
package com.alibaba.excel.write.executor; |
||||
|
||||
/** |
||||
* Excel write Executor |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public interface ExcelWriteExecutor { |
||||
} |
@ -0,0 +1,377 @@
|
||||
package com.alibaba.excel.write.executor; |
||||
|
||||
import java.util.ArrayList; |
||||
import java.util.Collection; |
||||
import java.util.HashMap; |
||||
import java.util.Iterator; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
import org.apache.poi.ss.usermodel.Cell; |
||||
import org.apache.poi.ss.usermodel.CellStyle; |
||||
import org.apache.poi.ss.usermodel.Row; |
||||
import org.apache.poi.ss.usermodel.Sheet; |
||||
|
||||
import com.alibaba.excel.context.WriteContext; |
||||
import com.alibaba.excel.enums.WriteDirectionEnum; |
||||
import com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum; |
||||
import com.alibaba.excel.exception.ExcelGenerateException; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
import com.alibaba.excel.metadata.Head; |
||||
import com.alibaba.excel.metadata.property.ExcelContentProperty; |
||||
import com.alibaba.excel.util.CollectionUtils; |
||||
import com.alibaba.excel.util.StringUtils; |
||||
import com.alibaba.excel.util.WriteHandlerUtils; |
||||
import com.alibaba.excel.write.metadata.fill.AnalysisCell; |
||||
import com.alibaba.excel.write.metadata.fill.FillConfig; |
||||
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; |
||||
|
||||
import net.sf.cglib.beans.BeanMap; |
||||
|
||||
/** |
||||
* Fill the data into excel |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor { |
||||
|
||||
private static final String ESCAPE_FILL_PREFIX = "\\\\\\{"; |
||||
private static final String ESCAPE_FILL_SUFFIX = "\\\\\\}"; |
||||
private static final String FILL_PREFIX = "{"; |
||||
private static final String FILL_SUFFIX = "}"; |
||||
private static final char IGNORE_CHAR = '\\'; |
||||
private static final String COLLECTION_PREFIX = "."; |
||||
/** |
||||
* Fields to replace in the template |
||||
*/ |
||||
private Map<Integer, List<AnalysisCell>> templateAnalysisCache = new HashMap<Integer, List<AnalysisCell>>(8); |
||||
/** |
||||
* Collection fields to replace in the template |
||||
*/ |
||||
private Map<Integer, List<AnalysisCell>> templateCollectionAnalysisCache = |
||||
new HashMap<Integer, List<AnalysisCell>>(8); |
||||
/** |
||||
* Style cache for collection fields |
||||
*/ |
||||
private Map<Integer, Map<AnalysisCell, CellStyle>> collectionFieldStyleCache = |
||||
new HashMap<Integer, Map<AnalysisCell, CellStyle>>(8); |
||||
/** |
||||
* Last index cache for collection fields |
||||
*/ |
||||
private Map<Integer, Map<AnalysisCell, Integer>> collectionLastIndexCache = |
||||
new HashMap<Integer, Map<AnalysisCell, Integer>>(8); |
||||
|
||||
public ExcelWriteFillExecutor(WriteContext writeContext) { |
||||
super(writeContext); |
||||
} |
||||
|
||||
public void fill(Object data, FillConfig fillConfig) { |
||||
if (fillConfig == null) { |
||||
fillConfig = FillConfig.builder().build(true); |
||||
} |
||||
fillConfig.init(); |
||||
if (data instanceof Collection) { |
||||
List<AnalysisCell> analysisCellList = readTemplateData(templateCollectionAnalysisCache); |
||||
Collection collectionData = (Collection)data; |
||||
if (CollectionUtils.isEmpty(collectionData)) { |
||||
return; |
||||
} |
||||
Iterator iterator = collectionData.iterator(); |
||||
if (WriteDirectionEnum.VERTICAL.equals(fillConfig.getDirection()) && fillConfig.getForceNewRow()) { |
||||
shiftRows(collectionData.size(), analysisCellList); |
||||
} |
||||
while (iterator.hasNext()) { |
||||
doFill(analysisCellList, iterator.next(), fillConfig); |
||||
} |
||||
} else { |
||||
doFill(readTemplateData(templateAnalysisCache), data, fillConfig); |
||||
} |
||||
} |
||||
|
||||
private void shiftRows(int size, List<AnalysisCell> analysisCellList) { |
||||
if (CollectionUtils.isEmpty(analysisCellList)) { |
||||
return; |
||||
} |
||||
int maxRowIndex = 0; |
||||
Integer sheetNo = writeContext.writeSheetHolder().getSheetNo(); |
||||
Map<AnalysisCell, Integer> collectionLastIndexMap = collectionLastIndexCache.get(sheetNo); |
||||
for (AnalysisCell analysisCell : analysisCellList) { |
||||
if (collectionLastIndexMap != null) { |
||||
Integer lastRowIndex = collectionLastIndexMap.get(analysisCell); |
||||
if (lastRowIndex != null) { |
||||
if (lastRowIndex > maxRowIndex) { |
||||
maxRowIndex = lastRowIndex; |
||||
} |
||||
continue; |
||||
} |
||||
} |
||||
if (analysisCell.getRowIndex() > maxRowIndex) { |
||||
maxRowIndex = analysisCell.getRowIndex(); |
||||
} |
||||
} |
||||
Sheet cachedSheet = writeContext.writeSheetHolder().getCachedSheet(); |
||||
int lastRowIndex = cachedSheet.getLastRowNum(); |
||||
if (maxRowIndex >= lastRowIndex) { |
||||
return; |
||||
} |
||||
Sheet sheet = writeContext.writeSheetHolder().getCachedSheet(); |
||||
int number = size; |
||||
if (collectionLastIndexMap == null) { |
||||
number--; |
||||
} |
||||
sheet.shiftRows(maxRowIndex + 1, lastRowIndex, number); |
||||
for (AnalysisCell analysisCell : templateAnalysisCache.get(writeContext.writeSheetHolder().getSheetNo())) { |
||||
if (analysisCell.getRowIndex() > maxRowIndex) { |
||||
analysisCell.setRowIndex(analysisCell.getRowIndex() + number); |
||||
} |
||||
} |
||||
} |
||||
|
||||
private void doFill(List<AnalysisCell> analysisCellList, Object oneRowData, FillConfig fillConfig) { |
||||
Map dataMap; |
||||
if (oneRowData instanceof Map) { |
||||
dataMap = (Map)oneRowData; |
||||
} else { |
||||
dataMap = BeanMap.create(oneRowData); |
||||
} |
||||
WriteSheetHolder writeSheetHolder = writeContext.writeSheetHolder(); |
||||
Map<String, ExcelContentProperty> fieldNameContentPropertyMap = |
||||
writeContext.currentWriteHolder().excelWriteHeadProperty().getFieldNameContentPropertyMap(); |
||||
for (AnalysisCell analysisCell : analysisCellList) { |
||||
Cell cell = getOneCell(analysisCell, fillConfig); |
||||
if (analysisCell.getOnlyOneVariable()) { |
||||
String variable = analysisCell.getVariableList().get(0); |
||||
if (!dataMap.containsKey(variable)) { |
||||
continue; |
||||
} |
||||
Object value = dataMap.get(variable); |
||||
CellData cellData = converterAndSet(writeSheetHolder, value == null ? null : value.getClass(), cell, |
||||
value, fieldNameContentPropertyMap.get(variable)); |
||||
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, null, Boolean.FALSE); |
||||
} else { |
||||
StringBuilder cellValueBuild = new StringBuilder(); |
||||
int index = 0; |
||||
List<CellData> cellDataList = new ArrayList<CellData>(); |
||||
for (String variable : analysisCell.getVariableList()) { |
||||
cellValueBuild.append(analysisCell.getPrepareDataList().get(index++)); |
||||
if (!dataMap.containsKey(variable)) { |
||||
continue; |
||||
} |
||||
Object value = dataMap.get(variable); |
||||
CellData cellData = convert(writeSheetHolder, value == null ? null : value.getClass(), cell, value, |
||||
fieldNameContentPropertyMap.get(variable)); |
||||
cellDataList.add(cellData); |
||||
switch (cellData.getType()) { |
||||
case STRING: |
||||
cellValueBuild.append(cellData.getStringValue()); |
||||
break; |
||||
case BOOLEAN: |
||||
cellValueBuild.append(cellData.getBooleanValue()); |
||||
break; |
||||
case NUMBER: |
||||
cellValueBuild.append(cellData.getNumberValue()); |
||||
break; |
||||
default: |
||||
break; |
||||
} |
||||
} |
||||
cellValueBuild.append(analysisCell.getPrepareDataList().get(index)); |
||||
cell.setCellValue(cellValueBuild.toString()); |
||||
WriteHandlerUtils.afterCellDispose(writeContext, cellDataList, cell, null, null, Boolean.FALSE); |
||||
} |
||||
} |
||||
} |
||||
|
||||
private Cell getOneCell(AnalysisCell analysisCell, FillConfig fillConfig) { |
||||
Sheet cachedSheet = writeContext.writeSheetHolder().getCachedSheet(); |
||||
if (WriteTemplateAnalysisCellTypeEnum.COMMON.equals(analysisCell.getCellType())) { |
||||
return cachedSheet.getRow(analysisCell.getRowIndex()).getCell(analysisCell.getColumnIndex()); |
||||
} |
||||
Integer sheetNo = writeContext.writeSheetHolder().getSheetNo(); |
||||
Sheet sheet = writeContext.writeSheetHolder().getSheet(); |
||||
|
||||
Map<AnalysisCell, Integer> collectionLastIndexMap = collectionLastIndexCache.get(sheetNo); |
||||
if (collectionLastIndexMap == null) { |
||||
collectionLastIndexMap = new HashMap<AnalysisCell, Integer>(16); |
||||
collectionLastIndexCache.put(sheetNo, collectionLastIndexMap); |
||||
} |
||||
boolean isOriginalCell = false; |
||||
Integer lastRowIndex; |
||||
Integer lastColumnIndex; |
||||
switch (fillConfig.getDirection()) { |
||||
case VERTICAL: |
||||
lastRowIndex = collectionLastIndexMap.get(analysisCell); |
||||
if (lastRowIndex == null) { |
||||
lastRowIndex = analysisCell.getRowIndex(); |
||||
collectionLastIndexMap.put(analysisCell, lastRowIndex); |
||||
isOriginalCell = true; |
||||
} else { |
||||
collectionLastIndexMap.put(analysisCell, ++lastRowIndex); |
||||
} |
||||
lastColumnIndex = analysisCell.getColumnIndex(); |
||||
break; |
||||
case HORIZONTAL: |
||||
lastRowIndex = analysisCell.getRowIndex(); |
||||
lastColumnIndex = collectionLastIndexMap.get(analysisCell); |
||||
if (lastColumnIndex == null) { |
||||
lastColumnIndex = analysisCell.getColumnIndex(); |
||||
collectionLastIndexMap.put(analysisCell, lastColumnIndex); |
||||
isOriginalCell = true; |
||||
} else { |
||||
collectionLastIndexMap.put(analysisCell, ++lastColumnIndex); |
||||
} |
||||
break; |
||||
default: |
||||
throw new ExcelGenerateException("The wrong direction."); |
||||
} |
||||
Row row = sheet.getRow(lastRowIndex); |
||||
if (row == null) { |
||||
row = cachedSheet.getRow(lastRowIndex); |
||||
if (row == null) { |
||||
WriteHandlerUtils.beforeRowCreate(writeContext, lastRowIndex, null, Boolean.FALSE); |
||||
if (fillConfig.getForceNewRow()) { |
||||
row = cachedSheet.createRow(lastRowIndex); |
||||
} else { |
||||
row = sheet.createRow(lastRowIndex); |
||||
} |
||||
WriteHandlerUtils.afterRowCreate(writeContext, row, null, Boolean.FALSE); |
||||
} |
||||
} |
||||
Cell cell = row.getCell(lastColumnIndex); |
||||
if (cell == null) { |
||||
WriteHandlerUtils.beforeCellCreate(writeContext, row, null, lastColumnIndex, null, Boolean.FALSE); |
||||
cell = row.createCell(lastColumnIndex); |
||||
WriteHandlerUtils.afterCellCreate(writeContext, cell, null, null, Boolean.FALSE); |
||||
} |
||||
|
||||
Map<AnalysisCell, CellStyle> collectionFieldStyleMap = collectionFieldStyleCache.get(sheetNo); |
||||
if (collectionFieldStyleMap == null) { |
||||
collectionFieldStyleMap = new HashMap<AnalysisCell, CellStyle>(16); |
||||
collectionFieldStyleCache.put(sheetNo, collectionFieldStyleMap); |
||||
} |
||||
if (isOriginalCell) { |
||||
collectionFieldStyleMap.put(analysisCell, cell.getCellStyle()); |
||||
} else { |
||||
CellStyle cellStyle = collectionFieldStyleMap.get(analysisCell); |
||||
if (cellStyle != null) { |
||||
cell.setCellStyle(cellStyle); |
||||
} |
||||
} |
||||
return cell; |
||||
} |
||||
|
||||
private List<AnalysisCell> readTemplateData(Map<Integer, List<AnalysisCell>> analysisCache) { |
||||
Integer sheetNo = writeContext.writeSheetHolder().getSheetNo(); |
||||
List<AnalysisCell> analysisCellList = analysisCache.get(sheetNo); |
||||
if (analysisCellList != null) { |
||||
return analysisCellList; |
||||
} |
||||
Sheet sheet = writeContext.writeSheetHolder().getCachedSheet(); |
||||
analysisCellList = new ArrayList<AnalysisCell>(); |
||||
List<AnalysisCell> collectionAnalysisCellList = new ArrayList<AnalysisCell>(); |
||||
for (int i = 0; i <= sheet.getLastRowNum(); i++) { |
||||
Row row = sheet.getRow(i); |
||||
if (row == null) { |
||||
continue; |
||||
} |
||||
for (int j = 0; j < row.getLastCellNum(); j++) { |
||||
Cell cell = row.getCell(j); |
||||
if (cell == null) { |
||||
continue; |
||||
} |
||||
prepareData(cell.getStringCellValue(), analysisCellList, collectionAnalysisCellList, i, j); |
||||
} |
||||
} |
||||
templateAnalysisCache.put(sheetNo, analysisCellList); |
||||
templateCollectionAnalysisCache.put(sheetNo, collectionAnalysisCellList); |
||||
return analysisCache.get(sheetNo); |
||||
} |
||||
|
||||
private void prepareData(String value, List<AnalysisCell> analysisCellList, |
||||
List<AnalysisCell> collectionAnalysisCellList, int rowIndex, int columnIndex) { |
||||
if (StringUtils.isEmpty(value)) { |
||||
return; |
||||
} |
||||
AnalysisCell analysisCell = null; |
||||
int startIndex = 0; |
||||
int length = value.length(); |
||||
int lastPrepareDataIndex = 0; |
||||
out: |
||||
while (startIndex < length) { |
||||
int prefixIndex = value.indexOf(FILL_PREFIX, startIndex); |
||||
if (prefixIndex < 0) { |
||||
break out; |
||||
} |
||||
if (prefixIndex != 0) { |
||||
char prefixPrefixChar = value.charAt(prefixIndex - 1); |
||||
if (prefixPrefixChar == IGNORE_CHAR) { |
||||
startIndex = prefixIndex + 1; |
||||
continue; |
||||
} |
||||
} |
||||
int suffixIndex = -1; |
||||
while (suffixIndex == -1 && startIndex < length) { |
||||
suffixIndex = value.indexOf(FILL_SUFFIX, startIndex + 1); |
||||
if (suffixIndex < 0) { |
||||
break out; |
||||
} |
||||
startIndex = suffixIndex + 1; |
||||
char prefixSuffixChar = value.charAt(suffixIndex - 1); |
||||
if (prefixSuffixChar == IGNORE_CHAR) { |
||||
suffixIndex = -1; |
||||
} |
||||
} |
||||
if (analysisCell == null) { |
||||
analysisCell = new AnalysisCell(); |
||||
analysisCell.setRowIndex(rowIndex); |
||||
analysisCell.setColumnIndex(columnIndex); |
||||
analysisCell.setOnlyOneVariable(Boolean.TRUE); |
||||
List<String> variableList = new ArrayList<String>(); |
||||
analysisCell.setVariableList(variableList); |
||||
List<String> prepareDataList = new ArrayList<String>(); |
||||
analysisCell.setPrepareDataList(prepareDataList); |
||||
analysisCell.setCellType(WriteTemplateAnalysisCellTypeEnum.COMMON); |
||||
} |
||||
String variable = value.substring(prefixIndex + 1, suffixIndex); |
||||
if (StringUtils.isEmpty(variable)) { |
||||
continue; |
||||
} |
||||
if (variable.startsWith(COLLECTION_PREFIX)) { |
||||
variable = variable.substring(1); |
||||
if (StringUtils.isEmpty(variable)) { |
||||
continue; |
||||
} |
||||
analysisCell.setCellType(WriteTemplateAnalysisCellTypeEnum.COLLECTION); |
||||
} |
||||
analysisCell.getVariableList().add(variable); |
||||
if (lastPrepareDataIndex == prefixIndex) { |
||||
analysisCell.getPrepareDataList().add(StringUtils.EMPTY); |
||||
} else { |
||||
analysisCell.getPrepareDataList() |
||||
.add(convertPrepareData(value.substring(lastPrepareDataIndex, prefixIndex))); |
||||
analysisCell.setOnlyOneVariable(Boolean.FALSE); |
||||
} |
||||
lastPrepareDataIndex = suffixIndex + 1; |
||||
} |
||||
if (analysisCell != null) { |
||||
if (lastPrepareDataIndex == length) { |
||||
analysisCell.getPrepareDataList().add(StringUtils.EMPTY); |
||||
} else { |
||||
analysisCell.getPrepareDataList().add(convertPrepareData(value.substring(lastPrepareDataIndex))); |
||||
analysisCell.setOnlyOneVariable(Boolean.FALSE); |
||||
} |
||||
if (WriteTemplateAnalysisCellTypeEnum.COMMON.equals(analysisCell.getCellType())) { |
||||
analysisCellList.add(analysisCell); |
||||
} else { |
||||
collectionAnalysisCellList.add(analysisCell); |
||||
} |
||||
} |
||||
} |
||||
|
||||
private String convertPrepareData(String prepareData) { |
||||
prepareData = prepareData.replaceAll(ESCAPE_FILL_PREFIX, FILL_PREFIX); |
||||
prepareData = prepareData.replaceAll(ESCAPE_FILL_SUFFIX, FILL_SUFFIX); |
||||
return prepareData; |
||||
} |
||||
|
||||
} |
@ -0,0 +1,89 @@
|
||||
package com.alibaba.excel.write.metadata.fill; |
||||
|
||||
import java.util.List; |
||||
|
||||
import com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum; |
||||
|
||||
/** |
||||
* Read the cells of the template while populating the data. |
||||
* |
||||
* @author Jiaju Zhuang |
||||
**/ |
||||
public class AnalysisCell { |
||||
private int columnIndex; |
||||
private int rowIndex; |
||||
private List<String> variableList; |
||||
private List<String> prepareDataList; |
||||
private Boolean onlyOneVariable; |
||||
private WriteTemplateAnalysisCellTypeEnum cellType; |
||||
|
||||
public int getColumnIndex() { |
||||
return columnIndex; |
||||
} |
||||
|
||||
public void setColumnIndex(int columnIndex) { |
||||
this.columnIndex = columnIndex; |
||||
} |
||||
|
||||
public int getRowIndex() { |
||||
return rowIndex; |
||||
} |
||||
|
||||
public void setRowIndex(int rowIndex) { |
||||
this.rowIndex = rowIndex; |
||||
} |
||||
|
||||
public List<String> getVariableList() { |
||||
return variableList; |
||||
} |
||||
|
||||
public void setVariableList(List<String> variableList) { |
||||
this.variableList = variableList; |
||||
} |
||||
|
||||
public List<String> getPrepareDataList() { |
||||
return prepareDataList; |
||||
} |
||||
|
||||
public void setPrepareDataList(List<String> prepareDataList) { |
||||
this.prepareDataList = prepareDataList; |
||||
} |
||||
|
||||
public Boolean getOnlyOneVariable() { |
||||
return onlyOneVariable; |
||||
} |
||||
|
||||
public void setOnlyOneVariable(Boolean onlyOneVariable) { |
||||
this.onlyOneVariable = onlyOneVariable; |
||||
} |
||||
|
||||
public WriteTemplateAnalysisCellTypeEnum getCellType() { |
||||
return cellType; |
||||
} |
||||
|
||||
public void setCellType(WriteTemplateAnalysisCellTypeEnum cellType) { |
||||
this.cellType = cellType; |
||||
} |
||||
|
||||
@Override |
||||
public boolean equals(Object o) { |
||||
if (this == o) { |
||||
return true; |
||||
} |
||||
if (o == null || getClass() != o.getClass()) { |
||||
return false; |
||||
} |
||||
AnalysisCell that = (AnalysisCell)o; |
||||
if (columnIndex != that.columnIndex) { |
||||
return false; |
||||
} |
||||
return rowIndex == that.rowIndex; |
||||
} |
||||
|
||||
@Override |
||||
public int hashCode() { |
||||
int result = columnIndex; |
||||
result = 31 * result + rowIndex; |
||||
return result; |
||||
} |
||||
} |
@ -0,0 +1,83 @@
|
||||
package com.alibaba.excel.write.metadata.fill; |
||||
|
||||
import com.alibaba.excel.enums.WriteDirectionEnum; |
||||
|
||||
/** |
||||
* Fill config |
||||
* |
||||
* @author Jiaju Zhuang |
||||
**/ |
||||
public class FillConfig { |
||||
private WriteDirectionEnum direction; |
||||
/** |
||||
* Create a new row each time you use the list parameter.The default create if necessary. |
||||
* <p> |
||||
* Warnning:If you use <code>forceNewRow</code> set true, will not be able to use asynchronous write file, simply |
||||
* say the whole file will be stored in memory. |
||||
*/ |
||||
private Boolean forceNewRow; |
||||
private boolean hasInit; |
||||
|
||||
public WriteDirectionEnum getDirection() { |
||||
return direction; |
||||
} |
||||
|
||||
public void setDirection(WriteDirectionEnum direction) { |
||||
this.direction = direction; |
||||
} |
||||
|
||||
public Boolean getForceNewRow() { |
||||
return forceNewRow; |
||||
} |
||||
|
||||
public void setForceNewRow(Boolean forceNewRow) { |
||||
this.forceNewRow = forceNewRow; |
||||
} |
||||
|
||||
public void init() { |
||||
if (hasInit) { |
||||
return; |
||||
} |
||||
if (direction == null) { |
||||
direction = WriteDirectionEnum.VERTICAL; |
||||
} |
||||
if (forceNewRow == null) { |
||||
forceNewRow = Boolean.FALSE; |
||||
} |
||||
hasInit = true; |
||||
} |
||||
|
||||
public static FillConfigBuilder builder() { |
||||
return new FillConfigBuilder(); |
||||
} |
||||
|
||||
public static class FillConfigBuilder { |
||||
private FillConfig fillConfig; |
||||
|
||||
FillConfigBuilder() { |
||||
this.fillConfig = new FillConfig(); |
||||
} |
||||
|
||||
public FillConfigBuilder direction(WriteDirectionEnum direction) { |
||||
fillConfig.setDirection(direction); |
||||
return this; |
||||
} |
||||
|
||||
public FillConfigBuilder forceNewRow(Boolean forceNewRow) { |
||||
fillConfig.setForceNewRow(forceNewRow); |
||||
return this; |
||||
} |
||||
|
||||
public FillConfig build() { |
||||
return build(true); |
||||
} |
||||
|
||||
public FillConfig build(boolean autoInit) { |
||||
if (autoInit) { |
||||
fillConfig.init(); |
||||
} |
||||
return fillConfig; |
||||
} |
||||
|
||||
} |
||||
} |
@ -0,0 +1,21 @@
|
||||
package com.alibaba.easyexcel.test.core.celldata; |
||||
|
||||
import java.util.Date; |
||||
|
||||
import com.alibaba.excel.annotation.ExcelProperty; |
||||
import com.alibaba.excel.annotation.format.DateTimeFormat; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
|
||||
import lombok.Data; |
||||
|
||||
/** |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@Data |
||||
public class CellDataData { |
||||
@DateTimeFormat("yyyy年MM月dd日") |
||||
private CellData<Date> date; |
||||
private CellData<Integer> integer1; |
||||
private Integer integer2; |
||||
private CellData formulaValue; |
||||
} |
@ -0,0 +1,37 @@
|
||||
package com.alibaba.easyexcel.test.core.celldata; |
||||
|
||||
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 Jiaju Zhuang |
||||
*/ |
||||
public class CellDataDataListener extends AnalysisEventListener<CellDataData> { |
||||
private static final Logger LOGGER = LoggerFactory.getLogger(CellDataDataListener.class); |
||||
List<CellDataData> list = new ArrayList<CellDataData>(); |
||||
|
||||
@Override |
||||
public void invoke(CellDataData data, AnalysisContext context) { |
||||
list.add(data); |
||||
} |
||||
|
||||
@Override |
||||
public void doAfterAllAnalysed(AnalysisContext context) { |
||||
Assert.assertEquals(list.size(), 1); |
||||
CellDataData cellDataData = list.get(0); |
||||
|
||||
Assert.assertEquals(cellDataData.getDate().getStringValue(), "2020年01月01日"); |
||||
Assert.assertEquals((long)cellDataData.getInteger1().getData(), 2L); |
||||
Assert.assertEquals((long)cellDataData.getInteger2(), 2L); |
||||
Assert.assertEquals(cellDataData.getFormulaValue().getFormulaValue(), "B2+C2"); |
||||
LOGGER.debug("First row:{}", JSON.toJSONString(list.get(0))); |
||||
} |
||||
} |
@ -0,0 +1,71 @@
|
||||
package com.alibaba.easyexcel.test.core.celldata; |
||||
|
||||
import java.io.File; |
||||
import java.math.BigDecimal; |
||||
import java.util.ArrayList; |
||||
import java.util.Date; |
||||
import java.util.List; |
||||
|
||||
import org.junit.Assert; |
||||
import org.junit.BeforeClass; |
||||
import org.junit.FixMethodOrder; |
||||
import org.junit.Test; |
||||
import org.junit.runners.MethodSorters; |
||||
|
||||
import com.alibaba.easyexcel.test.core.simple.SimpleData; |
||||
import com.alibaba.easyexcel.test.core.simple.SimpleDataListener; |
||||
import com.alibaba.easyexcel.test.core.simple.SimpleDataSheetNameListener; |
||||
import com.alibaba.easyexcel.test.util.TestFileUtil; |
||||
import com.alibaba.excel.EasyExcel; |
||||
import com.alibaba.excel.enums.CellDataTypeEnum; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
import com.alibaba.excel.util.DateUtils; |
||||
|
||||
/** |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@FixMethodOrder(MethodSorters.NAME_ASCENDING) |
||||
public class CellDataDataTest { |
||||
|
||||
private static File file07; |
||||
private static File file03; |
||||
|
||||
@BeforeClass |
||||
public static void init() { |
||||
file07 = TestFileUtil.createNewFile("cellData07.xlsx"); |
||||
file03 = TestFileUtil.createNewFile("cellData03.xls"); |
||||
} |
||||
|
||||
@Test |
||||
public void t01ReadAndWrite07() throws Exception { |
||||
readAndWrite(file07); |
||||
} |
||||
|
||||
@Test |
||||
public void t02ReadAndWrite03() throws Exception { |
||||
readAndWrite(file03); |
||||
} |
||||
|
||||
private void readAndWrite(File file) throws Exception { |
||||
EasyExcel.write(file, CellDataData.class).sheet().doWrite(data()); |
||||
EasyExcel.read(file, CellDataData.class, new CellDataDataListener()).sheet().doRead(); |
||||
} |
||||
|
||||
private List<CellDataData> data() throws Exception { |
||||
List<CellDataData> list = new ArrayList<CellDataData>(); |
||||
CellDataData cellDataData = new CellDataData(); |
||||
cellDataData.setDate(new CellData<Date>(DateUtils.parseDate("2020-01-01 01:01:01"))); |
||||
CellData<Integer> integer1 = new CellData<Integer>(); |
||||
integer1.setType(CellDataTypeEnum.NUMBER); |
||||
integer1.setNumberValue(BigDecimal.valueOf(2L)); |
||||
cellDataData.setInteger1(integer1); |
||||
cellDataData.setInteger2(2); |
||||
CellData formulaValue = new CellData(); |
||||
formulaValue.setFormula(Boolean.TRUE); |
||||
formulaValue.setFormulaValue("B2+C2"); |
||||
cellDataData.setFormulaValue(formulaValue); |
||||
list.add(cellDataData); |
||||
return list; |
||||
} |
||||
} |
@ -0,0 +1,14 @@
|
||||
package com.alibaba.easyexcel.test.core.encrypt; |
||||
|
||||
import com.alibaba.excel.annotation.ExcelProperty; |
||||
|
||||
import lombok.Data; |
||||
|
||||
/** |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@Data |
||||
public class EncryptData { |
||||
@ExcelProperty("姓名") |
||||
private String name; |
||||
} |
@ -0,0 +1,35 @@
|
||||
package com.alibaba.easyexcel.test.core.encrypt; |
||||
|
||||
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 Jiaju Zhuang |
||||
*/ |
||||
public class EncryptDataListener extends AnalysisEventListener<EncryptData> { |
||||
private static final Logger LOGGER = LoggerFactory.getLogger(EncryptDataListener.class); |
||||
List<EncryptData> list = new ArrayList<EncryptData>(); |
||||
|
||||
@Override |
||||
public void invoke(EncryptData 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))); |
||||
} |
||||
} |
@ -0,0 +1,88 @@
|
||||
package com.alibaba.easyexcel.test.core.encrypt; |
||||
|
||||
import java.io.File; |
||||
import java.io.FileInputStream; |
||||
import java.io.FileOutputStream; |
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
|
||||
import org.junit.Assert; |
||||
import org.junit.BeforeClass; |
||||
import org.junit.FixMethodOrder; |
||||
import org.junit.Test; |
||||
import org.junit.runners.MethodSorters; |
||||
|
||||
import com.alibaba.easyexcel.test.core.simple.SimpleData; |
||||
import com.alibaba.easyexcel.test.core.simple.SimpleDataListener; |
||||
import com.alibaba.easyexcel.test.core.simple.SimpleDataSheetNameListener; |
||||
import com.alibaba.easyexcel.test.util.TestFileUtil; |
||||
import com.alibaba.excel.EasyExcel; |
||||
import com.alibaba.excel.support.ExcelTypeEnum; |
||||
import com.alibaba.excel.util.FileUtils; |
||||
|
||||
/** |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@FixMethodOrder(MethodSorters.NAME_ASCENDING) |
||||
public class EncryptDataTest { |
||||
|
||||
private static File file07; |
||||
private static File file03; |
||||
private static File file07OutputStream; |
||||
private static File file03OutputStream; |
||||
|
||||
@BeforeClass |
||||
public static void init() { |
||||
file07 = TestFileUtil.createNewFile("encrypt07.xlsx"); |
||||
file03 = TestFileUtil.createNewFile("encrypt03.xls"); |
||||
file07OutputStream = TestFileUtil.createNewFile("encryptOutputStream07.xlsx"); |
||||
file03OutputStream = TestFileUtil.createNewFile("encryptOutputStream03.xls"); |
||||
} |
||||
|
||||
@Test |
||||
public void t01ReadAndWrite07() { |
||||
readAndWrite(file07); |
||||
} |
||||
|
||||
@Test |
||||
public void t02ReadAndWrite03() { |
||||
readAndWrite(file03); |
||||
} |
||||
|
||||
@Test |
||||
public void t01ReadAndWriteStream07() throws Exception { |
||||
readAndWriteStream(file07OutputStream, ExcelTypeEnum.XLSX); |
||||
} |
||||
|
||||
@Test |
||||
public void t02ReadAndWriteStream03() throws Exception { |
||||
readAndWriteStream(file03OutputStream, ExcelTypeEnum.XLS); |
||||
} |
||||
|
||||
private void readAndWrite(File file) { |
||||
EasyExcel.write(file, EncryptData.class).password("123456").sheet().doWrite(data()); |
||||
EasyExcel.read(file, EncryptData.class, new EncryptDataListener()).password("123456").sheet().doRead(); |
||||
} |
||||
|
||||
private void readAndWriteStream(File file, ExcelTypeEnum excelType) throws Exception { |
||||
FileOutputStream fileOutputStream = new FileOutputStream(file); |
||||
EasyExcel.write(fileOutputStream, EncryptData.class).password("123456").excelType(excelType).sheet() |
||||
.doWrite(data()); |
||||
fileOutputStream.close(); |
||||
|
||||
FileInputStream fileInputStream = new FileInputStream(file); |
||||
EasyExcel.read(fileInputStream, EncryptData.class, new EncryptDataListener()).password("123456") |
||||
.excelType(excelType).sheet().doRead(); |
||||
} |
||||
|
||||
private List<SimpleData> data() { |
||||
List<SimpleData> list = new ArrayList<SimpleData>(); |
||||
for (int i = 0; i < 10; i++) { |
||||
SimpleData simpleData = new SimpleData(); |
||||
simpleData.setName("姓名" + i); |
||||
list.add(simpleData); |
||||
} |
||||
return list; |
||||
} |
||||
} |
@ -0,0 +1,18 @@
|
||||
package com.alibaba.easyexcel.test.core.fill; |
||||
|
||||
import com.alibaba.excel.annotation.ExcelProperty; |
||||
import com.alibaba.excel.annotation.format.NumberFormat; |
||||
import com.alibaba.excel.converters.doubleconverter.DoubleStringConverter; |
||||
|
||||
import lombok.Data; |
||||
|
||||
/** |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@Data |
||||
public class FillData { |
||||
private String name; |
||||
@NumberFormat("#") |
||||
@ExcelProperty(converter = DoubleStringConverter.class) |
||||
private double number; |
||||
} |
@ -0,0 +1,157 @@
|
||||
package com.alibaba.easyexcel.test.core.fill; |
||||
|
||||
import java.io.File; |
||||
import java.util.ArrayList; |
||||
import java.util.HashMap; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
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.Assert; |
||||
import org.junit.BeforeClass; |
||||
import org.junit.FixMethodOrder; |
||||
import org.junit.Test; |
||||
import org.junit.runners.MethodSorters; |
||||
|
||||
import com.alibaba.easyexcel.test.core.style.StyleData; |
||||
import com.alibaba.easyexcel.test.core.style.StyleDataListener; |
||||
import com.alibaba.easyexcel.test.util.TestFileUtil; |
||||
import com.alibaba.excel.EasyExcel; |
||||
import com.alibaba.excel.ExcelWriter; |
||||
import com.alibaba.excel.enums.WriteDirectionEnum; |
||||
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.WriteSheet; |
||||
import com.alibaba.excel.write.metadata.fill.FillConfig; |
||||
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; |
||||
|
||||
/** |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@FixMethodOrder(MethodSorters.NAME_ASCENDING) |
||||
public class FillDataTest { |
||||
|
||||
private static File file07; |
||||
private static File file03; |
||||
private static File simpleTemplate07; |
||||
private static File simpleTemplate03; |
||||
private static File fileComplex07; |
||||
private static File complexFillTemplate07; |
||||
private static File fileComplex03; |
||||
private static File complexFillTemplate03; |
||||
private static File fileHorizontal07; |
||||
private static File horizontalFillTemplate07; |
||||
private static File fileHorizontal03; |
||||
private static File horizontalFillTemplate03; |
||||
|
||||
@BeforeClass |
||||
public static void init() { |
||||
file07 = TestFileUtil.createNewFile("fill07.xlsx"); |
||||
file03 = TestFileUtil.createNewFile("fill03.xls"); |
||||
simpleTemplate07 = TestFileUtil.readFile("fill" + File.separator + "simple.xlsx"); |
||||
simpleTemplate03 = TestFileUtil.readFile("fill" + File.separator + "simple.xls"); |
||||
fileComplex07 = TestFileUtil.createNewFile("fillComplex07.xlsx"); |
||||
complexFillTemplate07 = TestFileUtil.readFile("fill" + File.separator + "complex.xlsx"); |
||||
fileComplex03 = TestFileUtil.createNewFile("fillComplex03.xls"); |
||||
complexFillTemplate03 = TestFileUtil.readFile("fill" + File.separator + "complex.xls"); |
||||
fileHorizontal07 = TestFileUtil.createNewFile("fillHorizontal07.xlsx"); |
||||
horizontalFillTemplate07 = TestFileUtil.readFile("fill" + File.separator + "horizontal.xlsx"); |
||||
fileHorizontal03 = TestFileUtil.createNewFile("fillHorizontal03.xls"); |
||||
horizontalFillTemplate03 = TestFileUtil.readFile("fill" + File.separator + "horizontal.xls"); |
||||
} |
||||
|
||||
@Test |
||||
public void t01Fill07() { |
||||
fill(file07, simpleTemplate07); |
||||
} |
||||
|
||||
@Test |
||||
public void t02Fill03() { |
||||
fill(file03, simpleTemplate03); |
||||
} |
||||
|
||||
@Test |
||||
public void t03ComplexFill07() { |
||||
complexFill(fileComplex07, complexFillTemplate07); |
||||
} |
||||
|
||||
@Test |
||||
public void t04ComplexFill03() { |
||||
complexFill(fileComplex03, complexFillTemplate03); |
||||
} |
||||
|
||||
@Test |
||||
public void t05HorizontalFill07() { |
||||
horizontalFill(fileHorizontal07, horizontalFillTemplate07); |
||||
} |
||||
|
||||
@Test |
||||
public void t06HorizontalFill03() { |
||||
horizontalFill(fileHorizontal03, horizontalFillTemplate03); |
||||
} |
||||
|
||||
private void horizontalFill(File file, File template) { |
||||
ExcelWriter excelWriter = EasyExcel.write(file).withTemplate(template).build(); |
||||
WriteSheet writeSheet = EasyExcel.writerSheet().build(); |
||||
FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build(); |
||||
excelWriter.fill(data(), fillConfig, writeSheet); |
||||
excelWriter.fill(data(), fillConfig, writeSheet); |
||||
Map<String, Object> map = new HashMap<String, Object>(); |
||||
map.put("date", "2019年10月9日13:28:28"); |
||||
excelWriter.fill(map, writeSheet); |
||||
excelWriter.finish(); |
||||
|
||||
List<Object> list = EasyExcel.read(file).sheet().headRowNumber(0).doReadSync(); |
||||
Assert.assertEquals(list.size(), 5L); |
||||
Map<String, String> map0 = (Map<String, String>)list.get(0); |
||||
Assert.assertEquals("张三", map0.get(2)); |
||||
} |
||||
|
||||
private void complexFill(File file, File template) { |
||||
ExcelWriter excelWriter = EasyExcel.write(file).withTemplate(template).build(); |
||||
WriteSheet writeSheet = EasyExcel.writerSheet().build(); |
||||
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build(); |
||||
excelWriter.fill(data(), fillConfig, writeSheet); |
||||
excelWriter.fill(data(), fillConfig, writeSheet); |
||||
Map<String, Object> map = new HashMap<String, Object>(); |
||||
map.put("date", "2019年10月9日13:28:28"); |
||||
map.put("total", 1000); |
||||
excelWriter.fill(map, writeSheet); |
||||
excelWriter.finish(); |
||||
List<Object> list = EasyExcel.read(file).sheet().headRowNumber(3).doReadSync(); |
||||
Assert.assertEquals(list.size(), 21L); |
||||
Map<String, String> map19 = (Map<String, String>)list.get(19); |
||||
Assert.assertEquals("张三", map19.get(0)); |
||||
} |
||||
|
||||
private void fill(File file, File template) { |
||||
FillData fillData = new FillData(); |
||||
fillData.setName("张三"); |
||||
fillData.setNumber(5.2); |
||||
EasyExcel.write(file, FillData.class).withTemplate(template).sheet().doFill(fillData); |
||||
} |
||||
|
||||
private List<FillData> data() { |
||||
List<FillData> list = new ArrayList<FillData>(); |
||||
for (int i = 0; i < 10; i++) { |
||||
FillData fillData = new FillData(); |
||||
list.add(fillData); |
||||
fillData.setName("张三"); |
||||
fillData.setNumber(5.2); |
||||
} |
||||
return list; |
||||
} |
||||
|
||||
} |
@ -0,0 +1,12 @@
|
||||
package com.alibaba.easyexcel.test.demo.fill; |
||||
|
||||
import lombok.Data; |
||||
|
||||
/** |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@Data |
||||
public class FillData { |
||||
private String name; |
||||
private double number; |
||||
} |
@ -0,0 +1,181 @@
|
||||
package com.alibaba.easyexcel.test.demo.fill; |
||||
|
||||
import java.io.File; |
||||
import java.util.ArrayList; |
||||
import java.util.HashMap; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
import org.junit.Ignore; |
||||
import org.junit.Test; |
||||
|
||||
import com.alibaba.easyexcel.test.util.TestFileUtil; |
||||
import com.alibaba.excel.EasyExcel; |
||||
import com.alibaba.excel.ExcelWriter; |
||||
import com.alibaba.excel.enums.WriteDirectionEnum; |
||||
import com.alibaba.excel.write.metadata.WriteSheet; |
||||
import com.alibaba.excel.write.metadata.fill.FillConfig; |
||||
|
||||
/** |
||||
* 写的填充写法 |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
@Ignore |
||||
public class FillTest { |
||||
/** |
||||
* 最简单的填充 |
||||
*/ |
||||
@Test |
||||
public void simpleFill() { |
||||
// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
|
||||
String templateFileName = |
||||
TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "simple.xlsx"; |
||||
|
||||
// 方案1 根据对象填充
|
||||
String fileName = TestFileUtil.getPath() + "simpleFill" + System.currentTimeMillis() + ".xlsx"; |
||||
// 这里 会填充到第一个sheet, 然后文件流会自动关闭
|
||||
FillData fillData = new FillData(); |
||||
fillData.setName("张三"); |
||||
fillData.setNumber(5.2); |
||||
EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(fillData); |
||||
|
||||
// 方案2 根据Map填充
|
||||
fileName = TestFileUtil.getPath() + "simpleFill" + System.currentTimeMillis() + ".xlsx"; |
||||
// 这里 会填充到第一个sheet, 然后文件流会自动关闭
|
||||
Map<String, Object> map = new HashMap<String, Object>(); |
||||
map.put("name", "张三"); |
||||
map.put("number", 5.2); |
||||
EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(map); |
||||
} |
||||
|
||||
/** |
||||
* 填充列表 |
||||
*/ |
||||
@Test |
||||
public void listFill() { |
||||
// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
|
||||
// 填充list 的时候还要注意 模板中{.} 多了个点 表示list
|
||||
String templateFileName = |
||||
TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "list.xlsx"; |
||||
|
||||
// 方案1 一下子全部放到内存里面 并填充
|
||||
String fileName = TestFileUtil.getPath() + "listFill" + System.currentTimeMillis() + ".xlsx"; |
||||
// 这里 会填充到第一个sheet, 然后文件流会自动关闭
|
||||
EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(data()); |
||||
|
||||
// 方案2 分多次 填充 会使用文件缓存(省内存)
|
||||
fileName = TestFileUtil.getPath() + "listFill" + System.currentTimeMillis() + ".xlsx"; |
||||
ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build(); |
||||
WriteSheet writeSheet = EasyExcel.writerSheet().build(); |
||||
excelWriter.fill(data(), writeSheet); |
||||
excelWriter.fill(data(), writeSheet); |
||||
// 千万别忘记关闭流
|
||||
excelWriter.finish(); |
||||
} |
||||
|
||||
/** |
||||
* 复杂的填充 |
||||
*/ |
||||
@Test |
||||
public void complexFill() { |
||||
// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
|
||||
// {} 代表普通变量 {.} 代表是list的变量
|
||||
String templateFileName = |
||||
TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "complex.xlsx"; |
||||
|
||||
String fileName = TestFileUtil.getPath() + "complexFill" + System.currentTimeMillis() + ".xlsx"; |
||||
ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build(); |
||||
WriteSheet writeSheet = EasyExcel.writerSheet().build(); |
||||
// 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行,然后下面的数据往后移动。默认 是false,会直接使用下一行,如果没有则创建。
|
||||
// forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了,所以慎用
|
||||
// 简单的说 如果你的模板有list,且list不是最后一行,下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
|
||||
// 如果数据量大 list不是最后一行 参照下一个
|
||||
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build(); |
||||
excelWriter.fill(data(), fillConfig, writeSheet); |
||||
excelWriter.fill(data(), fillConfig, writeSheet); |
||||
Map<String, Object> map = new HashMap<String, Object>(); |
||||
map.put("date", "2019年10月9日13:28:28"); |
||||
map.put("total", 1000); |
||||
excelWriter.fill(map, writeSheet); |
||||
excelWriter.finish(); |
||||
} |
||||
|
||||
/** |
||||
* 数据量大的复杂填充 |
||||
* <p> |
||||
* 这里的解决方案是 确保模板list为最后一行,然后再拼接table.还有03版没救,只能刚正面加内存。 |
||||
*/ |
||||
@Test |
||||
public void complexFillWithTable() { |
||||
// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
|
||||
// {} 代表普通变量 {.} 代表是list的变量
|
||||
// 这里模板 删除了list以后的数据,也就是统计的这一行
|
||||
String templateFileName = |
||||
TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "complexFillWithTable.xlsx"; |
||||
|
||||
String fileName = TestFileUtil.getPath() + "complexFillWithTable" + System.currentTimeMillis() + ".xlsx"; |
||||
ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build(); |
||||
WriteSheet writeSheet = EasyExcel.writerSheet().build(); |
||||
// 直接写入数据
|
||||
excelWriter.fill(data(), writeSheet); |
||||
excelWriter.fill(data(), writeSheet); |
||||
|
||||
// 写入list之前的数据
|
||||
Map<String, Object> map = new HashMap<String, Object>(); |
||||
map.put("date", "2019年10月9日13:28:28"); |
||||
excelWriter.fill(map, writeSheet); |
||||
|
||||
// list 后面还有个统计 想办法手动写入
|
||||
// 这里偷懒直接用list 也可以用对象
|
||||
List<List<String>> totalListList = new ArrayList<List<String>>(); |
||||
List<String> totalList = new ArrayList<String>(); |
||||
totalListList.add(totalList); |
||||
totalList.add(null); |
||||
totalList.add(null); |
||||
totalList.add(null); |
||||
// 第四列
|
||||
totalList.add("统计:1000"); |
||||
// 这里是write 别和fill 搞错了
|
||||
excelWriter.write(totalListList, writeSheet); |
||||
excelWriter.finish(); |
||||
// 总体上写法比较复杂 但是也没有想到好的版本 异步的去写入excel 不支持行的删除和移动,也不支持备注这种的写入,所以也排除了可以
|
||||
// 新建一个 然后一点点复制过来的方案,最后导致list需要新增行的时候,后面的列的数据没法后移,后续会继续想想解决方案
|
||||
} |
||||
|
||||
/** |
||||
* 横向的填充 |
||||
*/ |
||||
@Test |
||||
public void horizontalFill() { |
||||
// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
|
||||
// {} 代表普通变量 {.} 代表是list的变量
|
||||
String templateFileName = |
||||
TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "horizontal.xlsx"; |
||||
|
||||
String fileName = TestFileUtil.getPath() + "horizontalFill" + System.currentTimeMillis() + ".xlsx"; |
||||
ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build(); |
||||
WriteSheet writeSheet = EasyExcel.writerSheet().build(); |
||||
FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build(); |
||||
excelWriter.fill(data(), fillConfig, writeSheet); |
||||
excelWriter.fill(data(), fillConfig, writeSheet); |
||||
|
||||
Map<String, Object> map = new HashMap<String, Object>(); |
||||
map.put("date", "2019年10月9日13:28:28"); |
||||
excelWriter.fill(map, writeSheet); |
||||
|
||||
// 别忘记关闭流
|
||||
excelWriter.finish(); |
||||
} |
||||
|
||||
private List<FillData> data() { |
||||
List<FillData> list = new ArrayList<FillData>(); |
||||
for (int i = 0; i < 10; i++) { |
||||
FillData fillData = new FillData(); |
||||
list.add(fillData); |
||||
fillData.setName("张三"); |
||||
fillData.setNumber(5.2); |
||||
} |
||||
return list; |
||||
} |
||||
} |
@ -0,0 +1,50 @@
|
||||
package com.alibaba.easyexcel.test.demo.read; |
||||
|
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
import org.slf4j.Logger; |
||||
import org.slf4j.LoggerFactory; |
||||
|
||||
import com.alibaba.excel.context.AnalysisContext; |
||||
import com.alibaba.excel.event.AnalysisEventListener; |
||||
import com.alibaba.excel.metadata.CellData; |
||||
import com.alibaba.fastjson.JSON; |
||||
|
||||
/** |
||||
* 读取头 |
||||
* |
||||
* @author Jiaju Zhuang |
||||
*/ |
||||
public class CellDataDemoHeadDataListener extends AnalysisEventListener<CellDataReadDemoData> { |
||||
private static final Logger LOGGER = LoggerFactory.getLogger(CellDataDemoHeadDataListener.class); |
||||
/** |
||||
* 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收 |
||||
*/ |
||||
private static final int BATCH_COUNT = 5; |
||||
List<CellDataReadDemoData> list = new ArrayList<CellDataReadDemoData>(); |
||||
|
||||
@Override |
||||
public void invoke(CellDataReadDemoData data, AnalysisContext context) { |
||||
LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data)); |
||||
if (list.size() >= BATCH_COUNT) { |
||||
saveData(); |
||||
list.clear(); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void doAfterAllAnalysed(AnalysisContext context) { |
||||
saveData(); |
||||
LOGGER.info("所有数据解析完成!"); |
||||
} |
||||
|
||||
/** |
||||
* 加上存储数据库 |
||||
*/ |
||||
private void saveData() { |
||||
LOGGER.info("{}条数据,开始存储数据库!", list.size()); |
||||
LOGGER.info("存储数据库成功!"); |
||||
} |
||||
} |