最近在迁移一个vue2项目到vue3,过程真的很曲折,我希望可以帮其他的vue3开发者节省一些时间
前端excel导出,并且希望有样式的话需要依赖三个插件
下面分享一下我的package-json 文件
"file-saver": "github:cityTS/FileSaver.js"
"xlsx": "0.16.2",
"xlsx-style-vite": "^0.0.2"
这是我的三个依赖,用以上的三个库就可以完美输出样式excel,这里解释一下xlsx-style-vite这是一个兼容vue3 的xlsx-style版本,开箱即用,香香。
由于时间原因我就直接放代码了,大家仅供参考:
/* eslint-disable */
import { saveAs } from 'file-saver'
import Blob from './Blob'
import XLSX from 'xlsx/dist/xlsx.core.min'
import xlsx_style from 'xlsx-style-vite'
function formatJson(jsonData) {
console.log(jsonData)
}
export function export_json_to_excel(th, jsonData, defaultTitle, merges, autoWidth = true) {
/* original data */
var data = jsonData;
data.unshift(th);
var ws_name = "SheetJS";
var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
// if (merges.length > 0) {
// if (!ws['!merges']) ws['!merges'] = [];
// merges.forEach(item => {
// ws['!merges'].push(XLSX.utils.decode_range(item))
// })
// }
// 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 * 2
// };
// } else {
// return {
// 'wch': val.toString().length
// };
// }
// }))
// /*以第一行为初始值*/
// 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;
// }
const options = {
'!cols': [
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
{ wpx: 60 },
],
// '!rows': [
// { hpx: 40, },
// { hpx: 60 },
// { hpx: 80 },
// { hpx: 60 },
// ],
'!margins': { left: 0.7, right: 0.7, top: 0.75, bottom: 0.75, header: 0.3, footer: 0.3 },
}
if (merges) {
ws['!merges'] = merges
}
ws = Object.assign(ws,options); //宽高
/* add worksheet to workbook */
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
console.log(wb.Sheets, xlsx_style);
var wbout = xlsx_style.write(wb, { bookType: 'xlsx', bookSST: false, type: 'binary' });
var title = defaultTitle || '列表';
saveAs(s2ab(wbout), title + ".xlsx")
}
blob.js
/* eslint-disable */
/* Blob.js
* A Blob implementation.
* 2014-05-27
*
* By Eli Grey, http://eligrey.com
* By Devin Samarin, https://github.com/eboyjr
* License: X11/MIT
* See LICENSE.md
*/
/*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 */
const blob = 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
;
FakeBlob.fake = FB_proto.fake = true;
while (file_ex_code--) {
FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
}
if (!real_URL.createObjectURL) {
URL = view.URL = {};
}
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 = this.data.length = 0;
};
return FakeBlobBuilder;
}(view));
view.Blob = function Blob(blobParts, options) {
var type = options ? (options.type || "") : "";
var builder = new BlobBuilder();
if (blobParts) {
for (var i = 0, len = blobParts.length; i < len; i++) {
builder.append(blobParts[i]);
}
}
return builder.getBlob(type);
};
}
export default blob
---
# 最后
[vue](https://blog.csdn.net/g18204746769/category_12025201.html?spm=1001.2014.3001.5482)
☃️ 个人简介:一个喜爱技术的人。
励志格言: 脚踏实地,虚心学习。
❗如果文章还可以,记得用你可爱的小手点赞关注✅,我会在第一时间回、回访,欢迎进一步交流。