vue 导出csv文件

2022-05-17  本文已影响0人  木火应
<template>
    <div>
      <div @click="downCsv" class="button">导出</div>
    </div>
</template>
<script>
import json2csv from "json2csv"
export default {
  data(){
    return {
        list:[
        ]
    }
  },
  created(){
    for(let i = 0;i<10000;i++){
      // 测试数据
      this.list.push({name:"木火应",age:i})
    }    
  },
  methods:{
    downCsv(){
        const csv = json2csv.parse(this.list, {
          // fields: fields,
          excelStrings: true
        });
        if (this.MyBrowserIsIE()) {
            var BOM = "\uFEFF";
              // 文件转Blob格式
            var csvData = new Blob([BOM + csv], { type: "text/csv" });
            navigator.msSaveBlob(csvData, `123.csv`);
        }else{
            let csvContent = "data:text/csv;charset=utf-8,\uFEFF" + csv;
            // 非ie 浏览器
            this.createDownLoadClick(csvContent, `123.csv`);
        }
    },
    MyBrowserIsIE() {
        let isIE = false;
        if (
          navigator.userAgent.indexOf("compatible") > -1 &&
          navigator.userAgent.indexOf("MSIE") > -1
        ) {
          // ie浏览器
          isIE = true;
        }
        if (navigator.userAgent.indexOf("Trident") > -1) {
          // edge 浏览器
          isIE = true;
        }
        return isIE;
  },
    //创建a标签下载
    createDownLoadClick(content, fileName) {
      const link = document.createElement("a");
      link.href = encodeURI(content);
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }
}
</script>
<style scoped>
  .button{
    cursor: pointer;
    width: 10%;
    border: 1px red solid;
  }
</style>
上一篇下一篇

猜你喜欢

热点阅读