How to open a excel file in Android Programmatically

Ashu Maurya
1 min readJan 20, 2020

--

Android 7 Nougat and higher have added a new security limitations which restricts Uri.parse() to gain access to documents or files in internal or external storage. Rather, we have to utilize the FileProvider class which is accessible in the Android Support Library. In this instructional exercise, please find below the best way to utilize FileProvider to get the records from internal and external storage.

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true"
>
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"
/>
</provider>

provider_paths.xml: depending on which storage you need to access, you need to use something else than external-path.

<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>

YourActivitity.java: In this example, I want to open a Excel file. We use the default FileProvider. For context, you can use this if you are inside an activity. Make sure you have given the permission for storage.

Intent intent=new Intent(Intent.ACTION_VIEW);
Uri apkURI = FileProvider.getUriForFile(getApplicationContext(),
getApplicationContext() .getPackageName(),file);

MimeTypeMap myMime = MimeTypeMap.getSingleton();
StringmimeType=myMime.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(apkURI.toString()));//It will return the mimetype

intent.setDataAndType(apkURI, mimeType);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);

As you can see in the above code, if the file is excel,word or even ppt; it returns the mime type of that file,and adds it to the intent arguments. This in turn would help you to open any type of file in Android.

Conclusion

Thank you for reading this tutorial. Let me know in the comments if this tutorial helped you.

UPDATED POST

For above code to work on Android Q (API LEVEL: 29) add the below line in manifest file.

android:requestLegacyExternalStorage=”true”

--

--

Ashu Maurya
Ashu Maurya

No responses yet