前端支持上传下载csv文件

npm install papaparse

import Papa from 'papaparse'

// 上传
handleFileChange (e) {
      const input = e.target
      const file = input.files[0]
      if (file) {
        Papa.parse(file, {
          encoding: 'utf-8',
          complete: result => {
            const data = result.data
            for (let i = 0; i < data.length; i++) {
              const row = data[i]
              for (let j = 0; j < row.length; j++) {
                const item = data[i][j]
                data[i][j] = String(item).replace(/\s+/g, '')
              }
            }
            const titles = data[0]
            const props = data[1]
            const columns = titles.map((x, i) => {
              return {
                property: props[i],
                title: `${titles[i]}(${props[i]})`
              }
            })
            const list = data.slice(2).map(row => {
              const tmp = {}
              row.forEach((x, i) => {
                tmp[props[i]] = x
              })
              return tmp
            }).filter(x => {
              return Object.keys(x).some(k => !!x[k])
            })
            this.importInfo = { columns, list }
            this.showImportData = true
          }
        })
      } else {
        this.$message.warning('文件读取失败')
      }
      input.value = ''
    }
// 下载
handleDownload () {
      if (this.tableName) {
        this.exporting = true
        this.$http
          .post(api.getDataList, {
            table_name: this.tableName,
            page_num: 1,
            page_size: 10 ** 6
          })
          .then(res => {
            const data = res.result.data || []
            const name = `${(this.tableListOrigin.find(x => x.table_name === this.tableName) || {}).text || 'file'}.csv`
            const columns = this.columns.filter(x => x.property !== 'operation')
            const item = columns.reduce((pre, curr) => {
              pre[curr.property] = curr.property
              return pre
            }, {})
            data.unshift(item)
            saveFile(generateCSV(data, { columns }), name)
          })
          .finally(() => {
            this.exporting = false
          })
      } else {
        this.$message.warning('请先选择一张表。')
      }
    }
posted @ 2020-08-05 15:05  奇德隆咚强  阅读(427)  评论(0)    收藏  举报