You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

生成Excel的杂货程序打包为可执行Jar后抛出IOException求助

解决可执行Jar中POI Excel操作抛出的IOException: Your InputStream was neither an OLE2 stream, nor an OOXML stream错误

问题本质

IDE运行时会自动加载所有Maven依赖,但打包成可执行Jar时若未正确包含Apache POI的OOXML相关依赖,或文件创建逻辑生成了无法被POI识别的空文件,就会触发该错误。

解决方案

1. 调整Maven打包配置,打包包含所有依赖的可执行Jar

默认的maven-jar-plugin只会打包你的代码,不会包含依赖。需要使用maven-shade-plugin构建包含所有依赖的Fat Jar,在pom.xml中添加以下配置:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.5.1</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <transformers>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <!-- 替换为你的主类全限定名 -->
                                <mainClass>你的主类完整路径</mainClass>
                            </transformer>
                            <!-- 处理POI的签名冲突 -->
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

执行mvn clean package后,target目录下的shaded Jar就是包含所有依赖的可执行Jar。

2. 确保POI依赖完整性

检查pom.xml中是否包含处理OOXML格式的完整依赖,版本需保持统一:

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.2.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>4.1.2</version>
    </dependency>
</dependencies>

3. 修正文件创建逻辑,避免生成空Excel文件

当目标Excel文件不存在时,直接创建空文件会导致POI无法识别。需通过POI API生成合法的工作簿并写入文件:

// 替换核心业务类中创建空文件的逻辑
File excelFile = new File("你的Excel文件路径.xlsx");
if (!excelFile.exists()) {
    // 创建合法的XSSF工作簿并写入文件
    try (XSSFWorkbook workbook = new XSSFWorkbook();
         FileOutputStream fos = new FileOutputStream(excelFile)) {
        // 添加默认工作表
        workbook.createSheet("商品清单");
        workbook.write(fos);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
// 之后再正常读取工作簿

4. 验证打包后的Jar依赖

解压打包后的Jar,检查是否包含poi-ooxml*.jar及相关依赖文件,确认依赖已被正确打包。

内容的提问来源于stack exchange,提问作者msoper342

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 01:39:40