angular 使用xlsx 導出導入excel


1.安裝xlsx插件 

npm install xlsx --save
 

2.在component中使用

ts:

 1 import { Component, OnInit } from '@angular/core';
 2 import * as XLSX from 'xlsx';
 3  
 4 @Component({
 5   selector: 'app-excel',
 6   templateUrl: './excel.component.html',
 7   styleUrls: ['./excel.component.css']
 8 })
 9 export class ExcelComponent implements OnInit {
10   data = [
11     ['1','a','aa'],
12     ['2','b','bb'],
13     ['3','c','cc']
14   ]
15   inputdata = []
16   constructor() {}
17   ngOnInit() {
18   }
19   // 導出
20   daochu(){
21     /* generate worksheet */
22     const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(this.data);
23     const ws2: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(this.data);
24  
25     /* generate workbook and add the worksheet */
26     const wb: XLSX.WorkBook = XLSX.utils.book_new();
27     XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
28     XLSX.utils.book_append_sheet(wb, ws2, 'Sheet2');
29  
30     console.log(wb)
31     /* save to file */
32     XLSX.writeFile(wb, 'SheetJS.xlsx');
33   }
34  
35   // 導入
36   daoru(evt: any) {
37     /* wire up file reader */
38     const target: DataTransfer = <DataTransfer>(evt.target);
39     if (target.files.length !== 1) throw new Error('Cannot use multiple files');
40     const reader: FileReader = new FileReader();
41     reader.onload = (e: any) => {
42       /* read workbook */
43       const bstr: string = e.target.result;
44       const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});
45  
46       /* grab first sheet */
47       const wsname: string = wb.SheetNames[0];
48       const ws: XLSX.WorkSheet = wb.Sheets[wsname];
49  
50       /* save data */
51       this.inputdata = (XLSX.utils.sheet_to_json(ws, {header: 1}));
52       console.log(this.inputdata)
53  
54       evt.target.value="" // 清空
55     };
56     reader.readAsBinaryString(target.files[0]);
57  
58   }
59  
60 }

 

 

html:

1 <div>導出</div>
2 <button (click)="daochu()">導出</button>
3 <div>導入</div>
4 <input type="file" (change)="daoru($event)" multiple="false" />

 

轉載自:https://blog.csdn.net/qq_39785489/article/details/80063129


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM