Android 打开 XLSX 文件
Android open XLSX file
我正在尝试在我的 Android 应用程序中打开一个 XLSX
文件。
我知道我必须触发的 Intent
类型是 application/excel
,但是尽管我已经安装了 Google Sheets
,但我的代码显示没有应用程序可以打开我的 excel 文件.
这是我用来触发 Intent
:
的代码
private void openXLS(){
File xls = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "prova.xlsx");
Uri path = Uri.fromFile(xls);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/excel");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No Application available to view XLS", Toast.LENGTH_SHORT).show();
}
}
注意: prova.xlsx
存在,我可以够到并打开它。
已解决
使用 MIME 类型 application/vnd.ms-excel
,可以打开 *.xls
和 *.xlsx
文件。
private void openXLS(final String path) {
File file = new File(path);
Uri uri ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
} else {
uri = Uri.fromFile(file);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/vnd.ms-excel");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
}
我正在尝试在我的 Android 应用程序中打开一个 XLSX
文件。
我知道我必须触发的 Intent
类型是 application/excel
,但是尽管我已经安装了 Google Sheets
,但我的代码显示没有应用程序可以打开我的 excel 文件.
这是我用来触发 Intent
:
private void openXLS(){
File xls = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "prova.xlsx");
Uri path = Uri.fromFile(xls);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/excel");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No Application available to view XLS", Toast.LENGTH_SHORT).show();
}
}
注意: prova.xlsx
存在,我可以够到并打开它。
已解决
使用 MIME 类型 application/vnd.ms-excel
,可以打开 *.xls
和 *.xlsx
文件。
private void openXLS(final String path) {
File file = new File(path);
Uri uri ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
} else {
uri = Uri.fromFile(file);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/vnd.ms-excel");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
}