下面是一个使用Angular 7从Excel中读取数据并插入现有表格中的解决方案的代码示例:
npm install xlsx file-saver --save
import { Injectable } from '@angular/core';
import * as XLSX from 'xlsx';
@Injectable({
providedIn: 'root'
})
export class ExcelService {
constructor() { }
public importExcel(file: File): Promise {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = (e: any) => {
const arrayBuffer: any = e.target.result;
const data = new Uint8Array(arrayBuffer);
const arr = new Array();
for (let i = 0; i !== data.length; ++i) {
arr[i] = String.fromCharCode(data[i]);
}
const workbook = XLSX.read(arr.join(''), { type: 'binary' });
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
const jsonData = XLSX.utils.sheet_to_json(worksheet, { raw: false });
resolve(jsonData);
};
fileReader.readAsArrayBuffer(file);
});
}
}
import { Component } from '@angular/core';
import { ExcelService } from './excel.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
data: any[];
constructor(private excelService: ExcelService) { }
onFileChange(evt: any) {
const target: DataTransfer = (evt.target);
if (target.files.length !== 1) throw new Error('Cannot use multiple files');
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
const contents: string = e.target.result;
this.excelService.importExcel(target.files[0])
.then(data => {
this.data = data;
});
};
reader.readAsText(target.files[0]);
}
}
onFileChange
方法:
Name
Age
{{item.name}}
{{item.age}}
这样,当你选择一个Excel文件后,它将被读取并将数据插入到表格中。请确保Excel文件的第一个工作表中包含名称为"name"和"age"的列。