Ashamed to ask, but for resolving my problem I need to ask. So, I have a problem with reading data from an excel file in my Angular project. The file is located in the assets folder.
I know how to get a file from the folder.
In app.component.ts inside ngOnInit I get a file:
ngOnInit() {
this.http.get('assets/dataTest.xlsx').subscribe((data: any) => {
console.log("get: " + data);
});
}
How I understand inside http.get I need to use code below:
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
console.log("READ " + e);
};
reader.readAsBinaryString(data);
But it does not work. I get an error:
ERROR TypeError: Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'.
Help me please with reading data from an excel file is located in the assets folder.
I suggest to use a library to parse the excel file.
See there an example of SheetJs :
/* <input type="file" (change)="onFileChange($event)" multiple="false" /> */
/* ... (within the component class definition) ... */
onFileChange(evt: any) {
/* wire up file reader */
const target: DataTransfer = <DataTransfer>(evt.target);
if (target.files.length !== 1) throw new Error('Cannot use multiple files');
const reader: FileReader = new FileReader();
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];
/* save data */
this.data = <AOA>(XLSX.utils.sheet_to_json(ws, {header: 1}));
};
reader.readAsBinaryString(target.files[0]);
}
i just solve the problem with this.
read() {
this.httpClient.get('assets/files/Report DTP.xls', { responseType: 'blob' })
.subscribe((data: any) => {
const reader: FileReader = new FileReader();
let dataJson1;
let dataJson2;
reader.onload = (e: any) => {
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
/* grab first sheet */
const wsname1: string = wb.SheetNames[1];
const ws1: XLSX.WorkSheet = wb.Sheets[wsname1];
/* grab second sheet */
const wsname2: string = wb.SheetNames[2];
const ws2: XLSX.WorkSheet = wb.Sheets[wsname2];
/* save data */
dataJson1 = XLSX.utils.sheet_to_json(ws1);
dataJson2 = XLSX.utils.sheet_to_json(ws2);
console.log(dataJson1);
};
reader.readAsBinaryString(data);
console.log(data);
});
}
I hope it helps you even though it's late :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.