vue中使用导出表格功能

1.下载依赖

 npm install -S file-saver xlsxnpm install -D script-loader

2.在src下创建vendor文件夹,并在文件夹中放两个文件

  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 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);};
}(typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content || this));

  Export2Excel.js。

/* eslint-disable */
require('script-loader!file-saver');
require('script-loader!@/vendor/Blob');
require('script-loader!xlsx/dist/xlsx.core.min');
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 rangesranges.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 Spanif (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 ValueoutRow.push(cellValue !== "" ? cellValue : null);//Handle Colspanif (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")
}

3.system.vue

<template><div class="systemHome"><el-button style='margin-bottom:20px;' type="primary" icon="document" @click="handleDownload">导出excel</el-button><el-table :data="tableData" style="width: 100%"><el-table-column prop="date" label="日期"width="180"></el-table-column><el-table-column prop="name"  label="姓名"  width="180"></el-table-column><el-table-column  prop="address" label="地址"></el-table-column></el-table></div>
</template><script>export default{name:"systemHome",data() {return {tableData: [{date: '2016-05-02',name: '王小虎',address: '上海市普陀区金沙江路 1518 弄'}, {date: '2016-05-04',name: '王小虎',address: '上海市普陀区金沙江路 1517 弄'}, {date: '2016-05-01',name: '王小虎',address: '上海市普陀区金沙江路 1519 弄'}, {date: '2016-05-03',name: '王小虎',address: '上海市普陀区金沙江路 1516 弄'}]};},methods:{handleDownload() {this.downloadLoading = truerequire.ensure([], () => {const { export_json_to_excel } = require('@/vendor/Export2Excel')const tHeader = ['日期', '姓名', '地址']const filterVal = ['date', 'name', 'address']const list = this.tableDataconst data = this.formatJson(filterVal, list)export_json_to_excel(tHeader, data, '列表excel')this.downloadLoading = false})},formatJson(filterVal, jsonData) {return jsonData.map(v => filterVal.map(j => v[j]))}}}
</script><style lang="less" scoped>
.systemHome{background:#F4F4F4;margin:8px;border-radius:4px;
}
</style>

4.点击按钮,导出表格

 

 

转载于:https://www.cnblogs.com/ldlx-mars/p/7919497.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/571532.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

adb shell 书籍_开发必备---你应该知道的一些 ADB 命令

版权声明&#xff1a;本文为LooperJing原创文章&#xff0c;转载请注明出处&#xff01;一、设备相关1、adb devices显示连接到计算机的设备List of devices attachedbe34d81e device输出格式为 [serialNumber] [state]&#xff0c;state 有如下几种&#xff1a;列名解释nodevi…

python生成器迭代_二十、深入Python迭代器和生成器

「Author&#xff1a;Runsen」学习python的过程中&#xff0c;迭代器与生成器是绕不开的话题&#xff0c; 什么是迭代器和生成器呢&#xff1f;下面我们来了解一下什么是迭代。但在了解迭代器之前&#xff0c;首先需要知道什么是容器。容器正所谓&#xff1a;一切都是对象&…

批改网禁止粘贴怎么破_重大利好!教育部声明,要求家长批改作业等行为,发现一起严处一起...

前段时间&#xff0c;在江苏一位家长发布短视频&#xff0c;他在视频中怒喊&#xff1a;我就退出家长群怎么了&#xff01;引起网上一阵热议起因是这位家长认为老师总是让家长帮忙批改作业&#xff0c;自己承担了太多教师应负的责任&#xff0c;完了还要昧着良心说老师你辛苦了…

mysql实验步骤_MySQL双方配置实验步骤

实验环境&#xff1a;两台MariaDB服务器&#xff0c;IP分别为&#xff1a; 172.16.2.16 和 172.16.2.17MariaDB的版本是5.5.36&#xff0c;使用二进制方式安装。已安装完成。/mydata/data 数据库文件存放目录/mydata/binlog/ 二进制日志文件存放位置/mydata/relaylog/ 中继日志…

mac 系统安装 eclipse 方法

经过好几天的折腾&#xff0c;终于在各种不靠谱的经验、说明的忽悠中把自己心爱的 mac 安装上了 eclipse&#xff0c;看到别人的不靠谱&#xff0c;我决定自己写一篇经验&#xff0c;为了大家能够不走我这么多的弯路&#xff0c;也为了自己将来可以回来看看&#xff0c;下次安装…

python自动化和教程_《手把手教你》系列练习篇之2-python+ selenium自动化测试(详细教程)...

1. 简介今天我们还是继续练习练习基本功&#xff0c;各位小伙伴要耐住住性子&#xff0c;要耐得住寂寞啊&#xff0c;不要急躁&#xff0c;后面你会感谢你在前边的不断练习的。到后面也是检验你前边的学习成果的一次很好实践。本文介绍如何通过link text、partial link text、c…

异常在哪一层处理_WiFi速度慢,信号不稳定,除了重启路由器外,自己能怎么处理?...

前言WiFi出了故障&#xff0c;速度慢&#xff0c;信号不稳定&#xff0c;自己处理&#xff0c;除了重启路由器&#xff0c;也没有什么别的招了&#xff1b;好在这万能重启&#xff0c;差不多能解决一大半的小故障&#xff1b;那信号不好&#xff0c;速度慢&#xff0c;不稳定&a…

linux运维、架构之路-HAProxy反向代理

一、HAProxy介绍 专业反向代理,支持双机热备支持虚拟主机,配置简单,拥有非常不错的服务器健康检查功能,当其代理的后端节点出现故障, HAProxy会自动将该服务器摘除,故障恢复后再自动将该服务器加入&#xff0c;基于TCP和HTTP应用的代理软件&#xff0c;开源免费、快速并且可靠的…

CSS3 3D transform变换

transform的坐标是需要了解的特性。 我们的rotateX,rotateY,rotateZ,和translateX,translateY等都是基于相同的坐标系来定位的。 3D的坐标如下入所示&#xff1a; 3D transform中有下面这三个方法&#xff1a; rotateX( angle )rotateY( angle )rotateZ( angle )理解了这三个方…

vba结束本次循环进行下次_VBA掌握循环结构,包你效率提高500倍

这是系列免费教程《Excel VBA&#xff1a;办公自动化》&#xff0c;还是老规矩&#xff0c;看看我们走到哪里了。1.认识VBA&#xff1a;什么是VBA&#xff1f;2.这些掌握了&#xff0c;你才敢说自己懂VBA3.VBA变量5年踩坑吐血精华总结4.VBA中重要的强制申明&#xff0c;谁看谁明…

CefSharp 支持MP4

效果图&#xff1a; 下载链接&#xff1a;https://share.weiyun.com/d1e249ef5c56b4d909b2124dc2dd8902 创建Wpf项目引用 如下&#xff1a; 第一步&#xff1a;创建项目引用CefSharp 第二步&#xff1a;将DLL拷贝到运行项目的Debug下 第三步&#xff1a;项目平台设置32位 第四…

ReentrantLock 分析

带着疑问去分析 ReentrantLock是如何实现锁管理的。ReentrantLock是如何实现重入的。ReentrantLock是如何实现公平锁与非公平锁。ReentantLock的公平锁为什么一般情况下性能都比公平锁查。ReentrantLock数据结构 ReentrantLock的底层是借助于AbstractQueuedSynchronizer实现的&…

v4l2 框架下如何设置分辨率_Linux下如何进行FTP设置

目录&#xff1a; 一、Redhat/CentOS安装vsftp软件二、Ubuntu/Debian安装vsftp软件一、Redhat/CentOS安装vsftp软件1.更新yum源yum update -y2.安装vsftpyum install vsftpd -y3.修改配置文件vi /etc/vsftpd/vsftpd.conf # 原有初始配置 local_umask022 dirmessage_enableYES x…

2017-2018-1 20155213 《信息安全系统设计基础》第十一周学习总结

2017-2018-1 20155213 《信息安全系统设计基础》第十一周学习总结 【学习内容:第九章——虚拟存储器】 一、课本内容梳理 1.虚拟存储器 作用&#xff1a; 将主存看作是一个存储在磁盘上的地址空间的高速缓存&#xff0c;在主存中只保护活动的区域&#xff0c;并根据需要在磁盘和…

vscode弹出cmd_先看看 VS Code Extension 知识点,再写个 VS Code 扩展玩玩

TL;DR文章篇幅有点长 &#xff0c;可以先收藏再看 。要是想直接看看怎么写一个扩展&#xff0c;直接去第二部分 &#xff0c;或者直接去github看源码 。第一部分 --- Extension 知识点一、扩展的启动如何保证性能 --- 扩展激活&#xff08;Extension Activation&#xff09; 我…

webp转换gif_用 WebP 创建尺寸更小、细节更丰富的图片,以此来提高网站的速度...

WebP 文件格式是一种基于 RIFF(资源互换文件格式)的文档格式。WebP 是 2010 年 Google 开发的一种图片格式&#xff0c;它为网页上的图片提供了卓越的无损和有损压缩。网站开发者们可以使用 WebP 来创建尺寸更小、细节更丰富的图片&#xff0c;以此来提高网站的速度。更快的加载…

python 如何判断excel单元格为空_如何用python处理excel(二)

读取excelimport xlrdworkbookxlrd.open_workbook(rC:\Users\Desktop\hebing\学生登记表.xls)sheetworkbook.sheet_by_index(0)#根据序列号来打开某一个sheetrowsheet.nrows#将excel的行数赋值给变量colsheet.ncols#将excel的列数赋值给变量print(sheet.cell_value(1,0))#打印出…

web前端到底是什么?有前途吗

web前端到底是什么&#xff1f; 某货&#xff1a; “前几年前端开发人员鱼目混杂&#xff0c;技术参差不齐&#xff0c;相对学习起来不规范&#xff0c;导致> 前端开发人员聚集&#xff0c;所以现在前端工种和工资还是没得到普遍重视&#xff0c;但近2年来&#xff0c;> …

此加载项为此计算机的所有用户安装_MDI Jade 6.5软件安装教程

软件下载▼关注微信公众号&#xff1a;贵州永航科技回复Jade即可获得软件安装包下载地址以及详细安装教程更多软件安装教程可点击菜单栏获取软件介绍MDI Jade是一款专门用于XRD分析的软件&#xff0c;XRD分析就是X射线衍射分析&#xff0c;MDI Jade通过对材料进行X射线衍射&…

java 线程定时器_Java线程之Timer定时器

定时/计划功能主要使用的就是Timer对象&#xff0c;它在内部还是使用多线程的方式进行处理&#xff0c;所以它和线程技术还是有非常大的关联。Timer类主要作用就是设置计划任务&#xff0c;但封装任务的类却是TimerTask类。TimerTask类是一个抽象类。执行任务的时间晚于当前时间…