前言:最近遇到一个需求,需要实现一个下载表格数据的操作,一般来说是前端请求后端的下载接口,将文件流下载下来,但是因为这个项目任务时间比较紧,后端没时间做下载接口,所以暂时由前端直接调列表的git接口,把后端传给我们的数组直接下载成csv文件,情况如下图:
实现步骤:
1、先在util文件夹下新增一个js文件:Export2Csv.js,放转csv的插件代码:
function processRow(row) {let finalVal = ''for (let j = 0; j < row.length; j++) {let innerValue = row[j] === null ? '' : row[j].toString()if (row[j] instanceof Date) {innerValue = row[j].toLocaleString()}let result = innerValue.replace(/"/g, '""')if (result.search(/("|,|\n)/g) >= 0) { result = '"' + result + '"' }if (j > 0) { finalVal += ',' }finalVal += result}return finalVal + '\n'
}export function exportToCsv(filename, rows) {let csvFile = ''for (let i = 0; i < rows.length; i++) {csvFile += processRow(rows[i])}// 添加\ufeff头,标识excel可以打开UTF8编码的文件const blob = new Blob(['\ufeff', csvFile], { type: 'text/csv;charset=utf-8;' })if (navigator.msSaveBlob) { // IE 10+navigator.msSaveBlob(blob, filename)} else {const link = document.createElement('a')if (link.download !== undefined) { // feature detection// Browsers that support HTML5 download attributeconst url = URL.createObjectURL(blob)link.setAttribute('href', url)link.setAttribute('download', filename)link.style.visibility = 'hidden'document.body.appendChild(link)link.click()document.body.removeChild(link)}}
}export function exportDictArray2csv(data, filename) {const keys = Object.keys(data[0])const rows = []// writer headerrows.push(keys)data.forEach(dict => {const row = []keys.forEach(key => {row.push(dict[key])})rows.push(row)})exportToCsv(filename, rows)
}export default exportDictArray2csv
2、在需要用的页面引入
import { exportDictArray2csv } from "@/utils/Export2Csv.js";
3、使用
const filename = `data.csv`;
exportDictArray2csv(tableData.value, filename);
filename就是下载的文件名,可以自己自定义
tableData.value就是接口传给我们的数据
tableData.value的数据格式:
[{aaa:1,bbb:2},{aaa:3,bbb:4}]
下载下来的csv文件:
aaa | bbb |
1 | 2 |
3 | 4 |