最近在做vue前端导出Excel时,遇到导出样式问题,很让人头疼,想设置Excel宽自适应,边框线,文字居中等等,查阅了很多资料,总结了一套自己得方法,废话不多说,上代码!!!!
一、ExportExcel.js
1.安装ExcelJS
注意:node如果是14版本,请装4.3.0的ExcelJS,还有file-saver插件要装,里面有个saveAs方法是导出)
查看插件版本
npm view exceljs versions
分别安装 file-saver、 xlsx、 script-loader三个依赖
npm install -S file-saver
npm install -S xlsx
npm install -D script-loader
2.下两个js文件
Blob.js
expor2Excel.js
这两个js包可以在网上搜索,代码内容大差不差,根据自己需求进行更改,以下是我导出版本的内容 存放路径:tools/file/export-excel/Expor2Excel,路径可修改
expor2Excel.js有调整,文章后面展示
Blob.js
/* eslint-disable */
/* Blob.js*/
/*global self, unescape */
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
plusplus: true */
/*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
(function (view) {
"use strict";
view.URL = view.URL || view.webkitURL;
if (view.Blob && view.URL) {
try {
new Blob;
return;
} catch (e) {
}
}
// Internally we use a BlobBuilder implementation to base Blob off of
// in order to support older browsers that only have BlobBuilder
var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function (view) {
var
get_class = function (object) {
return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
}
, FakeBlobBuilder = function BlobBuilder() {
this.data = [];
}
, FakeBlob = function Blob(data, type, encoding) {
this.data = data;
this.size = data.length;
this.type = type;
this.encoding = encoding;
}
, FBB_proto = FakeBlobBuilder.prototype
, FB_proto = FakeBlob.prototype
, FileReaderSync = view.FileReaderSync
, FileException = function (type) {
this.code = this[this.name = type];
}
, file_ex_codes = (
"NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
+ "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
).split(" ")
, file_ex_code = file_ex_codes.length
, real_URL = view.URL || view.webkitURL || view
, real_create_object_URL = real_URL.createObjectURL
, real_revoke_object_URL = real_URL.revokeObjectURL
, URL = real_URL
, btoa = view.btoa
, atob = view.atob
, ArrayBuffer = view.ArrayBuffer
, Uint8Array = view.Uint8Array
, origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/
;
FakeBlob.fake = FB_proto.fake = true;
while (file_ex_code--) {
FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
}
// Polyfill URL
if (!real_URL.createObjectURL) {
URL = view.URL = function (uri) {
var
uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
, uri_origin
;
uri_info.href = uri;
if (!("origin" in uri_info)) {
if (uri_info.protocol.toLowerCase() === "data:") {
uri_info.origin = null;
} else {
uri_origin = uri.match(origin);
uri_info.origin = uri_origin && uri_origin[1];
}
}
return uri_info;
};
}
URL.createObjectURL = function (blob) {
var
type = blob.type
, data_URI_header
;
if (type === null) {
type = "application/octet-stream";
}
if (blob instanceof FakeBlob) {
data_URI_header = "data:" + type;
if (blob.encoding === "base64") {
return data_URI_header + ";base64," + blob.data;
} else if (blob.encoding === "URI") {
return data_URI_header + "," + decodeURIComponent(blob.data);
}
if (btoa) {
return data_URI_header + ";base64," + btoa(blob.data);
} else {
return data_URI_header + "," + encodeURIComponent(blob.data);
}
} else if (real_create_object_URL) {
return real_create_object_URL.call(real_URL, blob);
}
};
URL.revokeObjectURL = function (object_URL) {
if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
real_revoke_object_URL.call(real_URL, object_URL);
}
};
FBB_proto.append = function (data/*, endings*/) {
var bb = this.data;
// decode data to a binary string
if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
var
str = ""
, buf = new Uint8Array(data)
, i = 0
, buf_len = buf.length
;
for (; i < buf_len; i++) {
str += String.fromCharCode(buf[i]);
}
bb.push(str);
} else if (get_class(data) === "Blob" || get_class(data) === "File") {
if (FileReaderSync) {
var fr = new FileReaderSync;
bb.push(fr.readAsBinaryString(data));
} else {
// async FileReader won't work as BlobBuilder is sync
throw new FileException("NOT_READABLE_ERR");
}
} else if (data instanceof FakeBlob) {
if (data.encoding === "base64" && atob) {
bb.push(atob(data.data));
} else if (data.encoding === "URI") {
bb.push(decodeURIComponent(data.data));
} else if (data.encoding === "raw") {
bb.push(data.data);
}
} else {
if (typeof data !== "string") {
data += ""; // convert unsupported types to strings
}
// decode UTF-16 to binary string
bb.push(unescape(encodeURIComponent(data)));
}
};
FBB_proto.getBlob = function (type) {
if (!arguments.length) {
type = null;
}
return new FakeBlob(this.data.join(""), type, "raw");
};
FBB_proto.toString = function () {
return "[object BlobBuilder]";
};
FB_proto.slice = function (start, end, type) {
var args = arguments.length;
if (args < 3) {
type = null;
}
return new FakeBlob(
this.data.slice(start, args > 1 ? end : this.data.length)
, type
, this.encoding
);
};
FB_proto.toString = function () {
return "[object Blob]";
};
FB_proto.close = function () {
this.size = 0;
delete this.data;
};
return FakeBlobBuilder;
}(view));
view.Blob = function (blobParts, options) {
var type = options ? (options.type || "") : "";
var builder = new BlobBuilder();
if (blobParts) {
for (var i = 0, len = blobParts.length; i < len; i++) {
if (Uint8Array && blobParts[i] instanceof Uint8Array) {
builder.append(blobParts[i].buffer);
}
else {
builder.append(blobParts[i]);
}
}
}
var blob = builder.getBlob(type);
if (!blob.slice && blob.webkitSlice) {
blob.slice = blob.webkitSlice;
}
return blob;
};
var getPrototypeOf = Object.getPrototypeOf || function (object) {
return object.__proto__;
};
view.Blob.prototype = getPrototypeOf(new view.Blob());
}(
typeof self !== "undefined" && self
|| typeof window !== "undefined" && window
|| this
));
二、html部分
<span class="btn" @click="exportExcel()">
<img src="@/assets/image/down.png" class="tb mr-5 img">
<span class="tb">導出</span>
</span>
导出函数,以下代码可根据实际情况编写,主要步骤
1.使用Export2Excel.js
调用Export2Excel.js中exportJsonToExcel
const {exportJsonToExcel} = require("@/tools/file/export-excel/Export2Excel.js");
2.定义导出字段
例如: value写字段名,label写标题 value尽量与页面table绑定的字段名一样,若需要计算或者修 改内容(存的code转为value),可以起一个新的字段名
const headerMapping = [
{ value: "entrustListCode", label: "委託單編號" }
]
3.存放数据
将数据和标题分别存放, 做为参数传递给exportJsonToExcel
const tHeader = [];
const filterVal = [];
for (const item of headerMapping) {
tHeader.push(item.label);
filterVal.push(item.value);
}
//self.multipleSelection代表你页面table中存放的需要导出的list数据,每个人定义的名字不一样
var temp = self.multipleSelection
//如果导出的值需要计算或者修改内容写此段代码,不需要可不做变更,直接存放即可
temp.forEach((it, index) => {
// it['code'] = index+1;
it['allLabCost'] = it.environmentLabCost+it.mechanicalLabCost+it.falLabCost+it.halfLabCost+it.mtbfLabCost;
it['statusName']=this.filterStatus(it.status)
});
4.过滤导出数据
将需要导出的数据过滤出来,调用exportJsonToExcel
const data = temp.map(v => filterVal.map(j => v[j]));
exportJsonToExcel(tHeader, data, "自定义导出的Excel名");
完整代码如下,根据实际情况修改
methods: {
exportExcel() {
var self = this;
self.loading = true;
//调用Export2Excel.js
require.ensure([], () => {
const {
exportJsonToExcel
} = require("@/tools/file/export-excel/Export2Excel.js");
//定义需要导出的字段与表头
const headerMapping = [
{ value: "entrustListCode", label: "委託單編號" },
{ value: "statusName", label: "狀態" },
{ value: "applicatioUunit", label: "申請單位" },
{ value: "applicant", label: "申請人" },
{ value: "projectType", label: "專案類型" },
{ value: "productNameProject", label: "專案/產品名稱" },
{ value: "projectCostCode", label: "專案費用代碼" },
{ value: "deptCostCode", label: "部門費用代碼" },
{ value: "payLegalPerson", label: "付款法人" },
{ value: "environmentLabCost", label: "環境實驗室$" },
{ value: "mechanicalLabCost", label: "機械實驗室$" },
{ value: "falLabCost", label: "FA實驗室$" },
{ value: "halfLabCost", label: "HALT實驗室$" },
{ value: "mtbfLabCost", label: "MTBF實驗室$" },
{ value: "allLabCost", label: "TRC實驗室合計$" },
{ value: "balanceDate", label: "結算日期" }];
const tHeader = [];
const filterVal = [];
for (const item of headerMapping) {
tHeader.push(item.label);
filterVal.push(item.value);
}
if (self.multipleSelection.length > 0) {
var temp = self.multipleSelection
temp.forEach((it, index) => {
// it['code'] = index+1;
it['allLabCost'] = it.environmentLabCost+it.mechanicalLabCost+it.falLabCost+it.halfLabCost+it.mtbfLabCost;
it['statusName']=this.filterStatus(it.status)
});
const data = temp.map(v => filterVal.map(j => v[j]));
//将所有数据传参 exportJsonToExcel要与Export2Excel.js里的匹配
exportJsonToExcel(tHeader, data, "結算和終止功能報表");
self.loading = false;
}else{
//导出接口
exportFileAPI({labCode:self.laboratoryCode}).then(res => {
if (res.code === 200) {
self.loading=false;
console.log("結算和終止功能報表", res);
const temp = res.result.list;
temp.forEach((it, index) => {
// it['code'] = index+1;
it['allLabCost'] = it.environmentLabCost+it.mechanicalLabCost+it.falLabCost+it.halfLabCost+it.mtbfLabCost;
it['statusName']=this.filterStatus(it.status)
});
const data = temp.map(v => filterVal.map(j => v[j]));
exportJsonToExcel(tHeader, data, "結算和終止功能報表");
} else {
this.$message.error("導出結算和終止功能報表失敗");
}
});
}
});
}
}
三、最终的 Export2Excel.js 文件
1.引入依赖
//由于这几个文件不支持import引入,所以我们需要`script-loader`来将他们挂载到全局环境下
require('script-loader!file-saver'); //保存文件用
require('script-loader!./Blob'); //保存二进制文件用,直接写绝对路径
require('script-loader!xlsx/dist/xlsx.core.min'); //xlsx核心
import XLSX from "xlsx-style"
2.导出函数
接收参数说明:
th==>tHeader自定义的标题 jsonData==>data导出数据 defaultTitle==>自定义的表名,autoWidth==>是否开启宽度自适应,默认为true,反之在使用时传false,bookType==>导出文件类型,若需要其他参数自行设计
export function exportJsonToExcel(th, jsonData, defaultTitle, autoWidth=true, bookType = 'xlsx', myRowFont = '1') {
/* original data */
var data = jsonData;
data.unshift(th);
var ws_name = "SheetJS";
var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
})
3.宽自适应
// console.log(autoWidth)
if (autoWidth) {
/*设置worksheet每列的最大宽度*/
const colWidth = data.map(row => row.map(val => {
/*先判断是否为null/undefined*/
if (val == null) {
return {
'wch': 10
};
}
/*再判断是否为中文*/
else if (val.toString().charCodeAt(0) > 255) {
return {
'wch': val.toString().length * 4
};
} else {
return {
'wch': val.toString().length*2
};
}
}))
/*以第一行为初始值*/
let result = colWidth[0];
for (let i = 1; i < colWidth.length; i++) {
for (let j = 0; j < colWidth[i].length; j++) {
if (result[j]['wch'] < colWidth[i][j]['wch']) {
result[j]['wch'] = colWidth[i][j]['wch'];
}
}
}
ws['!cols'] = result;
}
4.单元格加边框
/* add worksheet to workbook */
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
var dataInfo = wb.Sheets[wb.SheetNames[0]];
// 设置单元格框线
const borderAll = {
top: {
style: "thin"
},
bottom: {
style: "thin"
},
left: {
style: "thin"
},
right: {
style: "thin"
}
};
// 给所有单元格加上边框,内容居中,字体,字号,标题表头特殊格式部分后面替换
for (var i in dataInfo) {
if (
i == "!ref" ||
i == "!merges" ||
i == "!cols" ||
i == "!rows"
) { } else {
dataInfo[i + ""].s = {
border: borderAll,
// alignment: {
// horizontal: "center",
// vertical: "center"
// },
font: {
name: "微軟正黑體",
sz: 11
}
};
}
}
5.设置导出表题样式
定义tableStyle:[],存放最终样式
实现思路,dataInfo中存放着所有需要带出的信息,如下图
通过 Object.keys(dataInfo)将所有key取出,可发现需要设置的标题行列名都为A1 B1....XX1.......
通过数字截取的方式将表格第一行的每一个列名存到数组tableStyle,v.replace(/[^\d]/g, ''),最后遍历tableStyle每一项,设置fgColor背景颜色即可,代码如下:
// 设置表格样式
//獲取Excel第一行標題範圍
const tableStyle= []
const colKey = Object.keys(dataInfo)
//將dataInfo中所有key包含1的取出 例如A1 B1.......
colKey.some(function (v) {
if (v.replace(/[^\d]/g, '') === '1') {
tableStyle.push(v)
}
})
// 给标题、表格描述信息、表头等部分加上特殊格式
tableStyle.some(function (v) {
// for (let j = 1; j < data.length; j++) {
// const _v = v + j
if (dataInfo[v]) {
dataInfo[v].s.fill = {};
// 标题部分
dataInfo[v].s.fill = {
fgColor: {
rgb: "BDD7EE"
}
};
}
// }
});
6.导出
var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
var title = defaultTitle || '列表'
saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), title + ".xlsx")
7.完整的Export2Excel.js代码
/* eslint-disable */
require('script-loader!file-saver');
require('./Blob');
require('script-loader!xlsx/dist/xlsx.core.min');
import XLSX from "xlsx-style"
function generateArray(table) {
var out = [];
var rows = table.querySelectorAll('tr');
var ranges = [];
for (var R = 0; R < rows.length; ++R) {
var outRow = [];
var row = rows[R];
var columns = row.querySelectorAll('td');
for (var C = 0; C < columns.length; ++C) {
var cell = columns[C];
var colspan = cell.getAttribute('colspan');
var rowspan = cell.getAttribute('rowspan');
var cellValue = cell.innerText;
if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;
//Skip ranges
ranges.forEach(function (range) {
if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
}
});
//Handle Row Span
if (rowspan || colspan) {
rowspan = rowspan || 1;
colspan = colspan || 1;
ranges.push({s: {r: R, c: outRow.length}, e: {r: R + rowspan - 1, c: outRow.length + colspan - 1}});
}
;
//Handle Value
outRow.push(cellValue !== "" ? cellValue : null);
//Handle Colspan
if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
}
out.push(outRow);
}
return [out, ranges];
};
function datenum(v, date1904) {
if (date1904) v += 1462;
var epoch = Date.parse(v);
return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}
function sheet_from_array_of_arrays(data, opts) {
var ws = {};
var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};
for (var R = 0; R != data.length; ++R) {
for (var C = 0; C != data[R].length; ++C) {
if (range.s.r > R) range.s.r = R;
if (range.s.c > C) range.s.c = C;
if (range.e.r < R) range.e.r = R;
if (range.e.c < C) range.e.c = C;
var cell = {v: data[R][C]};
if (cell.v == null) continue;
var cell_ref = XLSX.utils.encode_cell({c: C, r: R});
if (typeof cell.v === 'number') cell.t = 'n';
else if (typeof cell.v === 'boolean') cell.t = 'b';
else if (cell.v instanceof Date) {
cell.t = 'n';
cell.z = XLSX.SSF._table[14];
cell.v = datenum(cell.v);
}
else cell.t = 's';
ws[cell_ref] = cell;
}
}
if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
return ws;
}
function Workbook() {
if (!(this instanceof Workbook)) return new Workbook();
this.SheetNames = [];
this.Sheets = {};
}
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;
}
export function export_table_to_excel(id) {
var theTable = document.getElementById(id);
console.log('a')
var oo = generateArray(theTable);
var ranges = oo[1];
/* original data */
var data = oo[0];
var ws_name = "SheetJS";
console.log(data);
var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
/* add ranges to worksheet */
// ws['!cols'] = ['apple', 'banan'];
ws['!merges'] = ranges;
/* add worksheet to workbook */
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), "test.xlsx")
}
function formatJson(jsonData) {
console.log(jsonData)
}
// export function export_json_to_excel(th, jsonData, defaultTitle) {
// /* original data */
// var data = jsonData;
// data.unshift(th);
// var ws_name = "SheetJS";
// var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
// /* add worksheet to workbook */
// wb.SheetNames.push(ws_name);
// wb.Sheets[ws_name] = ws;
// var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
// var title = defaultTitle || '列表'
// saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), title + ".xlsx")
// }
export function exportJsonToExcel(th, jsonData, defaultTitle, autoWidth=true, bookType = 'xlsx', myRowFont = '1') {
/* original data */
var data = jsonData;
data.unshift(th);
var ws_name = "SheetJS";
var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
// console.log(autoWidth)
if (autoWidth) {
/*设置worksheet每列的最大宽度*/
const colWidth = data.map(row => row.map(val => {
/*先判断是否为null/undefined*/
if (val == null) {
return {
'wch': 10
};
}
/*再判断是否为中文*/
else if (val.toString().charCodeAt(0) > 255) {
return {
'wch': val.toString().length * 4
};
} else {
return {
'wch': val.toString().length*2
};
}
}))
/*以第一行为初始值*/
let result = colWidth[0];
for (let i = 1; i < colWidth.length; i++) {
for (let j = 0; j < colWidth[i].length; j++) {
if (result[j]['wch'] < colWidth[i][j]['wch']) {
result[j]['wch'] = colWidth[i][j]['wch'];
}
}
}
ws['!cols'] = result;
}
/* add worksheet to workbook */
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
var dataInfo = wb.Sheets[wb.SheetNames[0]];
// 设置单元格框线
const borderAll = {
top: {
style: "thin"
},
bottom: {
style: "thin"
},
left: {
style: "thin"
},
right: {
style: "thin"
}
};
// 给所有单元格加上边框,内容居中,字体,字号,标题表头特殊格式部分后面替换
for (var i in dataInfo) {
if (
i == "!ref" ||
i == "!merges" ||
i == "!cols" ||
i == "!rows"
) { } else {
dataInfo[i + ""].s = {
border: borderAll,
// alignment: {
// horizontal: "center",
// vertical: "center"
// },
font: {
name: "微軟正黑體",
sz: 11
}
};
}
}
// 设置表格样式
//獲取Excel第一行標題範圍
const tableStyle= []
const colKey = Object.keys(dataInfo)
//將dataInfo中所有key包含1的取出 例如A1 B1.......
colKey.some(function (v) {
if (v.replace(/[^\d]/g, '') === '1') {
tableStyle.push(v)
}
})
// 给标题、表格描述信息、表头等部分加上特殊格式
tableStyle.some(function (v) {
// for (let j = 1; j < data.length; j++) {
// const _v = v + j
if (dataInfo[v]) {
dataInfo[v].s.fill = {};
// 标题部分
dataInfo[v].s.fill = {
fgColor: {
rgb: "BDD7EE"
}
};
}
// }
});
var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
var title = defaultTitle || '列表'
saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), title + ".xlsx")
}
总结:以上代码仅实现了简单样式导出,复杂表格导出,例如合并单元格等未整理,有兴趣的小伙伴可留言补充,有错误的地方欢迎指正!!!!!