溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue怎么實現(xiàn)二進制流文件導(dǎo)出excel

發(fā)布時間:2022-06-02 14:13:43 來源:億速云 閱讀:683 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“vue怎么實現(xiàn)二進制流文件導(dǎo)出excel”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“vue怎么實現(xiàn)二進制流文件導(dǎo)出excel”吧!

vue二進制流文件導(dǎo)出excel

問了一下其他的后端,他們公司前端是a標簽,后端是給了一個地址,a標簽或者window.open()都可以實現(xiàn)。

我們公司是后端返回的二進制流文件,實現(xiàn)了一下,親測可以,沒有問題

vue怎么實現(xiàn)二進制流文件導(dǎo)出excel

前端代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="btn">下載</button>
    <!-- yarn add axios -->
    <script src="node_modules/axios/dist/axios.min.js"></script>
    <script>
        const btn = document.getElementById("btn");
        btn.onclick = function () {
            axios({
                method: "post",
                url: "http://localhost:3000/download",
                data: {
                    // test: "test data",
                },
                responseType: 'blob' //返回類型
            }).then((res) => {
                let name = '合格率' //注意這里不可以再加.xlsx了,函數(shù)中已經(jīng)封裝了
                createExcel(res.data, name) //這里就直接這樣調(diào)用方法就行了
            });
        }
        // vue中可以寫方法 然后再暴露出去
        function createExcel(res, name) {
            let blob = new Blob([res], {
                type: 'application/vnd.ms-excel'
            })
            let fileName = name + '.xlsx'
            // 允許用戶在客戶端上保存文件
            if (window.navigator.msSaveOrOpenBlob) { 
                navigator.msSaveBlob(blob, fileName)
            } else {
                var link = document.createElement('a')
                link.href = window.URL.createObjectURL(blob)
                link.download = fileName
                link.click()
                //釋放內(nèi)存
                window.URL.revokeObjectURL(link.href)
            }
        }
        // 1.msSaveBlob:只提供一個保存按鈕
        //window.navigator.msSaveBlob(blobObject, 'msSaveBlob_testFile.txt');
        // 2.msSaveOrOpenBlob:提供保存和打開按鈕
        // window.navigator.msSaveOrOpenBlob(blobObject, 'msSaveBlobOrOpenBlob_testFile.txt');
    </script>
</html>

后端node

const http = require("http");
const fs = require("fs");
const server = http.createServer((req, res) => {
  if (req.url === "/download") {
    res.writeHead(200, {
      "Content-type": "application/vnd.ms-excel", // 返回 excel
      // 跨域設(shè)置
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers": "content-type",
    });
    // 異步讀取文件內(nèi)容  這里新建了一個test.xlsx的excel
    fs.readFile("test.xlsx", (err, data) => {
      // 返回二進制文件流
      res.end(data);
    });
  }
});
server.listen(3000, () => {
  console.log("好厲害,3000的服務(wù)器起來了");
});

關(guān)于二進制文件流導(dǎo)出Excel文件的一些坑

實現(xiàn)下載效果

vue怎么實現(xiàn)二進制流文件導(dǎo)出excel

<el-button type="warning" icon="el-icon-download" size="mini" @click="download()">導(dǎo)出</el-button>
 //下載操作
        download() {
            return axios({
                url: '/download/sms',
                method: 'post',
                data: this.queryForm,
                responseType: 'blob',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
                .then(res => {
                    console.log(res, '返回數(shù)據(jù)列');
                    const blob = new Blob([res.data], {
                        type: 'application/vnd.ms-excel'
                    });
                    console.log(blob, '----------0990');
                    const fileName = '短信列表.xls';
                    const linkNode = document.createElement('a');
                    linkNode.download = fileName; //a標簽的download屬性規(guī)定下載文件的名稱
                    linkNode.style.display = 'none';
                    linkNode.href = URL.createObjectURL(blob); //生成一個Blob URL
                    document.body.appendChild(linkNode);
                    linkNode.click(); //模擬在按鈕上的一次鼠標單擊
                    URL.revokeObjectURL(linkNode.href); // 釋放URL 對象
                    document.body.removeChild(linkNode);
                })
                .catch((err) => {
                    console.log(err);
                });
                return res;
        },

踩坑

1、剛開始看網(wǎng)上說需要axios原生才能請求,然后就引入了axios之后但是一直報錯,導(dǎo)致download的then代碼無法執(zhí)行,直接走catch,輸出錯誤

vue怎么實現(xiàn)二進制流文件導(dǎo)出excel

研究了半天才發(fā)現(xiàn)是blob返回沒有code,也沒有message,而我在攔截器中直接設(shè)置了code的判斷攔截,所以導(dǎo)致請求一直報錯

vue怎么實現(xiàn)二進制流文件導(dǎo)出excel

2、在發(fā)送請求時必須要加上responseType: &lsquo;blob&rsquo;,不然導(dǎo)出的文件是亂碼格式的

3、在then里面定義的blob new出來的數(shù)據(jù)需要再走一層,而不是直接輸出

vue怎么實現(xiàn)二進制流文件導(dǎo)出excel

到此,相信大家對“vue怎么實現(xiàn)二進制流文件導(dǎo)出excel”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI