vue 导出Excel/zip

1 安装依赖 

npm i jszip -S  //安装zip

  

npm install -S file-saver xlsx

npm install -D script-loader  

2 再项目中创建文件夹 src 下创建(vendor)

 

放入 两个文件 里面放置两个文件Blob.js和 Export2Excel.js

Export2Zip.js (zip)

 

3. 导入 export2Excel,

  

再build 文件夹下 webpack.base.conf.js

  

'vendor': path.resolve(__dirname, '../src/vendor')

 4. 调用

  

导出excel

zip_down(){
        this.downloadLoading = true
        require.ensure([], () => {
          const { export_json_to_excel } = require('@/vendor/Export2Excel')
          const tHeader = ['序号']
          const filterVal = ['name']
          const list = this.tableData   //导入数据
          const data = this.formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '列表文本', '压缩文本')
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      }

  

导出 zip

 

 

zip_down(){
        this.downloadLoading = true
        require.ensure([], () => {
          const { export_txt_to_zip } = require('@/vendor/Export2Zip')
          const tHeader = ['序号']
          const filterVal = ['name']
          const list = this.tableData
          const data = this.formatJson(filterVal, list)
          export_txt_to_zip(tHeader, data, '列表文本', '压缩文本')
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      }

  

Export2Zip.js 文件

/* eslint-disable */
require('script-loader!file-saver');

import JSZip from 'jszip'

export function export_txt_to_zip(th, jsonData, txtName, zipName) {
  const zip = new JSZip()
  const txt_name = txtName || '文本'
  const zip_name = zipName || '压缩包'
  const data = jsonData
  let txtData = `${th}\r\n`
  data.forEach((row) => {
    let tempStr = ''
    tempStr = row.toString()
    txtData += `${tempStr}\r\n`
  })
  zip.file(`${txt_name}.txt`, txtData)
  zip.generateAsync({type:"blob"}).then((blob) => {
    saveAs(blob, `${zip_name}.zip`)
  }, (err) => {
    alert('导出失败')
  })
}

 

 

 

posted @ 2017-12-01 11:22  野紫  阅读(5679)  评论(2编辑  收藏  举报