繁体   English   中英

java.io.FileNotFoundException:尝试读取 excel 文件时

[英]java.io.FileNotFoundException: when trying to read excel file

您好,我正在尝试使用Apache POI库读取和打印 excel 文件的所有单元格值。 这是我的代码:

MainActivity.java

public class MainActivity extends AppCompatActivity {
    Button btn;
    String name = null;
    Uri uri = null;
    private static final int STORAGE_PERMISSION_CODE = 101;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent data = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                data.setType("*/*");
                data = Intent.createChooser(data, "Choose a file");
                launch_activity.launch(data);
            }
        });
    }

    ActivityResultLauncher<Intent> launch_activity = registerForActivityResult
            (new ActivityResultContracts.StartActivityForResult(),
                    new ActivityResultCallback<ActivityResult>() {
                        @Override
                        public void onActivityResult(ActivityResult result) {
                            if (result.getResultCode() == Activity.RESULT_OK) {
                                Intent data = result.getData();
                                Uri uri = null;
                                if (data != null) {
                                    uri = data.getData();
                                }
                                if (uri != null && uri.getScheme().equals("content")) {
                                    try (Cursor returnCursor = getContentResolver().query(uri, null, null, null, null)) {
                                        if (returnCursor != null && returnCursor.moveToFirst()) {
                                            name = returnCursor.getString(returnCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME));
                                        }
                                    }
                                }
                                if(name == null){
                                    if (uri != null) {
                                        name = uri.getPath();
                                    }
                                    int cut = 0;
                                    if (name != null) {
                                        cut = name.lastIndexOf('/');
                                    }
                                    if(cut != 1){
                                        if (name != null) {
                                            name = name.substring(cut + 1);
                                        }
                                    }
                                }
                                String[] extension = null;
                                if (name != null) {
                                    extension = name.split("\\.");
                                }
                                if (extension != null && (extension[extension.length - 1].equals("xls") || extension[extension.length - 1].equals("xlsx")))
                                    checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE);
                                else if (extension != null) {
                                    Toast.makeText(MainActivity.this,extension[extension.length - 1]+" file is not supported",Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    });

    public static void readExcelFromStorage(Context context, String fileName) {
        InputStream fileInputStream = null;    
        try {
            try {
                fileInputStream = getContentResolver().openInputStream(uri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            // Create instance having reference to .xls/.xlsx file
            Workbook workbook = null;
            try {
                if (fileInputStream != null) {
                    workbook = new HSSFWorkbook(fileInputStream);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            // Fetch sheet at position 'i' from the workbook
            Sheet sheet = null;
            if (workbook != null) {
                sheet = workbook.getSheetAt(0);
            }

            // Iterate through each row
            if (sheet != null) {
                for (Row row : sheet) {
                    if (row.getRowNum() > 0) {
                        // Iterate through all the cells in a row (Excluding header row)
                        Iterator<Cell> cellIterator = row.cellIterator();

                        while (cellIterator.hasNext()) {
                            Cell cell = cellIterator.next();

                            // Check cell type and format accordingly
                            switch (cell.getCellType()) {
                                case Cell.CELL_TYPE_NUMERIC:
                                    Toast.makeText(context.getApplicationContext(), String.valueOf(cell.getNumericCellValue()),Toast.LENGTH_SHORT).show();
                                    break;

                                case Cell.CELL_TYPE_STRING:
                                       Toast.makeText(context.getApplicationContext(), cell.getStringCellValue(),Toast.LENGTH_SHORT).show();
                                    break;
                            }
                        }
                    }
                }
            }
        } finally {
            try {
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    public void checkPermission(String permission, int requestCode)
    {
        if (ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) {

            // Requesting the permission
            ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode);
        }
        else {
            Toast.makeText(MainActivity.this, "Permission already granted", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode,
                permissions,
                grantResults);

         if (requestCode == STORAGE_PERMISSION_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "Storage Permission Granted", Toast.LENGTH_SHORT).show();
                readExcelFromStorage(MainActivity.this, uri);
            } else {
                Toast.makeText(MainActivity.this, "Storage Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

当我执行我的代码时,我选择了我想要的 excel 文件(在我的内部存储中),然后我不断收到这个错误:

java.io.FileNotFoundException:/storage/emulated/0/Android/data/com.example.uploadipaselectricdata/files/employee_details.xlsx:打开失败:ENOENT(没有这样的文件或目录)

如何修复此错误? 请帮忙。

我正在实际的 android 设备上测试这个应用程序

如果您确定文件的路径正确但仍然出现此类异常,请检查应用程序是否有足够的权限访问该位置。 毕竟操作系统声称没有这样的文件,你将无法在应用程序代码中修复它。

我不完全确定 Excel 的工作簿想要什么,特别是 FileInputStream 或只是 InputStream,您可以尝试使用系统通过getContentResolver().openInputStream(uri)返回的 URI 打开并尝试传递它(这是通过Intent.getData() .) 这也应该适用于 API 30 及更高版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM