【问题标题】:Android reading data from xlsxAndroid 从 xlsx 读取数据
【发布时间】:2019-08-18 09:21:50
【问题描述】:

我正在尝试从 Android 中的 xlsx 读取数据。我有这段代码,用于选择一个文件,以及从所选 xlsx 获取一些数据的读取函数。
我得到这样的 xlsy 路径:

content://com.mi.android.globalFileexplorer.myprovider/root_files/storage/1EF>7-0EF8/Documents/export.xlsx

但是读取函数给了我一个 filenotfound 异常。
所以我的问题是,我应该如何获得文件的正确路径?

public void onBrowse() {
        Intent chooseFile;
        Intent intent;
        chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
        chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
        chooseFile.setType( "*/*");
        intent = Intent.createChooser(chooseFile, "Choose a file");
        startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) return;
        if(requestCode == ACTIVITY_CHOOSE_FILE)
        {
            Uri uri = data.getData();
            Log.d(TAG, "uri path: "+uri.getPath());
            read(uri.getPath());
        }
    }

private void read(String path) {
        try {
            workbook = WorkbookFactory.create(new File(path));
        } catch (Exception e) {
            Log.d(TAG, "read: " + e.getMessage());
        }

        Log.d(TAG, "Workbook has " + workbook.getNumberOfSheets() + " sheets");
    }

【问题讨论】:

  • 为什么在这一行有这个多余的空间chooseFile.setType( "*/ *");
  • @Skizo-ozᴉʞS 删除了多余的空间,但我仍然得到相同的 filenotfound 异常
  • 这门课WorkbookFactory.create(new File(path));在做什么?
  • 我正在关注本指南:callicoder.com/java-read-excel-file-apache-poi。 "从 Excel 文件(.xls 或 .xlsx)创建工作簿"
  • uri.getPath() 返回的是什么?

标签: java android file path xlsx


【解决方案1】:

必须将内容 uri 转换为文件路径

public class FileUtil {
     public static String getFileAbsolutePath(Context context, Uri uri) {
        if (context == null || uri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
            if (isExternalStorageDocument(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(uri)) {
                String id = DocumentsContract.getDocumentId(uri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if (ContentResolver.SCHEME_CONTENT.equalsIgnoreCase(uri.getScheme())) {
            // MediaStore (and general)
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(context, uri, null, null);
        } else if (ContentResolver.SCHEME_FILE.equalsIgnoreCase(uri.getScheme())) {
            // File
            return uri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.MediaColumns.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}

使用

Uri uri = data.getData();
Log.d(TAG, "uri path: "+uri.getPath());
String path = FileUtil.getFileAbsolutePath(this, uri);
Log.d(TAG, "file path: "+path);
read(path);

【讨论】:

  • 用你的代码试过了。得到这个:java.io.FileNotFoundException:/storage/1EF7-0EF8/Documents/export.xlsx:打开失败:EACCES(权限被拒绝)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-02
  • 2014-01-15
  • 2012-09-12
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多