角度4:如何从Excel读取数据? [英] Angular 4: How to read data from Excel?
本文介绍了角度4:如何从Excel读取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法从 Angular 4 中的 Excel工作表中获取数据. 下面是我的代码示例.
I am not able to get data from an Excel sheet in Angular 4. Below is my code sample.
HTML代码:
<input id="my-file-selector" type="file" (change)="uploadData($event)" name="uploadExcel">
upload.component.ts
:
public uploadData(event: any) : void {
// get data from file upload
let filesData = event.target.files;
console.log(filesData[0]);
}
推荐答案
您应遵循以下3个步骤
步骤1:导入ts-xlsx 请参考: https://www.npmjs.com/package/ts-xlsx 进行安装
step 1: import ts-xlsx refer: https://www.npmjs.com/package/ts-xlsx for installation
步骤2:使用FileReader转换为arraybuffer
step 2: Using FileReader convert to arraybuffer
步骤3:用XLSX读取数组缓冲区并将其转换为工作簿
step 3: Reading the arraybuffer with XLSX and converting as workbook
HTML代码
<input type="file" style="display: inline-block;" (change)="incomingfile($event)" placeholder="Upload file" accept=".xlsx">
<button type="button" class="btn btn-info" (click)="Upload()" >Upload</button>
打字稿
//import it
import * as XLSX from 'ts-xlsx';
//inside export class
arrayBuffer:any;
file:File;
incomingfile(event)
{
this.file= event.target.files[0];
}
Upload() {
let fileReader = new FileReader();
fileReader.onload = (e) => {
this.arrayBuffer = fileReader.result;
var data = new Uint8Array(this.arrayBuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type:"binary"});
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
console.log(XLSX.utils.sheet_to_json(worksheet,{raw:true}));
}
fileReader.readAsArrayBuffer(this.file);
}
这篇关于角度4:如何从Excel读取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文