VUE接收文件流并转换成Excel表格下载到本地

VUE接收文件流并转换成Excel表格下载到本地,

鄙人一直写的是Java,偶尔也谢谢VUE,像这样导出或者下载的功能经常要用到,分享给大家,希望在工作中能帮到大家。。。

一,声明一个button

<el-form-item>

            <el-button type="primary"  size="mini" @click="exportExcel">导出</el-button>

</el-form-item> 

二,定义exportExcel事件

exportExcel(){

              let data = Object.assign({},this.queryParam)

              this.$confirm('确定导出?','操作提示',{

                  confirmButtonText:'确定',

                  cancelButtonText:'取消',

                  type:'warning',

                  center:true

              }).then(()=>{

                this.$axios.post(this.$api.exporPersontExcel,data,{ responseType: "blob" }).then( (res) => { //$api.exporPersontExcel或者api文件的接口

                    let fileName="人员信息.xlsx"; //导出文件的名字

                    this.fileDownload(res,fileName);

                    this.$message({

                      message: '成功!',

                      type: 'success'

                    });

                })

              }).catch( err => {

                this.$message({

                  type: 'error',

                  message: '取消!'

                });

              })

            },

三,定义fileDownload

fileDownload(data, fileName) {

              let blob = new Blob([data], {

                type: "application/octet-stream"

              });

              let filename = fileName || "filename.xls";

              if(typeof window.navigator.msSaveBlob !== "undefined") {

                window.navigator.msSaveBlob(blob, filename);

              } else {

                var blobURL = window.URL.createObjectURL(blob);

                var tempLink = document.createElement("a");

                tempLink.style.display = "none";

                tempLink.href = blobURL;

                tempLink.setAttribute("download", filename);

                if(typeof tempLink.download === "undefined") {

                  tempLink.setAttribute("target", "_blank");

                }

                document.body.appendChild(tempLink);

                tempLink.click();

                document.body.removeChild(tempLink);

                window.URL.revokeObjectURL(blobURL);

              }

            },

很简单的三步,搞定

猜你喜欢

转载自blog.csdn.net/weixin_37999518/article/details/114951706
今日推荐