如何将excel文件导入angular项目typescript



在我的Angular项目中,我有一个包含这些信息的excel文件(FirstName, LastName, Age, Date),所以我创建了一个函数,使我导出此数据格式excel。现在我需要创建一个函数,使我能够将excel文件导入到我的angular项目中(在表中添加excel文件的信息)。

这是我的代码:

clients.html:

<div class="panel-body table-responsive">
<table id="excel-table" class="table">
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Age</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let client of clients'>
<td>{{client.FirstName}}</td>
<td>{{client.LastName}}</td>
<td>{{client.Age}}</td>
<td>{{client.Date}}</td>
<td>
<button class="btn btn-sm btn-danger" (click)="exportexcel()">ExportExcel</button>
<div class="upload-btn-wrapper">
<button class="btn btn-default" (click)="importexcel()">Importer Excel</button>
<input type="file" name="myfile" />
</div>
</td>
</tr>
</tbody>
</table>
</div>

客户。ts:

@Component({
selector: 'app-clients',
templateUrl: './clients.component.html',
styleUrls: ['./clients.component.css']
})
export class ClientsComponent implements OnInit {

constructor() { }
fileName = 'ExcelFile.xlsx';
exportexcel(): void {
const data = this.clients.map(c => ({ 'LastName': c.LastName, 'Age': c.Age }));
const ws = XLSX.utils.json_to_sheet(data);
const wb: XLSX.WorkBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
XLSX.writeFile(wb, this.fileName);
}
importexcel(): void {}

From the docs:

以一个type="file":

的HTML INPUT元素开始
<input type="file" id="input_dom_element">

对于瞄准Chrome 76+的现代网站,建议使用blob# arrayBuffer:

async function handleFileAsync(e) {
const file = e.target.files[0];
const data = await file.arrayBuffer();
/* data is an ArrayBuffer */
const workbook = XLSX.read(data);
/* DO SOMETHING WITH workbook HERE */
}
input_dom_element.addEventListener("change", handleFileAsync, false);

最新更新