Is there a correct way to use minified XLSX on an Angular 5 project?
Currently I'm using it as:
import * as XLSX from 'xlsx';
Using this import like:
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
And
const workbook: XLSX.WorkBook = XLSX.utils.book_new();
It works just fine, but produces a very large bundle object inside my build:
I want to know if it's possible to use the .min files, to help reduce the bundle size. And if so, how to import and use it properly?
This is how I did it in Angular:
import('xlsx').then(xlsx => {});
It is triggered only when a user clicks on my excel service button :) It seems like 'bad practice' but the xlsx
can't really be minified properly.. anyway, it saved me 1.2MB on my bundle!
Discussion on GitHub: https://github.com/SheetJS/sheetjs/issues/694#issuecomment-688310069
Getting the types requires extra (but yet easy) work - read this: How to use types with dynamic imports?
I was inspired by this developer, who encountered the same problem: https://netbasal.com/using-typescript-dynamic-imports-in-angular-d210547484dd
import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
// import * as XLSX from 'xlsx';
// import { utils, write } from 'xlsx';
// import { WorkSheet, WorkBook } from 'xlsx';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
@Injectable()
export class ExcelService {
constructor() { }
public exportAsExcelFile(arrOfObjs: {}[], excelFileName: string): void {
import('xlsx').then(xlsx => {
// console.log(xlsx);
const worksheet: import('xlsx').WorkSheet = xlsx.utils.json_to_sheet(arrOfObjs);
console.log('worksheet', worksheet);
const wb: import('xlsx').WorkBook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
if (!wb.Workbook) { wb.Workbook = {}; }
if (!wb.Workbook.Views) { wb.Workbook.Views = []; }
if (!wb.Workbook.Views[0]) { wb.Workbook.Views[0] = {}; }
wb.Workbook.Views[0].RTL = true;
const excelBuffer: BlobPart = xlsx.write(wb, { bookType: 'xlsx', type: 'array' });
this.saveAsExcelFile(excelBuffer, excelFileName);
});
}
private saveAsExcelFile(buffer: BlobPart, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE
});
FileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With