在components组件中新建 tableReport.vue 文件
<template>
<!-- 导出表格 -->
<el-dropdown class="export-btns">
<el-button type="success">数据导出</el-button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item @click="handleExport('current')"><el-icon class="el-icon--left">
<document />
</el-icon>导出当前页</el-dropdown-item>
<el-dropdown-item @click="handleExport('all')"><el-icon class="el-icon--left">
<document />
</el-icon>导出所有</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</template>
<script setup lang="ts">
import CsvExport from "@/utils/CsvExport";
import { onMounted } from 'vue'
// 接受父组件传递的数据
const props = defineProps({
// 表格所有数据
allTable: {
type: Array,
default: []
},
// 表格当页数据
viewTable: {
type: Array,
default: []
},
// 对应表头数据内容
tableDate: {
type: Array,
default: []
}
})
let tableItem: any = []
let allTableDate: any = []
let viewTableDate: any = []
onMounted(() => {
setTimeout(() => {
getTableItem()
allTableDate = props.allTable
viewTableDate = props.viewTable
}, 500)
})
const getTableItem = () => {
tableItem = props.tableDate.map((item: any) => {
return {
prop: item.prop,
label: item.label
}
})
}
const handleExport = (target: any) => {
const timestamp: any = new Date().valueOf();
const exportData =
target === "current" ? viewTableDate : allTableDate;
CsvExport(
exportData,
tableItem
,
`ecom-export-users-${target === "current" ? "current" : "all"}-${timestamp}`
);
};
</script>
<style scoped></style>
CsvExport 文件
const { Parser } = require("json2csv");
interface IColumn {
prop: string;
label?: string;
formatter?: (row: any, column: IColumn, cellValue: any) => any;
}
function GetRow(row: any, columns: IColumn[]): any {
let obj: any = {};
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) => {
return { value: t.prop, label: t.label };
});
try {
const json2csvParser = new Parser({ fields });
const result = json2csvParser.parse(rows);
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);
}
}