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