How to open an excel file in android

前端 未结 5 896
广开言路
广开言路 2021-01-06 08:25

I have downloaded the excel file to sdcard. want to open the file in my app and process it. Is there any way or any intent to open an excel file in android. I

5条回答
  •  既然无缘
    2021-01-06 08:36

    Use this piece of code which can be used to open arbitrary file (not only Excel).

    General idea is to get based on file mime type which Intent can handle it and then start those Intent. For sure it may happen that system doesn't have any intents to handle it or may have several Intents. Anyway here's general direction:

    Get mime type for given filename

    public String getMimeType(String filename)
    {
        String extension = FileUtils.getExtension(filename);
        // Let's check the official map first. Webkit has a nice extension-to-MIME map.
        // Be sure to remove the first character from the extension, which is the "." character.
        if (extension.length() > 0)
        {
            String webkitMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
            if (webkitMimeType != null)
               return webkitMimeType;
        }
      return "*/*";
     }
    

    Then get default intent which will handle given mime type

    public Intent getDefaultViewIntent(Uri uri)
    {
        PackageManager pm = this.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // Let's probe the intent exactly in the same way as the VIEW action
        String name=(new File(uri.getPath())).getName();
        intent.setDataAndType(uri, this.getMimeType(name));
        final List lri = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        if(lri.size() > 0)
            return intent;
        return null;
    }
    

    And as final step just start Intent returned by getDefaultViewIntent()

提交回复
热议问题