[英]Angular how to read an excel file from an assets folder using typeScript
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.因此,我在从 Angular 项目中的 excel 文件读取数据时遇到问题。 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内的app.component.ts 中,我得到一个文件:
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:我如何理解http.get我需要使用下面的代码:
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'.错误类型错误:无法在“FileReader”上执行“readAsBinaryString”:参数 1 不是“Blob”类型。
Help me please with reading data from an excel file is located in the assets folder.请帮助我从位于资产文件夹中的excel文件中读取数据。
I suggest to use a library to parse the excel file.我建议使用库来解析 excel 文件。
See there an example of SheetJs :请参阅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 :)我希望它可以帮助你,即使它很晚:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.