本文主要是介绍vue使用Export2Excel导出表格,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
安装插件
npm install xlsx xlsx-style file-saver
npm install node-polyfill-webpack-plugin (如果不安装的话后面使用会报错)
添加相关配置
在vue.config.js文件
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
module.exports = defineConfig({configureWebpack: {resolve: {fallback: { fs: false},},externals: {'./cptable': 'var cptable'},plugins: [new NodePolyfillPlugin()]},
})
封装公共方法
Export2Excel.js
import * as XLSX from 'xlsx'
import * as XLSXStyle from 'xlsx-style'
import { saveAs } from 'file-saver'
// 根据dom导出表格
export function exportToExcel(idSelector, fileName, titleNum = 1) {// 设置导出的内容是否只做解析,不进行格式转换 false:要解析, true:不解析const xlsxParam = { raw: true }let table = document.querySelector(idSelector).cloneNode(true);// 因为element-ui的表格的fixed属性导致多出一个table,会下载重复内容,这里删除掉if (table.querySelector('.el-table__fixed-right'))table.removeChild(table.querySelector('.el-table__fixed-right'));if (table.querySelector('.el-table__fixed'))table.removeChild(table.querySelector('.el-table__fixed'));const wb = XLSX.utils.table_to_book(table, xlsxParam)let range = XLSX.utils.decode_range(wb.Sheets['Sheet1']['!ref']);let cWidth = [];for (let C = range.s.c; C < range.e.c; ++C) { //SHEET列let len = 100; //默认列宽let len_max = 400; //最大列宽for (let R = range.s.r; R <= range.e.r; ++R) { //SHEET行let cell = { c: C, r: R }; //二维 列行确定一个单元格let cell_ref = XLSX.utils.encode_cell(cell); //单元格 A1、A2if (wb.Sheets['Sheet1'][cell_ref]) {// if (R == 0){if (R < titleNum) {wb.Sheets['Sheet1'][cell_ref].s = { //设置第一行单元格的样式 stylealignment: {horizontal: 'center',vertical: 'center',},};} else {wb.Sheets['Sheet1'][cell_ref].s = {alignment: {horizontal: 'center',vertical: 'center',},};}//动态自适应:计算列宽let va = JSON.parse(JSON.stringify(wb.Sheets['Sheet1'][cell_ref].v));var card1 = JSON.parse(JSON.stringify(va)).match(/[\u4e00-\u9fa5]/g); //匹配中文var card11 = "";if (card1) {card11 = card1.join("")}var card2 = JSON.parse(JSON.stringify(va)).replace(/([^\u0000-\u00FF])/g, ""); //剔除中文let st = 0;if (card11) {// st += card11.length * 16 //中文字节码长度st += card11.length * 20 //中文字节码长度}if (card2) {// st += card2.length * 8 //非中文字节码长度st += card2.length * 10 //非中文字节码长度}if (st > len) {len = st;}}}if (len > len_max) {//最大宽度len = len_max;}cWidth.push({ 'wpx': len }); //列宽}wb.Sheets['Sheet1']['!cols'] = cWidthconst wbout = XLSXStyle.write(wb, { bookType: 'xlsx', bookSST: false, type: 'binary' })try {saveAs(new Blob([s2ab(wbout)], { type: 'text/plain;charset=utf-8' }), `${fileName}.xlsx`)} catch (e) {if (typeof console !== 'undefined') {console.log(e, wbout)}}return wbout
}
function s2ab(s) {var buf = new ArrayBuffer(s.length);var view = new Uint8Array(buf);for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;return buf;
}
使用
import { exportToExcel } from '@/utils/Export2Excel'
handelExport() {// 给el-table组件添加id="table"exportToExcel('#table', '应用日志')
},
这篇关于vue使用Export2Excel导出表格的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!