代码之家  ›  专栏  ›  技术社区  ›  Alex Charters

无法使用Intent.ACTION\u视图在Android上打开excel文件

  •  0
  • Alex Charters  · 技术社区  · 8 年前


    enter image description here
    我不知道这是什么原因,也无法在网上找到任何相关信息。 我使用的是来自 here 支持我的目标SDK 28。

    我的导出方法:

     public void onExport(View view){
            try {
                //write changes to excel file(changes made outide of function)
                workbook.write();
                workbook.close();
                Toast.makeText(getApplication(),
                        "Data Exported to Excel Sheet", Toast.LENGTH_SHORT).show();
                findViewById(R.id.btn_export).setEnabled(false);
    
                //set file to saved excel file
                File file = new File(Environment.getExternalStorageDirectory(),
                        race.getName()+".xls");
                Uri path = FileProvider.getUriForFile(getApplicationContext(), "com.something.racecalculator.fileprovider", file);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                Log.i("path: ", path.toString());
                intent.setDataAndType(path, "image/jpg");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
    
            } catch (IOException e) {
                e.printStackTrace();
            } catch (WriteException e) {
                e.printStackTrace();
            }
            catch (ActivityNotFoundException e) {
                Log.i("oh no:", "No application available to view excel");
            }
     }
    

    AndroidManifest.xml中的My provider标记(设置为的子项):

    <provider
                android:name=".GenericFileProvider"
                android:authorities="com.something.racecalculator.fileprovider"
                android:exported="false"
                android:grantUriPermissions="true">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/provider_paths"/>
            </provider>
    

    1 回复  |  直到 8 年前
        1
  •  3
  •   Alex Charters    8 年前

    我不确定到底是什么导致了这个问题,但是,我怀疑我可能是把文件路径弄错了。我更改了一些内容(包括excel文件的保存位置)。更改自 /storage/emulated/0/ /storage/emulated/0/Samsung )以下是有效的方法:

    Intent intent = new Intent(Intent.ACTION_VIEW);
    File file = new File("/storage/emulated/0/Samsung"+File.separator + race.getName()+".xls");
    Uri path = FileProvider.getUriForFile(getApplicationContext(), "com.something.racecalculator.fileprovider", file);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.setDataAndType(path, "application/vnd.ms-excel");
    startActivity(intent);
    

    请记住,您需要实现一个 FileProvider 如果您的目标SDK为24或以上