效果
<a-button
size="default"
style="margin-left: 10px"
@click="exportData"
>导出</a-button
>
1.下载所需依赖
npm install xlsx --save
npm install file-saver --save
<script setup>
import { reactive, ref } from "vue";
//导入依赖
import * as XLSX from "xlsx/xlsx.mjs";
import { saveAs } from "file-saver";
import { message } from "ant-design-vue";
//导出
const exportData = () => {
queryAllData();
};
//导出查询的所有数据
const queryAllData = async() => {
const hide = message.loading('下载中', 0);
//模拟要导出的数据
let dataList = [{
commodityName: "名称",
classifyName: "分类",
operationType: "STOCK",
operationNum: "13",
currentNum: "34",
remarks: "备注",
operator: "操作人",
createTime: "2012-12-12 12:12:12",
}];
dataList.forEach(item => {
item.operationType = item.operationType == 'STOCK' ? '入库' : '出库';
})
console.log('要导出的数据', dataList)
// 定义表头数据
let head = {
commodityName: "商品名称",
classifyName: "商品分组",
operationType: "操作",
operationNum: "操作数量",
currentNum: "剩余库存",
remarks: "备注",
operator: "操作人",
createTime: "操作时间",
};
if (dataList.length > 0) {
// 准备表头数据
const headers = ['商品名称', '商品分组', '操作', '操作数量', '剩余库存', '备注', '操作人', '操作时间'];
exportDataMethods(head, dataList, true, 7, '库存明细导出', headers)
} else {
message.warning('暂无数据导出!')
}
}
//表格数据导出
//timeCel要转换时间,时间所在的列数 timeConversion是否要转换时间
//head 自定义表头 tableData:表格数据
//headers 自定义表头排序
const exportDataMethods = (head, tableData, timeConversion, timeCel, fileName, headers) => {
const hide = message.loading('导出中...', 0);
console.log(head, tableData, timeConversion, timeCel)
let timecel = timeCel ? timeCel : '';
let filename = fileName ? fileName : 'Excel';
let cols = [];
//表头数据切换
let list = tableData.map((item) => {
cols.push({ wch: 20 })
const obj = {};
for (const k in item) {
if (head[k]) {
obj[head[k]] = item[k];
}
}
return obj;
});
// 创建一个工作表
const ws = XLSX.utils.json_to_sheet(list, {
header: headers, // 使用新的表头顺序
});
const range = XLSX.utils.decode_range(ws['!ref']);
if (timeConversion) {
// 将时间戳列转换为日期字符串
ws['!cols'] = cols;
// 将时间戳列转换成日期格式
for (let i = 1; i <= range.e.r; i++) {
// const cell = 'D' + i;
const cell = XLSX.utils.encode_cell({ r: i, c: timecel }); // 时间戳所在的列
ws[cell].t = 's';
ws[cell].v = formatDate(ws[cell].v * 1);
// ws[cell].v = XLSX.SSF.format('yyyy-mm-dd hh:mm:ss', new Date(ws[cell].v));
}
}
console.log('导出表格', ws)
// 创建一个工作簿
const wb = XLSX.utils.book_new();
// 将工作表添加到工作簿中
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
// 将工作簿转换成二进制数据
const wbData = XLSX.write(wb, { bookType: "xlsx", type: "array" });
// 创建一个 Blob 对象
const blob = new Blob([wbData], { type: "application/octet-stream" });
// 下载文件
saveAs(blob, fileName + ".xlsx");
setTimeout(hide, 2500);
}
const formatDate = (value, str) => {
let date = new Date(value);
if (str) {
date = moment(date).format("YYYY年MM月DD日 HH:mm:ss");
} else {
date = moment(date).format("YYYY-MM-DD HH:mm:ss");
}
return date;
}
</script>