EasyExcel自定义参数的读取导出
1、导出
ExcelWriterBuilder excelWriterBuilder = new ExcelWriterBuilder();
excelWriterBuilder.registerWriteHandler(new SheetWriteHandler() {
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
Workbook workbook = writeWorkbookHolder.getWorkbook();
for (Map.Entry<String, String> entry : extraProp.entrySet()) {
if (workbook instanceof XSSFWorkbook){
POIXMLProperties.CustomProperties customProperties = ((XSSFWorkbook) workbook).getProperties().getCustomProperties();
if (ExcelUtils.hasNoProperty(customProperties, entry.getKey())){
customProperties.addProperty(entry.getKey(), entry.getValue());
}
} else if (workbook instanceof SXSSFWorkbook){
POIXMLProperties.CustomProperties customProperties = ((SXSSFWorkbook) workbook).getXSSFWorkbook().getProperties().getCustomProperties();
if (ExcelUtils.hasNoProperty(customProperties, entry.getKey())) {
customProperties.addProperty(entry.getKey(), entry.getValue());
}
} else if (workbook instanceof HSSFWorkbook){
HSSFWorkbook hssfWorkbook = (HSSFWorkbook) workbook;
hssfWorkbook.createInformationProperties();
DocumentSummaryInformation documentSummaryInformation = hssfWorkbook.getDocumentSummaryInformation();
CustomProperties customProperties = documentSummaryInformation.getCustomProperties();
if (Objects.isNull(customProperties)){
customProperties = new CustomProperties();
}
if (!ExcelUtils.hasProperty(customProperties, entry.getKey())) {
customProperties.put(entry.getKey(), entry.getValue());
documentSummaryInformation.setCustomProperties(customProperties);
}
}
}
}
});
2、读取
Map<String, Object> extraProp = new HashMap<>();
try {
ReadWorkbookHolder readWorkbookHolder = context.readWorkbookHolder();
if (readWorkbookHolder instanceof XlsxReadWorkbookHolder) {
OPCPackage opcPackage = ((XlsxReadWorkbookHolder) readWorkbookHolder).getOpcPackage();
POIXMLProperties poiProperties = new POIXMLProperties(opcPackage);
POIXMLProperties.CustomProperties customProperties = poiProperties.getCustomProperties();
List<CTProperty> propertyList = customProperties.getUnderlyingProperties().getPropertyList();
for (CTProperty property : propertyList) {
extraProp.put(property.getName(), property.getLpwstr());
}
} else if (readWorkbookHolder instanceof XlsReadWorkbookHolder){
DocumentSummaryInformation documentSummaryInformation = ((XlsReadWorkbookHolder) readWorkbookHolder).getHssfWorkbook().getDocumentSummaryInformation();
CustomProperties customProperties = documentSummaryInformation.getCustomProperties();
List<CustomProperty> propertyList = customProperties.properties();
for (CustomProperty property : propertyList) {
extraProp.put(property.getName(), property.getValue());
}
}
} catch (XmlException | OpenXML4JException | IOException e) {
throw new RuntimeException("解析Excel额外属性异常");
}