Browse Source

修改加密异常

pull/2074/head
Jiaju Zhuang 4 years ago
parent
commit
d0a55912ca
  1. 38
      src/main/java/com/alibaba/excel/context/WriteContextImpl.java
  2. 9
      src/main/java/com/alibaba/excel/metadata/NullObject.java
  3. 52
      src/main/java/com/alibaba/excel/util/FieldUtils.java
  4. 2
      src/main/java/com/alibaba/excel/util/MapUtils.java
  5. 11
      src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java
  6. 5
      src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java
  7. 2
      src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataTest.java
  8. 79
      src/test/java/com/alibaba/easyexcel/test/temp/poi/PoiEncryptTest.java

38
src/main/java/com/alibaba/excel/context/WriteContextImpl.java

@ -50,7 +50,7 @@ import org.slf4j.LoggerFactory;
public class WriteContextImpl implements WriteContext { public class WriteContextImpl implements WriteContext {
private static final Logger LOGGER = LoggerFactory.getLogger(WriteContextImpl.class); private static final Logger LOGGER = LoggerFactory.getLogger(WriteContextImpl.class);
private static final String NO_SHEETS="no sheets"; private static final String NO_SHEETS = "no sheets";
/** /**
* The Workbook currently written * The Workbook currently written
@ -248,7 +248,8 @@ public class WriteContextImpl implements WriteContext {
Cell cell = row.createCell(columnIndex); Cell cell = row.createCell(columnIndex);
WriteHandlerUtils.afterCellCreate(this, cell, head, relativeRowIndex, Boolean.TRUE); WriteHandlerUtils.afterCellCreate(this, cell, head, relativeRowIndex, Boolean.TRUE);
cell.setCellValue(head.getHeadNameList().get(relativeRowIndex)); cell.setCellValue(head.getHeadNameList().get(relativeRowIndex));
WriteHandlerUtils.afterCellDispose(this, (WriteCellData<?>) null, cell, head, relativeRowIndex, Boolean.TRUE); WriteHandlerUtils.afterCellDispose(this, (WriteCellData<?>)null, cell, head, relativeRowIndex,
Boolean.TRUE);
} }
} }
@ -351,7 +352,7 @@ public class WriteContextImpl implements WriteContext {
try { try {
Workbook workbook = writeWorkbookHolder.getWorkbook(); Workbook workbook = writeWorkbookHolder.getWorkbook();
if (workbook instanceof SXSSFWorkbook) { if (workbook instanceof SXSSFWorkbook) {
((SXSSFWorkbook) workbook).dispose(); ((SXSSFWorkbook)workbook).dispose();
} }
} catch (Throwable t) { } catch (Throwable t) {
throwable = t; throwable = t;
@ -446,14 +447,9 @@ public class WriteContextImpl implements WriteContext {
throw e; throw e;
} }
} }
POIFSFileSystem fileSystem = null; try (POIFSFileSystem fileSystem = openFileSystemAndEncrypt(tempXlsx)) {
try {
fileSystem = openFileSystemAndEncrypt(tempXlsx);
fileSystem.writeFilesystem(writeWorkbookHolder.getOutputStream()); fileSystem.writeFilesystem(writeWorkbookHolder.getOutputStream());
} finally { } finally {
if (fileSystem != null) {
fileSystem.close();
}
if (!tempXlsx.delete()) { if (!tempXlsx.delete()) {
throw new ExcelGenerateException("Can not delete temp File!"); throw new ExcelGenerateException("Can not delete temp File!");
} }
@ -472,19 +468,9 @@ public class WriteContextImpl implements WriteContext {
if (writeWorkbookHolder.getFile() == null) { if (writeWorkbookHolder.getFile() == null) {
return; return;
} }
FileOutputStream fileOutputStream = null; try (POIFSFileSystem fileSystem = openFileSystemAndEncrypt(writeWorkbookHolder.getFile());
POIFSFileSystem fileSystem = null; FileOutputStream fileOutputStream = new FileOutputStream(writeWorkbookHolder.getFile())) {
try {
fileSystem = openFileSystemAndEncrypt(writeWorkbookHolder.getFile());
fileOutputStream = new FileOutputStream(writeWorkbookHolder.getFile());
fileSystem.writeFilesystem(fileOutputStream); fileSystem.writeFilesystem(fileOutputStream);
} finally {
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (fileSystem != null) {
fileSystem.close();
}
} }
} }
@ -492,15 +478,9 @@ public class WriteContextImpl implements WriteContext {
POIFSFileSystem fileSystem = new POIFSFileSystem(); POIFSFileSystem fileSystem = new POIFSFileSystem();
Encryptor encryptor = new EncryptionInfo(EncryptionMode.standard).getEncryptor(); Encryptor encryptor = new EncryptionInfo(EncryptionMode.standard).getEncryptor();
encryptor.confirmPassword(writeWorkbookHolder.getPassword()); encryptor.confirmPassword(writeWorkbookHolder.getPassword());
OPCPackage opcPackage = null; try (OPCPackage opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE);
try { OutputStream outputStream = encryptor.getDataStream(fileSystem)) {
opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE);
OutputStream outputStream = encryptor.getDataStream(fileSystem);
opcPackage.save(outputStream); opcPackage.save(outputStream);
} finally {
if (opcPackage != null) {
opcPackage.close();
}
} }
return fileSystem; return fileSystem;
} }

9
src/main/java/com/alibaba/excel/metadata/NullObject.java

@ -0,0 +1,9 @@
package com.alibaba.excel.metadata;
/**
* Null object.
*
* @author Jiaju Zhuang
*/
public class NullObject {
}

52
src/main/java/com/alibaba/excel/util/FieldUtils.java

@ -2,7 +2,12 @@ package com.alibaba.excel.util;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.Map;
import com.alibaba.excel.metadata.NullObject;
import com.alibaba.excel.write.metadata.RowData;
import net.sf.cglib.beans.BeanMap;
/** /**
* Field utils * Field utils
@ -11,8 +16,29 @@ import java.lang.reflect.Modifier;
**/ **/
public class FieldUtils { public class FieldUtils {
public static Class<?> nullObjectClass = NullObject.class;
private static final int START_RESOLVE_FIELD_LENGTH = 2; private static final int START_RESOLVE_FIELD_LENGTH = 2;
public static Class<?> getFieldClass(Map dataMap, String filedName) {
if (dataMap instanceof BeanMap) {
return ((BeanMap)dataMap).getPropertyType(filedName);
}
Object value = dataMap.get(filedName);
if (value != null) {
return value.getClass();
}
return nullObjectClass;
}
public static Class<?> getFieldClass(RowData rowData, int dataIndex) {
Object value = rowData.get(dataIndex);
if (value != null) {
return value.getClass();
}
return nullObjectClass;
}
/** /**
* Parsing the name matching cglib * Parsing the name matching cglib
* <ul> * <ul>
@ -51,17 +77,13 @@ public class FieldUtils {
return firstChar + fieldName.substring(1); return firstChar + fieldName.substring(1);
} }
/** /**
* Gets an accessible {@link Field} by name respecting scope. Superclasses/interfaces will be considered. * Gets an accessible {@link Field} by name respecting scope. Superclasses/interfaces will be considered.
* *
* @param cls * @param cls the {@link Class} to reflect, must not be {@code null}
* the {@link Class} to reflect, must not be {@code null} * @param fieldName the field name to obtain
* @param fieldName
* the field name to obtain
* @return the Field object * @return the Field object
* @throws IllegalArgumentException * @throws IllegalArgumentException if the class is {@code null}, or the field name is blank or empty
* if the class is {@code null}, or the field name is blank or empty
*/ */
public static Field getField(final Class<?> cls, final String fieldName) { public static Field getField(final Class<?> cls, final String fieldName) {
final Field field = getField(cls, fieldName, false); final Field field = getField(cls, fieldName, false);
@ -69,19 +91,15 @@ public class FieldUtils {
return field; return field;
} }
/** /**
* Gets an accessible {@link Field} by name, breaking scope if requested. Superclasses/interfaces will be * Gets an accessible {@link Field} by name, breaking scope if requested. Superclasses/interfaces will be
* considered. * considered.
* *
* @param cls * @param cls the {@link Class} to reflect, must not be {@code null}
* the {@link Class} to reflect, must not be {@code null} * @param fieldName the field name to obtain
* @param fieldName * @param forceAccess whether to break scope restrictions using the
* the field name to obtain * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will
* @param forceAccess * only
* whether to break scope restrictions using the
* {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only
* match {@code public} fields. * match {@code public} fields.
* @return the Field object * @return the Field object
* @throws NullPointerException if the class is {@code null} * @throws NullPointerException if the class is {@code null}
@ -140,6 +158,4 @@ public class FieldUtils {
return match; return match;
} }
} }

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

@ -9,8 +9,10 @@ import java.util.LinkedHashMap;
* @author Jiaju Zhuang * @author Jiaju Zhuang
**/ **/
public class MapUtils { public class MapUtils {
private MapUtils() {} private MapUtils() {}
/** /**
* Creates a <i>mutable</i>, empty {@code HashMap} instance. * Creates a <i>mutable</i>, empty {@code HashMap} instance.
* *

11
src/main/java/com/alibaba/excel/write/executor/ExcelWriteAddExecutor.java

@ -113,8 +113,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor {
WriteHandlerUtils.afterCellCreate(writeContext, cell, head, relativeRowIndex, Boolean.FALSE); WriteHandlerUtils.afterCellCreate(writeContext, cell, head, relativeRowIndex, Boolean.FALSE);
Object value = oneRowData.get(dataIndex); Object value = oneRowData.get(dataIndex);
WriteCellData<?> cellData = converterAndSet(writeContext.currentWriteHolder(), WriteCellData<?> cellData = converterAndSet(writeContext.currentWriteHolder(),
value == null ? null : value.getClass(), FieldUtils.getFieldClass(oneRowData, dataIndex), null, cell, value, null, head, relativeRowIndex);
null, cell, value, null, head, relativeRowIndex);
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE);
} }
@ -143,8 +142,7 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor {
Object value = beanMap.get(name); Object value = beanMap.get(name);
WriteCellData<?> cellData = converterAndSet(currentWriteHolder, WriteCellData<?> cellData = converterAndSet(currentWriteHolder,
excelContentProperty.getField().getType(), excelContentProperty.getField().getType(),
null, null, cell, value, excelContentProperty, head, relativeRowIndex);
cell, value, excelContentProperty, head, relativeRowIndex);
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head, relativeRowIndex, Boolean.FALSE);
beanMapHandledSet.add(name); beanMapHandledSet.add(name);
} }
@ -168,9 +166,8 @@ public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor {
WriteHandlerUtils.beforeCellCreate(writeContext, row, null, cellIndex, relativeRowIndex, Boolean.FALSE); WriteHandlerUtils.beforeCellCreate(writeContext, row, null, cellIndex, relativeRowIndex, Boolean.FALSE);
Cell cell = WorkBookUtil.createCell(row, cellIndex); Cell cell = WorkBookUtil.createCell(row, cellIndex);
WriteHandlerUtils.afterCellCreate(writeContext, cell, null, relativeRowIndex, Boolean.FALSE); WriteHandlerUtils.afterCellCreate(writeContext, cell, null, relativeRowIndex, Boolean.FALSE);
WriteCellData<?> cellData = converterAndSet(currentWriteHolder, value == null ? null : value.getClass(), WriteCellData<?> cellData = converterAndSet(currentWriteHolder,
null, cell, FieldUtils.getFieldClass(beanMap, filedName), null, cell, value, null, null, relativeRowIndex);
value, null, null, relativeRowIndex);
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, relativeRowIndex, Boolean.FALSE); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, relativeRowIndex, Boolean.FALSE);
} }
} }

5
src/main/java/com/alibaba/excel/write/executor/ExcelWriteFillExecutor.java

@ -16,6 +16,7 @@ import com.alibaba.excel.enums.WriteTemplateAnalysisCellTypeEnum;
import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.FieldUtils;
import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.util.WriteHandlerUtils; import com.alibaba.excel.util.WriteHandlerUtils;
import com.alibaba.excel.write.metadata.fill.AnalysisCell; import com.alibaba.excel.write.metadata.fill.AnalysisCell;
@ -198,8 +199,8 @@ public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor {
continue; continue;
} }
Object value = dataMap.get(variable); Object value = dataMap.get(variable);
WriteCellData<?> cellData = converterAndSet(writeSheetHolder, value == null ? null : value.getClass(), null, WriteCellData<?> cellData = converterAndSet(writeSheetHolder, FieldUtils.getFieldClass(dataMap, variable),
cell, value, fieldNameContentPropertyMap.get(variable), null, relativeRowIndex); null, cell, value, fieldNameContentPropertyMap.get(variable), null, relativeRowIndex);
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, relativeRowIndex, Boolean.FALSE); WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, null, relativeRowIndex, Boolean.FALSE);
} else { } else {
StringBuilder cellValueBuild = new StringBuilder(); StringBuilder cellValueBuild = new StringBuilder();

2
src/test/java/com/alibaba/easyexcel/test/core/encrypt/EncryptDataTest.java

@ -30,7 +30,7 @@ public class EncryptDataTest {
@BeforeClass @BeforeClass
public static void init() { public static void init() {
file07 = TestFileUtil.createNewFile("encrypt07111.xlsx"); file07 = TestFileUtil.createNewFile("encrypt07.xlsx");
file03 = TestFileUtil.createNewFile("encrypt03.xls"); file03 = TestFileUtil.createNewFile("encrypt03.xls");
file07OutputStream = TestFileUtil.createNewFile("encryptOutputStream07.xlsx"); file07OutputStream = TestFileUtil.createNewFile("encryptOutputStream07.xlsx");
file03OutputStream = TestFileUtil.createNewFile("encryptOutputStream03.xls"); file03OutputStream = TestFileUtil.createNewFile("encryptOutputStream03.xls");

79
src/test/java/com/alibaba/easyexcel/test/temp/poi/PoiEncryptTest.java

@ -0,0 +1,79 @@
package com.alibaba.easyexcel.test.temp.poi;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.easyexcel.test.core.encrypt.EncryptData;
import com.alibaba.easyexcel.test.core.simple.SimpleData;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Ignore;
import org.junit.Test;
/**
* TODO
*
* @author Jiaju Zhuang
*/
@Ignore
public class PoiEncryptTest {
@Test
public void encrypt() throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook();
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(workbook);
Sheet sheet = sxssfWorkbook.createSheet("sheet1");
sheet.createRow(0).createCell(0).setCellValue("T2");
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("123456");
// write the workbook into the encrypted OutputStream
OutputStream encos = enc.getDataStream(fs);
sxssfWorkbook.write(encos);
sxssfWorkbook.dispose();
sxssfWorkbook.close();
encos.close(); // this is necessary before writing out the FileSystem
OutputStream os = new FileOutputStream(
TestFileUtil.createNewFile("encrypt" + System.currentTimeMillis() + ".xlsx"));
fs.writeFilesystem(os);
os.close();
fs.close();
}
@Test
public void encryptExcel() throws Exception {
EasyExcel.write(TestFileUtil.createNewFile("encryptv2" + System.currentTimeMillis() + ".xlsx"),
EncryptData.class).password("123456")
.sheet().doWrite(data());
}
private List<SimpleData> data() {
List<SimpleData> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
SimpleData simpleData = new SimpleData();
simpleData.setName("姓名" + i);
list.add(simpleData);
}
return list;
}
}
Loading…
Cancel
Save