【随手记录】Apache POI 报错:Zip bomb detected! The file would exceed the max. ratio of compressed file ....
1、背景:
使用POI解析Excel报错:
1 | Zip bomb detected! The file would exceed the max. ratio of compressed file size to the size of the expanded data。<br>This may indicate that the file is used to inflate memory usage and this could pose a security risk.<br>You can adjust this limit via Zipsecureile.setMinInflateRatio() if you need to work with files which exceed this limit.<br>Uncompressed size:105456Raw/compressedsize : 9 -70ratio: 0 .009198Limits: MIN_INFLATE_RATIO: 0.010000 ,Entryxl/pivotCache/pivotCacheRecords1.xml |
2、原因:
Excel是有压缩机制的,读取解析Excel时候,会将Excel解压为一个非常大的未压缩文件,会引起诸如耗尽内存或磁盘空间等问题。
为了防止这种情况的发生,Apache POI内置了一些防护措施,并且默认情况下启用了这些防护措施。
3、处理
1 2 3 4 5 6 7 | fileInputStream = new FileInputStream(filePath); // 设置最小解压比率以解决 Zip bomb 错误 ZipSecureFile.setMinInflateRatio(- 1 .0d); // 创建 XSSFWorkbook 对象 XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream); // 获取指定的 sheet XSSFSheet sheet = workbook.getSheet(sheetName); |
4、其他
4.1、分块处理:
将文件分块读取并处理,而不是一次性加载整个文件,这样可以减少内存使用,防止内存溢出。
4.2、另存为csv:
可以尝试重新压缩文件,另存为csv格式,降低压缩比率,以减少解压时的内存使用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】