测试代码:此问题在 macOs 可直接复现,windows 下 jdk11 可以复现
public class ExcelTest {
public static void main(String[] args) {
// 写法2
String fileName = System.currentTimeMillis() + ".xlsx";
// 这里 需要指定写用哪个class去写
ExcelWriter excelWriter = null;
try {
excelWriter = EasyExcel.write(fileName, DemoData.class).password("123456").build();
WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
excelWriter.write(data(), writeSheet);
} finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
}
}
private static List<DemoData> data() {
List<DemoData> list = new ArrayList<DemoData>();
for (int i = 0; i < 10; i++) {
DemoData data = new DemoData();
data.setString("字符串" + i);
data.setDate(new Date());
data.setDoubleData(0.56);
list.add(data);
}
return list;
}
@Data
public static class DemoData {
@ExcelProperty("字符串标题")
private String string;
@ExcelProperty("日期标题")
private Date date;
@ExcelProperty("数字标题")
private Double doubleData;
/**
* 忽略这个字段
*/
@ExcelIgnore
private String ignore;
}
}
问题定位:
在 com.alibaba.excel.context.WriteContextImpl#openFileSystemAndEncrypt 方法中,OutputStream 使用后未正确关闭
private POIFSFileSystem openFileSystemAndEncrypt(File file) throws Exception {
POIFSFileSystem fileSystem = new POIFSFileSystem();
Encryptor encryptor = (new EncryptionInfo(EncryptionMode.standard)).getEncryptor();
encryptor.confirmPassword(this.writeWorkbookHolder.getPassword());
OPCPackage opcPackage = null;
try {
opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE);
// 该输出流应关闭
OutputStream outputStream = encryptor.getDataStream(fileSystem);
opcPackage.save(outputStream);
} finally {
if (opcPackage != null) {
opcPackage.close();
}
}
return fileSystem;
}