vue.js element ui table export csv/xlsx

CsvExport.ts

import json2csv from 'json2csv'

interface IColumn {
  prop: string
  label?: string
  formatter?: (row: any, column: IColumn, cellValue: any) => any;
}

function GetRow(row: any, columns: IColumn[]): any {
  let obj = {}

  columns.forEach(col => {
    let val = row[col.prop]

    if (col.formatter) {
      val = col.formatter(row, col, val)
    }

    obj[col.prop] = val
  })

  return obj
}

export default function ExportCsv(data: any[], columns: IColumn[], fileName: string = 'file') {
  const rows = data.map(t => GetRow(t, columns))
  const fields = columns.map(t => t.prop)
  const fieldNames = columns.map(t => t.label)

  try {
    const result = json2csv({ data: rows, fields, fieldNames })
    const csvContent = 'data:text/csv;charset=GBK,\uFEFF' + result
    const link = document.createElement('a')
    link.href = encodeURI(csvContent)
    link.download = `${fileName}.csv`
    document.body.appendChild(link) // Required for FF
    link.click() // This will download the data file named 'my_data.csv'.
    document.body.removeChild(link) // Required for FF
  } catch (err) {
    // Errors are thrown for bad options, or if the data is empty and no fields are provided. 
    // Be sure to provide fields if it is possible that your data array will be empty. 
    console.error(err)
  }
}
import CsvExport from '@/utils/CsvExport.ts'

export default {
    //...
    methods: {
        exportCsv(filename = '列表') {
            const columns = this.$refs.table.$children.filter(t => t.prop != null)
            CsvExport(this.tableData, columns, filename)
        }
    },
    //...
}
import * as XLSX from "xlsx";

interface IColumn {
  prop: string;
  label: string;
  formatter?: (row: any, column: IColumn, cellValue: any) => any;
}

function GetRow(row: any, columns: IColumn[]) {
  const arr = [];

  columns.forEach(col => {
    let val = row[col.prop];

    if (col.formatter) {
      val = col.formatter(row, col, val);
    }

    arr.push(val);
  });

  return arr;
}

export default function CsvExport(
  data: any[],
  columns: IColumn[],
  fileName: string = "file1"
) {
  const rows = data.map(t => GetRow(t, columns));
  const fieldNames = columns.map(t => t.label);
  ExportExcel([fieldNames, ...rows], fileName);
}

function ExportExcel(rows: any[][], filename = "file1") {
  /* original data */
  const ws_name = "SheetJS";

  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.aoa_to_sheet(rows);

  /* add worksheet to workbook */
  XLSX.utils.book_append_sheet(wb, ws, ws_name);

  /* write workbook */
  XLSX.writeFile(wb, filename + ".xlsx");
}
    原文作者:Chobits
    原文地址: https://segmentfault.com/a/1190000008060543
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞