//导出指定列的excel数据
|
import { ElMessage } from 'element-plus';
|
// import XLSX from 'xlsx';
|
import XLSXS from 'xlsx-js-style';
|
|
export function exportExcel(dataSource: any[], entozh: any={}, type = "xlsx", name = "全部信息") {
|
const nowdata = dataSource;
|
if (nowdata != undefined) {
|
// let i = 1;
|
// const json = nowdata.map((item: { [x: string]: any; }) => {
|
// return Object.keys(item).reduce((newData, key) => {
|
// const newKey = entozh[key] //|| key
|
// if (newKey !== undefined) {
|
// if (key !== 'key') {
|
// //不需要key
|
// if (key === 'id') {
|
// newData[newKey] = i;
|
// i++;
|
// } else {
|
// newData[newKey] = item[key]
|
// }
|
// }
|
// }
|
// return newData
|
// }, {})
|
// });
|
// // debugger;
|
// console.log(json,'1111')
|
// const sheet = XLSXS.utils.json_to_sheet(json);
|
// openDownloadDialog(sheet2blob(sheet, undefined, type), `${name}.${type}`);
|
const keysArr: string[] = Object.keys(entozh)
|
const aoa = [];
|
|
const headerArr: any[] = [];
|
keysArr.forEach(item => {
|
if(item != 'id') {
|
headerArr.push(entozh[item])
|
}
|
})
|
const contentArr: any[][] = [];
|
nowdata.forEach(item => {
|
const arr: any[] = [];
|
keysArr.forEach(key => {
|
if(key != 'id') {
|
arr.push(item[key])
|
}
|
})
|
contentArr.push(arr)
|
})
|
aoa.push(headerArr,...contentArr)
|
// console.log(aoa)
|
const worksheet = XLSXS.utils.aoa_to_sheet(aoa)
|
openDownloadDialog(sheet2blob(worksheet, undefined, type), `${name}.${type}`);
|
// XLSXS.utils.book_append_sheet(workbook,worksheet,`${name}.${type}`)
|
|
} else {
|
ElMessage.warning('无数据')
|
}
|
|
}
|
|
export function openDownloadDialog(url: string | any, saveName: string) {
|
if (typeof url == 'object' && url instanceof Blob) {
|
url = URL.createObjectURL(url); // 创建blob地址
|
}
|
const aLink = document.createElement('a');
|
aLink.href = url;
|
aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
|
let event;
|
if (window.MouseEvent) event = new MouseEvent('click');
|
else {
|
event = document.createEvent('MouseEvents');
|
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
|
}
|
aLink.dispatchEvent(event);
|
}
|
|
export function sheet2blob(sheet: XLSXS.WorkSheet, sheetName: string | undefined, type = "xlsx") {
|
sheetName = sheetName || 'sheet1';
|
const workbook = {
|
SheetNames: [sheetName],
|
Sheets: {}
|
};
|
workbook.Sheets[sheetName] = sheet; // 生成excel的配置项
|
|
const wopts: any = {
|
bookType: `${type}`, // 要生成的文件类型
|
bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
|
type: 'binary'
|
};
|
|
const wbout = XLSXS.write(workbook, wopts);
|
const blob = new Blob([s2ab(wbout)], {
|
type: "application/octet-stream"
|
}); // 字符串转ArrayBuffer
|
function s2ab(s: string) {
|
const buf = new ArrayBuffer(s.length);
|
const view = new Uint8Array(buf);
|
for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
|
return buf;
|
}
|
|
return blob;
|
}
|