@
1、安装FileSaver和xlsx,在项目中使用
(1)导出按钮方法
async exportMethods() {
let that = this
let pageSize = 2000
// let Fields = {
// zdwbm: "单位组织编码",
// }
try {
const data = await this.queryData(1, 2000, {}, 'export');
this.downloadData = JSON.parse(JSON.stringify(data))
} catch (error) {
console.error('Error fetching data:', error);
}
},
(2)假设有1万条数据,每次最多请求2000条,循环获取所有数据
async queryData(pageNum, pageSize, { }, type) {
let res
let that = this
res = await this.getListDataByApi(pageNum, pageSize, {}, type)
var Data = []
Data = Array.from(Data).concat(res)
if (this.exportListTotal > pageNum * pageSize) {
var data = await this.queryData(++pageNum, pageSize, {}, type)
Data = Array.from(Data).concat(data)
}
return Data
},
(3)downloadData保存所有得数据,在watch中监听,方法如下
downloadData() {
let Fields = {}//需要导出的字段
this.tableHeader.forEach(item => {
Fields[item.key] = item.label
})
if (this.downloadData.length == 0 || this.downloadData[0] == undefined) return
var datas = this.DataInfo2(this.downloadData, Fields)
this.download(datas, "Sheet1", this.tabTitleValue)
},
(4)将处理后的数据使用安装的插件进行导出
/**export--------------start */
DataInfo2(datainfo, MapKey) {
var Datas = [];
if (datainfo.length == 0) return datainfo
for (var i = 0; i < datainfo.length; i++) {
var data = {};
var rowData = datainfo[i];
try {
for (let key in MapKey) {
if (MapKey) {
data[MapKey[key]] = (rowData[key] == undefined || rowData[key] == null) ? "" : rowData[key];
}
}
} catch (error) {
console.error('Error fetching data:', error);
}
Datas.push(data)
}
return Datas;
},
download(data, sheetName, xlsxName) {
var file = this.GetXlsxFile(data, sheetName, xlsxName)
FileSaver.saveAs(file, xlsxName + ".xlsx");
},
GetXlsxFile(data, sheetName = "Sheet1", xlsxName) {
// 创建一个新的工作簿
const workbook = XLSX.utils.book_new();
// 创建一个新的工作表
const worksheet = XLSX.utils.json_to_sheet(data);
console.log("worksheet", worksheet)
// 将工作表添加到工作簿
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
// 访问需要居中的单元格
const range = XLSX.utils.decode_range(worksheet['!ref']);
const style = {
alignment: {
horizontal: 'center', // 水平居中
vertical: 'center' // 垂直居中
}
};
const startCell = range.s; // 开始单元格
const endCell = range.e; // 结束单元格
// 遍历范围内的每个单元格,并应用样式
for (let row = startCell.r; row <= endCell.r; row++) {
for (let col = startCell.c; col <= endCell.c; col++) {
// 获取单元格
const cell = worksheet[XLSX.utils.encode_cell({ r: row, c: col })];
// 设置单元格样式
}
}
// 将样式应用于单元格
const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
const fileData = new Blob([excelBuffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
// 生成文件对象
const file = new File([fileData], xlsxName + ".xlsx", { type: fileData.type });
return file;
},
/**export-------------- end */