I am using xlsx excel reader and I've to repeat the same operation in 3 pages; So, I'm trying to create a common excel read function but I am unable to make it synchrous.
Can someone please guide me because I've read many articles?
public importExcelData(evt: any)
{
let data: any[] = [];
const target: DataTransfer = <DataTransfer>(evt.target);
if (target.files.length !== 1)
throw new Error('Cannot use multiple files');
const reader: FileReader = new FileReader();
reader.readAsBinaryString(target.files[0]);
reader.onload = (e: any) => {
/* read workbook */
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
/* grab first sheet */
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
/* fill data */
data = (XLSX.utils.sheet_to_json(ws, { header: 1 }));
}
return new Promise(resolve => { resolve(data) });
}
Here is the function that will call the above function
onFileChange(evt: any) {
this.importExcelData(evt).then(data => {
console.log(data);
});
}