前端表格导出excel一般我们使用xlsx等插件导出,但如果想保留表格的样式导出的话,还需要再使用其他的插件才行,如要保留宽度、字体颜色、背景颜色等样式。
这里可以直接使用简短的 原生js方法即可导出带样式的excel文件。
直接上代码
/*原生表格导出 带样式 参数table是原生table的DOM元素 filename是文件名*/
export function tableToXlsx(table, filename) {
const uri = 'data:application/vnd.ms-excel;base64,',
template = `<html>
<head><meta charset="UTF-8"></head>
<body><table border="1">${table.innerHTML}</table></body>
</html>`;
const a = document.createElement('a');
a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
a.download = filename;
a.click();
document.removeChild(a);
}
使用场景
template
//ref的printRef用来获取dom
//Reconciliation 是需要打印的带有样式的组件
//isExport判断是否展示
//reconciliationData是传入的数据
//ref的printRef用来获取dom
//Reconciliation 是需要打印的带有样式的组件
//isExport判断是否展示
//reconciliationData是传入的数据
<template>
<div style="height: 65vh; overflow: auto" ref="printRef">
<Reconciliation :export="isExport" :content-data="reconciliationData"/>
</div>
<a-button type="primary" @click="exportSubmit">导出</a-button>
</template>
js引入
引入方法,将需要导出的table放到方法的第一个参数,这就是你需要导出的带样式的table
//引入方法,将需要导出的table放到方法的第一个参数
<script lang="ts" setup>
import { tableToXlsx } from '/@/components/Excel';
const printRef = ref();
const isExport = ref(false);
const exportSubmit = function () {
const time = moment().format('yyyyMMDDHHmmss');
isExport.value = true;
nextTick(() => {
tableToXlsx({
table: printRef.value.firstChild.querySelector('table'),
filename: '导出内容' + time + '.xlsx',
})
nextTick(() => {
isExport.value = false;
})
})
}
</script>
然后点击导出就可以了,导出内容就是带有样式的了