vue 导出excel
1、安装三个依赖包
npm install -S file-saver
npm install -S xlsx
npm install -D script-loader
2、在项目中创建一个文件夹(比如vendor,一般是在src目录下创建)
把Blob.js和 Export2Excel.js这两个文件夹放到新建的文件夹内,如图:

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 */ (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);
};
}(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 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")
}
3、在页面中使用
<template>
<f7-page :name="$route.route.name" :class="$route.route.name" pull-to-refresh>
<navbar :title="$route.route.title"></navbar>
<button style='margin-bottom:20px;' type="primary" icon="document" @click="handleDownload" >导出excel</button>
<table data="tableData" style="width: 100%">
<tr>
<td prop="id" label="名称" width="180"></td>
<td prop="name" label="姓名" width="180">
</td>
</tr>
</table>
</f7-page>
</template>
export default {
data(){
return{
table:[{
id:1,
name:'测试1'
},{
id:2,
name:'测试2'
},{
id:3,
name:'测试3'
}]
}
},
methods:{
handleDownload() {
this.downloadLoading = true
require.ensure([], () => {
const { export_json_to_excel } = require('../../vendor/Export2Excel')
const tHeader = ['ID', '姓名']
const filterVal = ['id', 'name']
const list = this.table
const 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]))
}
}
}
4.在main.js(全局js文件)中加入如下代码:

在webpack.base.conf.js中加入

出现下面的错误:

首先按照提示运行该语句,如果还是不行,则需要查看上面的路径配置。然后就解决了
vue 导出excel的更多相关文章
- vue 导出excel表格
对于涉及到数据比较多的管理后台导出excel 表格这个需求就非常的常见了 所以? vue 怎么到处excel表格的? 有两种办法 1:请求接口后台直接给你的是excel文件,你需要做的就是怎么接收ex ...
- 【vue开发】vue导出Excel表格教程&demo
前端工作量最多的就是需求,需求就是一直在变,比如当前端数据写完之后,需要用Excel把数据下载出来:再比如前端在没有数据库想写些demo玩时,也是很好的选择. 第一步安装依赖包,修改配置 1.装依赖: ...
- 个人推荐的两款vue导出EXCEL插件
个人认为前端VUE项目中导出EXCEL比较好的两种方法,均不是我个人原创,我只是收录简单说明,原创地址在下面. 下面推荐两种方法,个人推荐第一种,第二种不做详细讲解,因为作者已经写过博客了,你们可以点 ...
- vue 导出excel后端返回乱码下载不了的解析问题
有俩种方法可以用 第一种方法: 解析:直接解析并且下载后端的乱码 this.download('后端给的导出excel的方法', { ...this.queryParams }, ` ...
- 使用vue导出excel文件
今天再开发中遇到一件事情,就是怎样用已有数据导出excel文件,网上有许多方法,有说用数据流的方式,https://www.cnblogs.com/yeqrblog/p/9758981.html,但是 ...
- vue导出Excel文件
1.需要安装file-saver和script-loader.xlsx npm install file-saver / yarn add file-saver npm install script- ...
- VUE 导出Excel(iframe)
1. 概述 1.1 说明 在开发过程中,有时候需要导出某数据表格(excel)以便客户使用,使用iframe对返回二进制文件进行下载处理.记录此功能,以便后期使用. 2. 示例 2.1 vue示例代码 ...
- vue导出excel
1.按装依赖 cnpm install -S file-saver xlsx cnpm install -D script-loader 2.引入Blob.js和expor2Excal.js 3.在m ...
- vue导出excel数据表格功能
前端工作量最多的就是需求,需求就是一直在变,比如当前端数据写完之后,需要用Excel把数据下载出来. 第一步安装依赖包,需要把代码下载你的项目当中 cnpm install file-saver c ...
随机推荐
- javaScript之this的五种情况
this一直是JavaScript研究的难题,特别是在笔试和面试中的各种程序分析问题中,也常常会被问到.下面来看一看this被运用的五中情况: (1) 纯粹的函数调用 函数最普通用法,此时 ...
- url传参解决中文乱码
跳转前: window.open("http://localhost:9728/content/agent/devolution.html?search_agent=" + enc ...
- Java之网络编程UDP和TCP
注*部分转来的 第1章 网络通信协议 通过计算机网络可以使多台计算机实现连接,位于同一个网络中的计算机在进行连接和通信时需要遵守一定的规则,这就好比在道路中行驶的汽车一定要遵守交通规则一样.在计算机网 ...
- win7 eclipse连接hadoop2.x开发环境搭建
环境: hadoop-2.3.0-cdh5.1.0 centos 6.5 x64 win7 eclipse4.3 0. 前提条件 ,jdk,maven要安装好. 1.下载hadoop,用winRAR解 ...
- iOS开发,使用CocoaSSDP查找设备时按关键字过滤Device
关于CocoaSSDP的资料有很多,这里就不介绍了. 希望寻找的目标设备,在header中设置了自定义的keyword,虽然通过外围代码也能达到相同目的,但是直接修改CocoaSSDP源码更简便. 导 ...
- NIO和Reactor
本文参考Doug Lea的Scalable IO in Java. 网络服务 随着网络服务的越来越多,我们对网络服务的性能有了更高的要求,提供一个高性能,稳定的web服务是一件很麻烦的事情,所以有了n ...
- Fetch超时设置和终止请求
1.基本使用 Fetch 是一个新的端获取资源的接口,用于替换笨重繁琐XMLHttpRequest.它有了Request 和 Response 以及Headers对象的概念,与后端语言请求资源更接近. ...
- python文件名匹配
待匹配文件:#FY3D_IPMNT_GBAL_L1_20180516_0003_030KM_MS.HDF 干扰文件:#FY3D_IPMNT_GBAL_L1_20180516_0003_030KM_MS ...
- XML之DTD
前言 上篇我们知道了,XML的应用范围还是很广的,那么无规矩不成方圆,如果我们每个人写XML的风格不一致,那么读起来是不是很费劲呢?所以格式良好的XML就渐渐的被我们所需要. 内容 格式良好指:拥有正 ...
- java整理(一)
1.方法重载:方法名称相同,参数的类型或个数不同.但是返回值类型不同,不是方法重载. 2.引用数据类型:数组,类,接口.内存地址分为两类,栈内存和对内存.栈内存保存的是对内存的地址,简单理解就是保存了 ...