一、依赖导入
1、Vue2 + Webpack构建的
npm i xlsx
npm i xlsx-style
npm i file-saver
同时修改以下:
解决 Can’t resolve ‘./cptable’ in ‘…’ 的问题,在 vue.config.js 文件中加入该配置
module.exports = {
externals: {
'./cptable': 'var cptable'
}
}
2、Vue3 + Vite构建的
npm i xlsx
npm i xlsx-style-vite
二、导入项目
import * as XLSX from 'xlsx'
import * as XLSX_STYLE from 'xlsx-style' // Vue2 + Webpack
import * as XLSX_STYLE from 'xlsx-style-vite' // Vue3 + Vite
import FileSaver from 'file-saver' //保存下载
三、项目示例
const exportExcel = () => {
let table = [
// 表格表头
["能耗周期", '燃气消耗量(m³)', '水消耗量(m³)', "电消耗量(kwh)", "供热消耗量(m³)"]
];
state.tableData.forEach((item, index) => {
let rowData = [];
//导出内容的字段
rowData = [index + 1, item.date_month, item.zlconut, item.jscount]
table.push(rowData)
});
let bookNew = XLSX.utils.book_new();
let workSheet = XLSX.utils.aoa_to_sheet(table);
XLSX.utils.book_append_sheet(bookNew, workSheet, '企业能耗统计')
// 设置单元格宽度
workSheet['!cols'] = [{
wpx: 80
}, {
wpx: 100
}, {
wpx: 100
}, {
wpx: 100
}];
// 导出Excel, 注意这里用到的是XLSXS对象
let wbout = XLSXS.write(bookNew, {
bookType: 'xlsx',
bookSST: false,
type: 'binary',
})
FileSaver.saveAs(
new Blob([s2ab(wbout)], {
type: 'application/octet-stream'
}),
'企业能耗统计.xlsx'
);
}
const 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
}