I've managed to answer my own questions, partly thanks to Randyka Yudhistira for the first one.
First of all, in order that your app is detected as capable of opening XLSX files, you have to edit its AndroidManifest.xml. In a Ionic app, this file is located at: YOUR_APP/platforms/android/AndroidManifest.xml
. Add the following intent-filter inside of the <activity>
section (thanks again for this, Randyka Yudhistira):
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="file" />
<data android:mimeType="*/*" />
<data android:pathPattern=".*\\.xlsx" />
<data android:host="*" />
</intent-filter>
Secondly, to open and read the XLSX file and extract the data from it, you'll need the ngCordova plugin, that you can install easily with Bower, and the WebIntent Android plugin for Cordova and ngCorodva plugin named File:
bower install ngCordova
cordova plugin add https://github.com/Initsogar/cordova-webintent.git
cordova plugin add org.apache.cordova.file
Reference ngCordova in your HTML file (before the reference to the cordova lib):
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
And inject it as an Angular dependency in your angular module:
var yourApp = angular.module("yourApp", ['ionic', 'ngCordova']);
If you need to "feed" your app with a given file, like in my app, you need to retrieve the URL of the file. To do so, in your Ionic controller, add the services $cordovaFile
and $ionicPlatform
, and use the webintent plugin as follow to get the URI to your file:
yourApp.controller('yourAppController', function($scope, $ionicPlatform, $cordovaFile) {
$ionicPlatform.ready(function() {
if (window.plugins && window.plugins.webintent) { // checks if plugins are enabled and loaded
window.plugins.webintent.getUri(function (url) {
if(url) {
// use your file URL here
}
}
}
});
}
To open the file and read its data, you'll need to separate the path to your file from the name of the file:
var path = url.slice(0, url.lastIndexOf('/') + 1);
var filename = url.substring(url.lastIndexOf('/') + 1);
Finally, you can read the data from your file with the cordova File plugin, in four different ways (as Text, as DataURL, BinaryString, ArrayBuffer), with the function cordovaFile.readAs<theWayYouWant>(path, file)
(you get a Promise); here for example I needed the data as a binary string:
$cordovaFile.readAsBinaryString(path, filename)
.then(function(result) { // success
...
}, function() { // failure
alert('failed to open file');
});
Hope this answer will help people who struggled like me to open and read data from a file in a Ionic App :-)