1.下载插件:

npm install xlsx --save

2.在需要使用的页面引入:

import { read, utils } from 'xlsx';

3.使用elementUI中的el-upload组件实现:

<el-upload
	:before-upload="upload"
    class="upload-demo"
    accept=".xlsx,.xls"
    :show-file-list="false"
    drag
	action="https://jsonplaceholder.typicode.com/posts/"
    multiple
>
	<i class="el-icon-upload"></i>
    <div class="el-upload__text">
    	将文件拖到此处,或
        <em>点击上传</em>
    </div>
</el-upload>

4.上传后的函数:

upload(file, fileList) {
	let files = { 0: file };
    this.readExcel1(files);
},
readExcel1(files) {
	// 如果没有文件名
    if (files.length <= 0) {
    	return;
    }
    if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$message.error('上传格式不正确,请上传xls或者xlsx格式');
        return;
     }
     const fileReader = new FileReader();
     fileReader.onload = ev => {
     	try {
        	const data = ev.target.result;
            const workbook = read(data, {
            	type: 'binary',
            });
            // 取第一张表
            const wsname = workbook.SheetNames[0];
            // 生成json表格内容
            const ws = utils.sheet_to_json(workbook.Sheets[wsname]);
            console.log(ws);
            // 后续数据的处理
            
         } catch (e) {
         	return false;
         }
    };
	fileReader.readAsBinaryString(files[0]);
},

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐