Search code examples
angularxlsx

how to use SheetJS (js-xlsx) in angular 2


I'm learning angular2 and i wanted to use js-xlsx library in my project.

I installed xlsx npm install xlsx and jszip npm install jszip and added them in my index.html

<script src="node_modules/xlsx/dist/xlsx.core.min.js"></script>

<script src="node_modules/jszip/dist/jszip.min.js"></script>

and added the typescript defitions tsd install xlsx

and I'm using webpack

but when I used it in

import * as xlsx from 'xlsx';

but i get error module build failed: error: cannot resolve module 'xlsx'


Solution

  • An easier method would be not using typings at all:

    1. Add xlsx.core.min.js to your index.html file as you did. (I'm using angular-cli so my js files get copied to the dist/vendor directory)

      <script src="vendor/xlsx/dist/xlsx.core.min.js"></script>

    2. In your module, do not use import but declare XLSX under your imports block.

      declare var XLSX: any;

    If you're using angular-cli, you will need to add xlsx to your angular-cli-build.js file.

    module.exports = function(defaults) {
      return new Angular2App(defaults, {
        vendorNpmFiles: [
          'systemjs/dist/system-polyfills.js',
          'systemjs/dist/system.src.js',
          'zone.js/dist/**/*.+(js|js.map)',
          'es6-shim/es6-shim.js',
          'reflect-metadata/**/*.+(ts|js|js.map)',
          'rxjs/**/*.+(js|js.map)',
          '@angular/**/*.+(js|js.map)',
          'moment/moment.js',
           ....
          'xlsx/**/*.+(js|js.map)'
        ]})
    };