Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端解析excel文件 #45

Open
0fengzi0 opened this issue Sep 17, 2021 · 0 comments
Open

前端解析excel文件 #45

0fengzi0 opened this issue Sep 17, 2021 · 0 comments

Comments

@0fengzi0
Copy link
Owner

首先安装xlsx依赖

yarn add xlsx

vue文件中引入xlsx依赖

import XLSX from "xlsx";

通过某种方式获得excel文件(以浏览器上传为例子)

vue

<input id="chooseFile" ref="inputFile"
               style="display: none"
               type="file"
               @change="chooseFile"/>	

js

chooseFile(e) {
    // 上传文件可能是多个,获取上传文件数组的第一个文件
    const file = e.target.files[0];

    // 定义需要的文件类型
    const types = ["xls", "xlsx"];
    // 按点分割上传文件的名字
    const arr = file.name.split(".");
    //判断文件是否为excel文件
    if (!types.find(item => item === arr[arr.length - 1])) {
        // 这里可以进行弹窗提醒,告知文件类型错误

        return;
    }

    // 开始解析excel
    const reader = new FileReader();
    reader.onload = e => {
        let data = new Uint8Array(e.target.result);
        let workbook = XLSX.read(data, {type: 'array'});

        // 将excel文件中第一个数据表的数据转为json格式,如果需要从某一个行开始的数据,可以修改sheet_to_json的第二个参数
        let workbookData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
        // workbookData 就是excel的数据
        console.log(workbookData)

    };
    reader.readAsArrayBuffer(file);

    // 解决上传同名文件后无法触发@change事件
    this.$refs.inputFile.value = null;

        },

将数据转为excel文件下载下来

// 设置需要保存的数据内容
let tableData = [
    ['名称', '规格', '售价'],
    ['aaa', '个', '13'],
    ['bbb', '个', '13'],
    ['ccc', '个', '13'],
];

// 创建新的workbook
let wb = XLSX.utils.book_new()
// 根据传入的二维数组,生成包含对应内容的worksheet
let ws = XLSX.utils.aoa_to_sheet(tableData);

// 将worksheet添加进workbook,并指定worksheetd的名字
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

// 下载生成的excel文件
XLSX.writeFile(wb, "下载文件.xlsx");

参考文档

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant