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

Android使用Apache Poi读取.xlsx文件遇ENOENT等异常求助

问题分析与解决方案

第一个错误:文件找不到(ENOENT)

错误信息:

java.io.FileNotFoundException: assets/test.xlsx: open failed: ENOENT (No such file or directory)

原因:Android中无法直接用FileInputStream读取assets目录下的文件,assets属于应用内部资源,必须通过AssetManager获取输入流。

第二个错误:命名空间不兼容

使用AssetManager后出现:

org.apache.poi.ooxml.POIXMLException: error: The 'namespace-prefix' feature is not supported while the 'namespaces' feature is enabled.

原因:POI 4.x版本在Android平台上,默认XML解析器与Android系统存在兼容性冲突,命名空间配置不匹配。

后续仍出现文件找不到

添加DocumentBuilderFactory配置后还是:

java.io.FileNotFoundException: xlsx.xlsx

原因:文件路径/文件名拼写错误,或assets文件未正确放置。


分步解决方法

1. 正确读取Assets文件

替换FileInputStream为AssetManager获取输入流,确保文件路径正确:

public void readingFile(TextView textView) {
    try {
        // 获取AssetManager实例
        AssetManager assetManager = getAssets();
        // 打开assets下的test.xlsx文件
        InputStream inputStream = assetManager.open("test.xlsx");
        
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
        Row row = sheet.getRow(0);
        if (row != null) {
            Cell cell = row.getCell(0);
            if (cell != null) {
                String cellValue = cell.getStringCellValue();
                textView.setText(cellValue);
            }
        }
        // 关闭流
        inputStream.close();
        xssfWorkbook.close();
    } catch (IOException e) {
        e.printStackTrace();
        textView.setText("读取失败:" + e.getMessage());
    }
}

2. 解决POI命名空间兼容问题

在初始化POI前,修改DocumentBuilderFactory配置并全局生效:

// 在Application类或Activity的onCreate开头添加静态代码块
static {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    try {
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    // 替换POI使用的DocumentBuilderFactory
    XMLHelper.setDocumentBuilderFactory(factory);
}

3. 确保文件正确放置

  • 确认test.xlsx文件放在src/main/assets目录下(无assets目录则手动创建,目录名需小写);
  • 检查文件名拼写完全一致(区分大小写);
  • 默认build配置会自动打包assets目录,无需额外配置。

4. 调整POI依赖版本(可选)

若上述方法无效,尝试升级到更兼容Android的POI版本,比如5.2.3:

dependencies {
    implementation 'org.apache.poi:poi:5.2.3'
    implementation 'org.apache.poi:poi-ooxml:5.2.3'
    // 添加XML解析依赖避免冲突
    implementation 'org.xmlpull:xmlpull:1.1.3.1'
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:00:14