vue 上傳xlsx文件,讀取文件內(nèi)容,vue生成xlsx并下載

依賴文件 xlsx

npm install xlsx

詳細實現(xiàn)請見如下案例

<template>
    <div class='file'>
        <button class='file-btn' type='default' @click='fileXlsx'>上傳JC Number 獲取Approvers</button>
        <p>{{ fileName }}</p>
        <input class='uploadFile' type='file' @change='fileChange'>
    </div>
</template>

<script>
import { read, utils, writeFile } from 'xlsx';
import { getCandidateInfoByJCNumber } from '../../../api';

export default {
    name: 'FileXlsxGetApprovalers',
    data() {
        return {
            fileName: ''
        };
    },
    methods: {
        fileXlsx() {
            document.querySelector('.uploadFile').click();
        },
        fileChange(event) {
            if (!event.currentTarget.files.length) {
                return false;
            }
            // 拿取文件對象
            const file = event.target.files[0];
            // 顯示文件名
            this.fileName = file.name;
            // 用FileReader來讀取
            const reader = new FileReader();
            // 重寫FileReader上的readAsBinaryString方法
            const rABS = true;
            reader.onload = (e) => {
                let dataResult = e.target.result;
                if (!rABS) dataResult = new Uint8Array(dataResult);
                const workbook = read(dataResult, {
                    type: rABS ? 'binary' : 'array'
                });
                // 假設(shè)我們的數(shù)據(jù)在第一個標(biāo)簽
                const firstWorksheet = workbook.Sheets[workbook.SheetNames[0]];
                // XLSX自帶了一個工具把導(dǎo)入的數(shù)據(jù)轉(zhuǎn)成json
                const jsonArr = utils.sheet_to_json(firstWorksheet, { header: 1 });
                document.querySelector('.uploadFile').value = null;
                const data = jsonArr.map(item => item[0]);
                this.getJCNumberData(data);
            };
            if (rABS) reader.readAsBinaryString(file);
            else reader.readAsArrayBuffer(file);
            return false;
        },
        getJCNumberData(paramsArr) {
            const arr = [];
            paramsArr.forEach(item => {
                arr.push(getCandidateInfoByJCNumber({ id: item }));
            });
            // 將返回數(shù)據(jù)寫入xlsx并下載
            // eslint-disable-next-line compat/compat
            Promise.all(arr).then(res => {
                //res=[{name:'張三',age:18}]
                const ws=utils.json_to_sheet(res);
                const wb=utils.book_new();
                utils.book_append_sheet(wb,ws,'Approvers');
                writeFile(wb, "Approvers.xlsx");
            });
        }
    }
};
</script>

<style lang='less' scoped>
.file {
    padding-top: 30px;
}

.uploadFile {
    display: none;
}
</style>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容