欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 纯前端表格导出Excel

纯前端表格导出Excel

2024/10/25 6:27:08 来源:https://blog.csdn.net/weixin_44177413/article/details/142363775  浏览:    关键词:纯前端表格导出Excel

先写好两个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]//如果是直接用后端的值就直接这样就好了}}),)
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com