Vue achieve csv file export function

npm install papaparse

In the page you want to use to introduce:

import Papa from "papaparse"

 

    <i-button type="primary" @click="download">文件转换下载</i-button>
 methods: {
    download (csv) {
      if (!csv) {
        return;
      }
      console.log("downLoad");
      var csv = Papa.unparse(this.itemList);
      console.log("downLoad", csv);
      //定义文件内容,类型必须为Blob 否则createObjectURL会报错
      let content = new Blob([csv], {
        type:
          'text/plain;charset=utf-8;'
        // application/vnd.openxmlformats-officedocument.wordprocessingml.document;
      });
      //生成url对象
      let urlObject = window.URL || window.webkitURL || window;
      let url = urlObject.createObjectURL(content);
      //生成<a></a>DOM元素
      let el = document.createElement("a");
      //链接赋值
      el.href = url;
      el.download = "todo文件导出.csv";
      //必须点击否则不会下载
      el.click();
      //移除链接释放资源
      urlObject.revokeObjectURL(url);
    },
}

But there is a bug, file content will be messy, to be resolved in 

Published 98 original articles · won praise 4 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_42416812/article/details/101446591