在使用 ruoyi-vue-pro 开发中,导出为 Excel 时通常让后端实现。
由于表格数据是统计使用,前端做了数据处理,因此,再使用后端导出就不方便了。
这里介绍如何使用前端方式来导出 Excel 文件。
1、安装 xlsx 库
npm install xlsx
2、编写函数保存至:\src\utils\htmlToExcel.ts
export const htmlToExcel = {
getExcel(dom: string, title: string = 'temp') {
const excelTitle = title;
import('xlsx').then((XLSX) => {
const wb = XLSX.utils.table_to_book(document.querySelector(dom), {raw: true});
try {
XLSX.writeFile(wb, excelTitle + '.xlsx');
} catch (e) {
if (typeof console !== 'undefined') {
console.log(e);
console.log('导出失败!');
}
}
}).catch((error) => {
console.error('Failed to load xlsx module', error);
});
},
};
3、使用时,页面中引入 htmlToExcel
import { htmlToExcel } from '@/utils/htmlToExcel'4、在 el-table 中增加 id 属性
<el-table
id="contrScoreNumListElem"
v-loading="loading"
:data="contrScoreNumList"
:stripe="true"
:show-overflow-tooltip="true"
>
</el-table>5、增加导出按钮
<el-form-item>
<el-button type="success" plain @click="handleExport">
<Icon icon="ep:download" /> 导出
</el-button>
</el-form-item>6、增加导出按钮方法
const handleExport = async () => {
htmlToExcel.getExcel('#contrScoreNumListElem, contrScoreNumList.value)
}