android ENOENT(No such file or directory)Apache Poi安卓

mpgws1up  于 2023-03-27  发布在  Android
关注(0)|答案(2)|浏览(134)

我尝试使用Apache Poi lib访问.xlsx文件,但收到错误

java.io.FileNotFoundException:资产/测试.xlsx:打开失败:ENOENT(无此类文件或目录)

package com.example.apachepoi;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = findViewById(R.id.textView);

        readingFile(textView);
    }
    public void readingFile(TextView textView) {
        try {
            FileInputStream fileInputStream = new FileInputStream("assets/test.xlsx");
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileInputStream);
            XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
            Row row = sheet.getRow(0);
            Cell cell = row.getCell(0);
            String cellValue = cell.getStringCellValue();
            textView.setText(cellValue);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我也尝试这样做与资产管理器,但然后我得到的错误

org.apache.poi.ooxml.POIXMLException:错误:启用“命名空间”功能时,不支持“命名空间前缀”功能。
添加后
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false);
结果是
java.io.FileNotFoundException:xlsx.xlsx
创建.gradle是
x一个一个一个一个x一个一个二个x

myzjeezk

myzjeezk1#

资源是开发计算机上的文件。它们不是设备上的文件。
替换:

FileInputStream fileInputStream = new FileInputStream("assets/test.xlsx");

与:

InputStream inputStream = getAssets().open("test.xlsx");

...然后在现在有fileInputStream的地方使用inputStream

p4rjhz4m

p4rjhz4m2#

我找到了答案。我只需要在依赖项中将版本库更改为5.2.3。

dependencies {

    implementation 'org.apache.poi:poi:5.2.3'
    implementation 'org.apache.poi:poi-ooxml:5.2.3'
}

相关问题