|
作者:不老猫
日期:2020年04月28日
(如果文章确实地帮助你解决了问题,请点个推荐,让我开心一下,助人为乐,嘿嘿(*^▽^*))
前端时间想做一个读取EXCEL的相关应用,只想在单页面上使用,一直没有找到可以用的。后来在一个之前的前端页面框架中找到了,然后截出来用,特此做个笔记。
导入库
首先需要一个套件,这个套件叫sheetJS,需要导入一个xlsx库,不过我npm不成功,我找到一个http直连。在html页面中添加如下代码:
<!-- 引入xlsx库 -->
<script type="text/javascript" src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
页面组件
1、在页面中需要添加一个input组件,以从电脑中获取文件。
1 <input type="file" accept=".xlsx, .xls" @change="Excelinput_handle_change">
change 事件就是导入文件之后触发的事件。
2、事件处理
1 // 选择文件完毕
2 Excelinput_handle_change(e) {
3 const files = e.target.files; // 导入的文件是数组的
4 const file = files[0]; // only use files[0]
5 if (!file) return;
6
7 console.log('导入的文件:' + file.name);
8 this.Excelfile_reader_file(file);
9 }
读取文件
读取文件是异步的。直接上代码:
1 // 读取文件,是个异步的
2 Excelfile_reader_file(rawFile) {
3 return new Promise((resolve, reject) => {
4 const reader = new FileReader();
5 reader.onload = e => {
6 const data = e.target.result
7 const workbook = XLSX.read(data, { type: 'array' });
8 // console.log('读取出的源表格数据');
9 // console.log(workbook);
10 const firstSheetName = workbook.SheetNames[0];
11 const worksheet = workbook.Sheets[firstSheetName];
12 const header = this.Excelfile_get_header_row(worksheet);// 第一行为标题栏
13 const results = XLSX.utils.sheet_to_json(worksheet);
14 this.file_excel.file_data.header = header;
15 this.file_excel.file_data.results = results;
16 // console.log('读取出的数据');
17 // console.log(this.file_excel.file_data);
18 resolve();
19 }
20 reader.readAsArrayBuffer(rawFile);
21 })
22 },
这是标题转化的函数,直接粘贴使用即可:
1 Excelfile_get_header_row(sheet) {
2 const headers = [];
3 const range = XLSX.utils.decode_range(sheet['!ref'])
4 let C;
5 const R = range.s.r;
6 /* start in the first row */
7 for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
8 const cell = sheet[XLSX.utils.encode_cell({
9 c: C,
10 r: R
11 })]
12 /* find the cell in the first row */
13 let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
14 if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
15 headers.push(hdr);
16 }
17 return headers;
18 }
这些足够了,其余没了……
来源:https://www.cnblogs.com/Romanticcat-Lin/p/12794280.html |