Sheetjs: Import js-xlsx Angular2/Ionic2/TypeScript proyect

Created on 5 Jan 2017  路  9Comments  路  Source: SheetJS/sheetjs

Hi, im trying to import the library to my Ionic2/Angular2/Typescript proyect and im following this steps:
First im adding the library to my app:
npm install xlsx --save
Then im including the typings:
npm install @types/xlsx --save
So at this point i can see in my app node_modules folder the index.d.ts generated:
**export declare function readFile(filename: string, opts?: IParsingOptions): IWorkBook;
export declare function read(data: any, opts?: IParsingOptions): IWorkBook;
export declare function write(data: any, opts?: IParsingOptions): any;
export declare var utils: IUtils;

export interface IProperties {
LastAuthor?: string
Author?: string;
CreatedDate?: Date;**
......

And the package.json:
{
"name": "ionic-hello-world",
"author": "Ionic Framework",
"homepage": "http://ionicframework.com/",
"private": true,
"scripts": {
"clean": "ionic-app-scripts clean",
"build": "ionic-app-scripts build",
"ionic:build": "ionic-app-scripts build",
"ionic:serve": "ionic-app-scripts serve"
},
"dependencies": {
"@angular/common": "2.2.1",
"@angular/compiler": "2.2.1",
"@angular/compiler-cli": "2.2.1",
"@angular/core": "2.2.1",
"@angular/forms": "2.2.1",
"@angular/http": "2.2.1",
"@angular/platform-browser": "2.2.1",
"@angular/platform-browser-dynamic": "2.2.1",
"@angular/platform-server": "2.2.1",
"@ionic/storage": "1.1.6",
"@types/xlsx": "0.0.31",
"ionic-angular": "2.0.0-rc.4",
"ionic-native": "2.2.11",
"ionicons": "3.0.0",
"rxjs": "5.0.0-beta.12",
"xlsx": "^0.8.1",
"zone.js": "0.6.26"
},
"devDependencies": {
"@ionic/app-scripts": "0.0.47",
"typescript": "2.0.9"
},
"cordovaPlugins": [
...
],
"cordovaPlatforms": [],
"description": "myApp: An Ionic project"
}

Then im trying to import the functions i need in home.ts file like this:
import { readFile, IWorkBook, IWorkSheet, IUtils } from '@types/xlsx';

public getXLSXRequest(){
var wb: IWorkBook;
wb = readFile('../../assets/filename.xls');
}

But cant import the library correctly. Anyone has an idea of what im doing wrong?
Thanks in advance.

Most helpful comment

Ok, try this code.
Import xlsx library first to your page.ts or provider:
import * as XLSX from 'xlsx';
You have to do the steps i put on my first comment to import a library first.
Then create a method to recieve the xls and transform it to json in your page class or provider class:

public XLStoJSON(){
  return new Promise((resolve, reject) => {
    var url = 'put here the url where your xls is';
    var oReq = new XMLHttpRequest();
    var workbook: any;
    oReq.open("GET", url, true);
    oReq.responseType = "arraybuffer";
    oReq.onload = (e) => {
      if (oReq.status >= 200 && oReq.status < 300) {
        var arraybuffer = oReq.response;
        var data = new Uint8Array(arraybuffer);
        var arr = new Array();
        for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
        var bstr = arr.join("");
        workbook = XLSX.read(bstr, {type:"binary"});
        var worksheetname = workbook.SheetNames[0];
        var worksheet = workbook.Sheets[worksheetname];
        var json = XLSX.utils.sheet_to_json(worksheet, {raw: true});
        resolve('Finished generating JSON');
      } else {
        reject(console.log('XMLHttpRequest failed; error code:' + oReq.statusText));
      }
    }
    oReq.send();
  });
}

You can find info about how to manage Promises here

All 9 comments

I am not familiar with Angular or Ionic or TypeScript. What is the error message? Can you possibly share a very basic app that shows this problem?

I have solved it using the following code:
import * as XLSX from 'xlsx'; //instead of import { readFile, IWorkBook, IWorkSheet, IUtils } from '@types/xlsx';

And then in my home.ts file:

public getXLSXRequest(){
  var wb = XLSX.readFile('../../assets/filename.xls');
}

It seems that you cant import this library using the named exports approach and you have to use the default export approach. You can read more info about importing third party libs to your ionic2 proyect here

Thanks for the response @reviewher

@MarcoAPA can you please provide me some more code how to handle this in ionic 2?
I want to choose a file from the system and then get it into json.
Thanks!

hi @wurstel, sorry for the delay answering. Are you using this library to choose a file from the system? Is that file you want to get from the system and parse a .csv, a .xls or another format supported in the js-xlsx library? js-xlsx library has a method to transform a .xls to json for example, don't know if its what you want to achieve.

Yes, I want to import a .xls file and transform it to json.
But there's the problem, I don't get how to do this in ionic 2 ;-)

Ok, try this code.
Import xlsx library first to your page.ts or provider:
import * as XLSX from 'xlsx';
You have to do the steps i put on my first comment to import a library first.
Then create a method to recieve the xls and transform it to json in your page class or provider class:

public XLStoJSON(){
  return new Promise((resolve, reject) => {
    var url = 'put here the url where your xls is';
    var oReq = new XMLHttpRequest();
    var workbook: any;
    oReq.open("GET", url, true);
    oReq.responseType = "arraybuffer";
    oReq.onload = (e) => {
      if (oReq.status >= 200 && oReq.status < 300) {
        var arraybuffer = oReq.response;
        var data = new Uint8Array(arraybuffer);
        var arr = new Array();
        for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
        var bstr = arr.join("");
        workbook = XLSX.read(bstr, {type:"binary"});
        var worksheetname = workbook.SheetNames[0];
        var worksheet = workbook.Sheets[worksheetname];
        var json = XLSX.utils.sheet_to_json(worksheet, {raw: true});
        resolve('Finished generating JSON');
      } else {
        reject(console.log('XMLHttpRequest failed; error code:' + oReq.statusText));
      }
    }
    oReq.send();
  });
}

You can find info about how to manage Promises here

Made my day ;-)

Unfortunately I'm facing now two new problems: Calling functions and the data type of the resolve

addXLS(){
  var olddata = this.getData()

  this.XLStoJSON().then(function(data){
        for(var i=0; i < 5; i++){               // I can't call data.length, but I think it's an array (IDE says it's an object - iterating through it with data[i] works
            var newdata: any = {}
            newdata.name = data[i].name
            newdata.id = this.generateID()      // is it not possible to call another function from inside the .then function? - it throws always an error
           olddata.push(newdata)
        }
    this.setData(olddata)                 // same here - without calling another function I don't know how to save the data from the .xls sheet 
  })
  }

The promise resolves this data-structure:
[{"name":"Nikolaj","g":"m"},{"name":"Eric","g":"m"}]

Thank you one more time!

Does generateID method return a number? you can call that method there but dont know if youre returning a number.
About the data type of the resolve, are you returning the json variable when the XLStoJSON() promise resolves?
If you want to just save the XLS info in your page class why dont you create a class variable and save that json?

export class YourPageClass{
 private xlsinfo: any;

 public XLStoJSON(){
  return new Promise((resolve, reject) => {
        ...
        var json = XLSX.utils.sheet_to_json(worksheet, {raw: true});
        this.xlsinfo = json;                       // You have your json updated so you can work with it in another method
        resolve(json.json());                     // may work without .json() method, this is what i was asking in the second question
      } else {
        reject(console.log('XMLHttpRequest failed; error code:' + oReq.statusText));
      }
    }
    oReq.send();
  });
 }
}

Havent tried it but hope it works.

For completeness sake, the angular2 demo now includes an ionic example that reads from and writes to the documents directory of the device and displays an array of arrays as a grid.

https://github.com/SheetJS/js-xlsx/blob/master/demos/angular2/ionic.ts is the code example.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

eyalcohen4 picture eyalcohen4  路  3Comments

thomasledoux1 picture thomasledoux1  路  3Comments

happy0088 picture happy0088  路  3Comments

jamespan0 picture jamespan0  路  3Comments

lxzhh picture lxzhh  路  3Comments