- npm i file-saver
- npm i xlsx
Создайте сервис с помощью следующих методов
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
const EXCEL_TYPE = 'application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
public exportAsExcelFile(report:string, json: any[], excelFileName: string): void {
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'];
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
this.saveAsExcelFile(report,excelBuffer, excelFileName);
}
private saveAsExcelFile(reportName:string,buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], { type: EXCEL_TYPE });
FileSaver.saveAs(data + fileName + EXCEL_EXTENSION);
}
Позвоните этот метод в любом компоненте, который вы хотите.
this.excelService.exportAsExcelFile("filename","filenameagain", "data that has to be...");
// Обновление для загрузки
fileUpload = (data)=> {
let fileUploaded = data.target.files[0];
const dummyFunc = ()=>{
// call some function here
}
// Get The File From The Input
var oFile = data.target.files[0];
var sFilename = oFile.name;
// Create A File Reader HTML5
var temp_array = [];
var reader = new FileReader();
// Ready The Event For When A File Gets Selected
reader.onload = function (e) {
var data = (<FileReader>e.target).result;
var cfb = XLSX.read(data, {
type: 'binary'
});
var oJS = XLSX.utils.sheet_to_json(cfb.Sheets[cfb.SheetNames[0]], {
// blankRows: false,
header: ["Give some name here"], //This will be the header name
});
oJS.shift();
for (let i = 0; i < oJS.length; i++) {
temp_array.push(oJS[i]["Give some name here"]
if (i == oJS.length - 1) {
dummyFunc(temp_array) // To call some function after upload is done.
}
}
}
reader.readAsBinaryString(oFile);
}