表格导出
根据表格的ref来返回导出excel所需参数
export const getTableExcelOpts = (page, refName) => { const data = [] const tHeader = [] // table Header const secondTHeader = [] // 二级表头 const mergeHeader = [] // 一级、二级表头 merge 规则 const filterVal = [] // 列对应属性 const singleHeader = [] const ref = page && refName && page.$refs && page.$refs[refName] let childrenNode = [] if (ref) { if (Array.isArray(ref)) { childrenNode = ref[0] ? (ref[0].$children || []) : [] } else { childrenNode = ref.$children || [] } } let totalIdx = 0 let needMerge = false childrenNode.filter(el => el && el.label && el.type !== 'index' && el.type !== 'operation').forEach((el, idx) => { const children = el.$children || [] const childrenLen = children.length || 0 tHeader.push(el.label) secondTHeader.push(childrenLen > 0 ? children[0].label : '') mergeHeader.push({ s: { r: 0, c: totalIdx }, e: { r: childrenLen > 0 ? 0 : 1, c: childrenLen > 0 ? (totalIdx + childrenLen - 1) : totalIdx } }) if (childrenLen > 0) { needMerge = true filterVal.push(children[0].prop) if (childrenLen > 1) { children.filter((cEl, cIdx) => cIdx > 0).forEach(cEl => { tHeader.push('') secondTHeader.push(cEl.label) filterVal.push(cEl.prop) }) } children.forEach(cEl => { const pLabel = el.label || '' if (pLabel && pLabel.indexOf('/万元') > -1) { singleHeader.push(pLabel.replace('/万元') + '' + cEl.label) } else if (pLabel && pLabel.indexOf('/万') > -1) { singleHeader.push(pLabel.replace('/万', '') + '' + cEl.label + '/万') } else { singleHeader.push(pLabel + '' + cEl.label) } }) } else { filterVal.push(el.prop) singleHeader.push(el.label) } totalIdx += childrenLen || 1 }) if (needMerge) { data.unshift(secondTHeader) } return { filterVal: filterVal || [], singleHeader: singleHeader || [], excelOpts: { header: tHeader, data, autoWidth: true, bookType: 'xlsx', merges: needMerge ? mergeHeader : {} } } }
export const exportExcel = (self, ref, dataList, fileName, extra = [], beforeheaderInfo) => { // 获取列表结构数据 const opts = getTableExcelOpts(self, ref) const excelOpts = opts.excelOpts || {} const extraFilterVal = extra.map(col => { return col.value }) // 额外导出列字段 const extraHeader = extra.map(col => { return col.label }) // 额外导出列名称 const filterVal = [...opts.filterVal || [], ...extraFilterVal] excelOpts.header = [...excelOpts.header, ...extraHeader] const data = excelOpts.data || [] import('../Export2Excel.js').then(excel => { dataList.forEach(v => { const d = filterVal.map(j => { let val = v[j] return (typeof (val) === 'undefined') ? null : val }) data.push(d) }) const style = { alignment: { wrapText: 1, // 自动换行 vertical: 'center', horizontal: 'center' } } excel.export_json_to_excel({ ...excelOpts, filename: fileName, maxWidth: 50, data, style, beforeheaderInfo }) }).catch((err) => { self.ErrorMessage(err, '导出失败') }) }