纯前端表格导出Excel

ops/2024/9/22 23:37:21/

先写好两个js文件 直接复制粘贴

文件目录是这样的

Bolb.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 BlobBuildervar BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {varget_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) {vartype = 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 stringif (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {varstr = "", 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 syncthrow 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 stringbb.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);};
}
exports.blob = blob;

Export2Excel.js

/* eslint-disable */
require('script-loader!file-saver');
// require('script-loader!./Blob');
// require('script-loader!xlsx/dist/xlsx.core.min');
// require('script-loader!xlsx-style/xlsx');
require('script-loader!xlsx-style/dist/xlsx.core.min');
require('script-loader!xlsx-style/xlsx');
// 设置表格中cell默认的字体,居中,颜色等
/**
{ auto: 1} specifying automatic values
{ rgb: "FFAA00" } specifying a hex ARGB value
{ theme: "1", tint: "-0.25"} specifying an integer index to a theme color and a tint value (default 0)
{ indexed: 64} default value for fill.bgColor*/
const defaultCellStyle = {font: { name: "宋体", sz: 11, color: { rgb: "000000" } },border: {color: { auto: 1 }},alignment: {/// 自动换行wrapText: 1,// 居中horizontal: "center",vertical: "center",indent: 0}
};// 从json转化为sheet,xslx中没有aoaToSheet的方法,该方法摘自官方test
function sheet_from_array_of_arrays(data) {const ws = {};const range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } };for (let R = 0; R !== data.length; ++R) {for (let 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;// 这里生成cell的时候,使用上面定义的默认样式const cell = { v: data[R][C], s: defaultCellStyle };if (cell.v == null) continue;const cell_ref = XLSX.utils.encode_cell({ c: C, r: R });/* TEST: proper cell types and value handling */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;}}/* TEST: proper range */if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);// 自适应宽度return ws;
}export function formatJson(filterVal, jsonData) {return jsonData.map(v => filterVal.map(j => v[j]))
}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);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;ws['!cols'] = [{ wch: 4 }, { wch: 8 }];var wbout = XLSX.write(wb, {bookType: 'xlsx',bookSST: false,type: 'binary',});saveAs(new Blob([s2ab(wbout)], {type: 'application/octet-stream',}),'test.xlsx');
}
/*** 计算表格宽度* @param {*} th * @param {*} ws * @returns */
function matchWidth(th) {let retn = []console.log(th);th.forEach(element => {retn.push({ wch: (element + "").length * 2 })});return retn
}/*** 多sheet导出* @param {Array} th 表头* @param {Array} jsonDatas 数据集 * @param {String} defaultTitle 导出的excel名称* @param {Array} sheetNames sheet名称集*/
export function export_season_to_excel(th, jsonDatas, defaultTitle, sheetNames) {var wb = new Workbook()jsonDatas.forEach((item, index) => {var data = item;data.unshift(th);var ws_name = sheetNames[index];var 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 export_json_to_excel(th, jsonData, defaultTitle) {/* original data */var data = jsonData;data.unshift(th);var ws_name = 'sheet1';var wb = new Workbook(),ws = sheet_from_array_of_arrays(data);/* add worksheet to workbook */th.push()// 自适应宽度再这里设置// ws['!cols'] = matchWidth(th)//  [{wch:100},{wch:200}];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');
}

然后安装所需依赖

npm install file-saver -S             
npm install script-loader -S             
npm install xlsx -S                      
npm install xlsx-style -S             

然后是使用方法

// 引入文件
import { export_json_to_excel } from '@/vendor/Export2Excel.js'
// 表头
const tHeader = this.tableData.map((e) => e.label)//['运维单位','运维负责人','负责人电话']
// table表格中对应的属性名
const filterVal = this.tableData.map((e) => e.prop)//['name','manager','phone']
// 表格绑定数据转json
const data = this.formatJson(filterVal, this.exportMultipleSelection)//第二个参数是表格数据 [{name:'疼训',manager:'张三',phone:'123456'},{name:'精东',manager:'李四',phone:'123456'},]
export_json_to_excel(tHeader,//表头data,//列表数据'预警清单' + new Date().toLocaleDateString(),//文件名
)// 导出列表格式化数据的方法
formatJson(filterVal, jsonData) {return jsonData.map((v, index) =>filterVal.map((j) => {//这里可以做一些判断 比如后端给时间一般都是时间戳 在这里判断prop后单独处理时间戳if (j === 'occurTime') {//预警时间return v.occurTime ? this.$format(v.occurTime) : "";} else {return v[j]//如果是直接用后端的值就直接这样就好了}}),)
}


http://www.ppmy.cn/ops/114470.html

相关文章

【Leetcode:1184. 公交站间的距离 + 模拟】

&#x1f680; 算法题 &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;…

有关elementui form验证问题,有值却仍然显示不通过

参考链接 有关elementui form验证问题&#xff0c;有值却仍然显示不通过 - 一棵写代码的柳树 - 博客园 需要保证表单上的 :model" "和prop" "对应的属性相同 el-form 绑定数据:model 和 规则:rules input 绑定 数据表单里的数据 其父组件提供校验所绑定的…

数据结构-树和二叉树

树 和 二叉树 1.树的概念 树 tree 是n(n>0)个节点的有限集 在任意的一个非空树中 (1)有且仅有一个特定的被称为 根(root) 的节点 (2)当n>1时, 其余的节点可分为m(m>0)个互不相交的有限集T1, T2, T3, .... …

stm32单片机个人学习笔记6(EXTI外部中断)

前言 本篇文章属于stm32单片机&#xff08;以下简称单片机&#xff09;的学习笔记&#xff0c;来源于B站教学视频。下面是这位up主的视频链接。本文为个人学习笔记&#xff0c;只能做参考&#xff0c;细节方面建议观看视频&#xff0c;肯定受益匪浅。 STM32入门教程-2023版 细…

适用于QF的存档系统

存档系统 今天分享一个适用于QF的存档系统 这个系统的优点为 1、轻量化&#xff0c;总共代码不超过400行 2、自动化&#xff0c;基于QF框架&#xff0c;自动注入值 缺点&#xff1a; 1、不能序列化Unity内部类型&#xff0c;如Vector 2、需要给能被序列化的类加上【Seri…

【python】修改字典的内容

person {"name": "John", "age": 30, "city": "New York"} print("最开始的信息&#xff1a;",person)def process_person_info(person):# 检查对象中是否包含所有必要的键if name in person and age in person …

如何有效检测住宅IP真伪?

在当今的互联网时代&#xff0c;住宅IP&#xff08;即家庭用户通过宽带服务提供商获得的IP地址&#xff09;在跨境电商、广告投放、网络安全等多个领域扮演着重要角色。然而&#xff0c;随着网络环境的复杂化和欺诈行为的增多&#xff0c;如何有效检测和辨别住宅IP的真伪成为了…

第三十七条:不要以序号作为索引,使用EnumMap代替

我们有时可能会看到使用ordinal方法来索引数组或者列表的代码。例如&#xff0c;考虑到下面这个简单的类&#xff0c;用于表示一种植物&#xff1a; public class Plant {enum LifeCycle {ANNUAL, PERENNIAL, BIENNIAL}final String name;final LifeCycle lifeCycle;public Pl…