vue Export2Excel 导出文件
使用需要引入这些js
在src目录下创建一个文件(vendor)进入Blob.js和Export2Excel.js
npm install -S file-saver 用来生成文件的web应用程序
npm install -S xlsx 电子表格格式的解析器
npm install -D script-loader 将js挂在在全局下
Blob.js
/* eslint-disable */
/* Blob.js*/ /*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 , origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/
;
FakeBlob.fake = FB_proto.fake = true;
while (file_ex_code--) {
FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
}
// Polyfill URL
if (!real_URL.createObjectURL) {
URL = view.URL = function (uri) {
var
uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
, uri_origin
;
uri_info.href = uri;
if (!("origin" in uri_info)) {
if (uri_info.protocol.toLowerCase() === "data:") {
uri_info.origin = null;
} else {
uri_origin = uri.match(origin);
uri_info.origin = uri_origin && uri_origin[1];
}
}
return uri_info;
};
}
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 = 0;
delete this.data;
};
return FakeBlobBuilder;
}(view)); view.Blob = function (blobParts, options) {
var type = options ? (options.type || "") : "";
var builder = new BlobBuilder();
if (blobParts) {
for (var i = 0, len = blobParts.length; i < len; i++) {
if (Uint8Array && blobParts[i] instanceof Uint8Array) {
builder.append(blobParts[i].buffer);
}
else {
builder.append(blobParts[i]);
}
}
}
var blob = builder.getBlob(type);
if (!blob.slice && blob.webkitSlice) {
blob.slice = blob.webkitSlice;
}
return blob;
}; var getPrototypeOf = Object.getPrototypeOf || function (object) {
return object.__proto__;
};
view.Blob.prototype = getPrototypeOf(new view.Blob());
}(
typeof self !== "undefined" && self
|| typeof window !== "undefined" && window
|| this
));
Export2Excel.js
require('script-loader!file-saver')
// vue 2.6必须要使用这种载入其他js文件的方式才行
import '@/vendor/Blob'
require('script-loader!xlsx/dist/xlsx.core.min')
require('script-loader!xlsx-style/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)
var oo = generateArray(theTable)
var ranges = oo[1]
/* original data */
var data = oo[0]
var ws_name = 'SheetJS'
var wb = new Workbook()
var 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'
)
}
// 主要修改此函数内的方法
export function export_json_to_excel({
multiHeader = [],
header,
data,
sheetname,
filename,
merges = [],
autoWidth = true,
bookType = 'xlsx'
} = {}) {
/* original data */
filename = filename || 'excel-list'
data = [...data]
for (var i = 0; i < header.length; i++) {
data[i].unshift(header[i])
}
// data.unshift(header)
for (let i = multiHeader.length - 1; i > -1; i--) {
data[i].unshift(multiHeader[i])
}
var ws_name = sheetname
var wb = new Workbook()
var ws = []
for (var j = 0; j < header.length; j++) {
ws.push(sheet_from_array_of_arrays(data[j]))
}
if (merges.length > 0) {
for (var j = 0; j < header.length; j++) {
if (!ws[j]['!merges']) ws[j]['!merges'] = []
merges[j].forEach(item => {
ws[j]['!merges'].push(XLSX.utils.decode_range(item))
})
}
}
// console.log("width", autoWidth)
if (autoWidth) {
/* 设置worksheet每列的最大宽度*/
var colWidth = []
for (var k = 0; k < header.length; k++) {
colWidth.push(
data[k].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
}
}
})
)
)
}
/* 以第一行为初始值*/
const result = []
for (var k = 0; k < colWidth.length; k++) {
result[k] = colWidth[k][0]
for (let i = 1; i < colWidth[k].length; i++) {
for (let j = 0; j < colWidth[k][i].length; j++) {
if (!result[k][j]) {
continue
}
if (result[k][j]['wch'] < colWidth[k][i][j]['wch']) {
result[k][j]['wch'] = colWidth[k][i][j]['wch']
}
}
}
}
// 分别给sheet表设置宽度
for (var l = 0; l < result.length; l++) {
ws[l]['!cols'] = result[l]
}
}
/* add worksheet to workbook */
for (var k = 0; k < header.length; k++) {
wb.SheetNames.push(ws_name[k])
wb.Sheets[ws_name[k]] = ws[k]
}
// 设置单元格框线
const borderAll = {
top: {
style: 'thin'
},
bottom: {
style: 'thin'
},
left: {
style: 'thin'
},
right: {
style: 'thin'
}
}
for (var k = 0; k < header.length; k++) {
var dataInfo = wb.Sheets[wb.SheetNames[k]]
// 给所有单元格加上边框,内容居中,字体,字号
for (var i in dataInfo) {
if (
i === '!ref' ||
i === '!merges' ||
i === '!cols' ||
i === '!rows' ||
i === 'A1'
) {
} else {
dataInfo[i + ''].s = {
border: borderAll,
alignment: {
horizontal: 'left',
vertical: 'left'
},
font: {
name: '微软雅黑',
sz: 10
}
}
}
}
}
if (merges.length > 0) {
// 表头合并
const titleArr = ['A1', 'B1', 'C1', 'D1', 'E1', 'F1', 'G1', 'H1', 'I1', 'J1', 'K1', 'L1', 'M1', 'N1', 'O1', 'P1', 'Q1', 'R1', 'S1', 'T1', 'U1', 'V1', 'W1', 'X1', 'Y1', 'Z1']
for (var k = 0; k < header.length; k++) {
var dataInfo = wb.Sheets[wb.SheetNames[k]]
titleArr.some(function(v) {
const a = merges[k][0].split(':')
if (v === a[1]) {
if (!dataInfo[v]) {
dataInfo[v] = {}
}
dataInfo[v].s = {}
return true
} else {
if (!dataInfo[v]) {
dataInfo[v] = {}
}
dataInfo[v].s = {}
}
})
// 设置主标题样式
dataInfo['A1'].s = {
font: {
name: '微软雅黑',
sz: 18,
color: { rgb: '000000' },
bold: true,
italic: false,
underline: false
},
alignment: {
horizontal: 'center',
vertical: 'center'
}
}
}
}
var wbout = XLSX.write(wb, {
bookType: bookType,
bookSST: false,
type: 'binary'
})
saveAs(
new Blob([s2ab(wbout)], {
type: 'application/octet-stream'
}),
`${filename}.${bookType}`
)
}
setMethods.js
import { parseTime } from '@/utils/index'
import { export_json_to_excel } from '@/vendor/Export2Excel'
/**
* Parse the json to excel
* tableJson 导出数据 ; filenames导出表的名字; autowidth表格宽度自动 true or false; bookTypes xlsx & csv & txt
* @param {(Object)} tableJson
* @param {string} filenames
* @param {boolean} autowidth
* @param {string} bookTypes
*/
export function json2excel(tableJson, filenames, autowidth, bookTypes) {
require.ensure([], () => {
var tHeader = []
var dataArr = []
var sheetnames = []
// 合并列对象
var multiHeader = []
// 表格合并位置
var merges = []
for (var i in tableJson) {
tHeader.push(tableJson[i].tHeader)
dataArr.push(formatJson(tableJson[i].filterVal, tableJson[i].tableDatas))
sheetnames.push(tableJson[i].sheetName)
var multiHeaderData = [filenames]
if (tableJson[i].multiHeaderData && tableJson[i].multiHeaderData.length > 0) {
multiHeaderData = tableJson[i].multiHeaderData
}
// 表格标题空白处使用标题填充
for (var j = 1; j < tableJson[i].tHeader.length; j++) {
multiHeaderData.push('')
}
multiHeader.push(multiHeaderData)
// 表格合并位置 从A1->H1
var mergesData = ['A1:H1']
merges.push(mergesData)
}
export_json_to_excel({
header: tHeader,
data: dataArr,
sheetname: sheetnames,
filename: filenames,
autoWidth: autowidth,
bookType: bookTypes,
merges: merges,
multiHeader: multiHeader
})
})
}
// 数据过滤,时间过滤
function formatJson(filterVal, jsonData) {
return jsonData.map(v =>
filterVal.map(j => {
if (j === 'timestamp') {
return parseTime(v[j])
} else {
// 如果 undefine,返回空字符串
if (!v[j]) {
return ''
}
return v[j]
}
})
)
}
// 剪切标题
export function cutValue(target, name) {
var arr = []
for (var i = 0; i < target.length; i++) {
arr.push(target[i][name])
}
return arr
}
调用代码例1:
// 在vue页面引入插件
import { json2excel } from '@/vendor/setMethods'
// 例
// tHeader= [[表头名称1,表头名称1,表头名称1],[表头名称2]]
// filterVal= [[columnName1,columnName1,columnName1],[columnName2]]
// tableDatas= [[{columnName1:1,columnName2:2},{},{}],[{}]]
// sheetName= ['sheet1','sheet2','sheet3']
methods: {
// 导出报表
handleDownload(sheetLen) {
var that = this
var excelDatas = []
for (let i = 0; i <= sheetLen; i++) {
var data = {
tHeader: that.downIndexData.tHeaders[i], // sheet表一头部
filterVal: that.downIndexData.filterVals[i], // 表一的数据字段
tableDatas: that.downIndexData.datas[i], // 表一的整体json数据
sheetName: that.downIndexData.sheetNames[i] // 表一的sheet名字
}
excelDatas.push(data)
}
const fileName = '月度报表'
json2excel(excelDatas, fileName, true, 'xlsx')
}
}
调用代码例2(导出单个sheet):
var fileName = data.year + '年' + data.timeRange + '月' + data.reportName + data.orgName
const tHeader = [ '排序', '指标名称', '单位', '填报值', '上期数据', '指标说明', '备注' ]
const filterVal = [ 'indexSort', 'indexName', 'unit', 'value', 'termValue', 'describe', 'remark' ]
var excelDatas = []
var sheet = {
tHeader: tHeader, // sheet表一头部
filterVal: filterVal, // 表一的数据字段
tableDatas: that.downData, // 表一的整体json数据
sheetName: fileName // 表一的sheet名字
}
excelDatas.push(sheet)
json2excel(excelDatas, fileName, true, 'xlsx')
调用代码例3(导出多个sheet):
downReportMony: async function() {
var that = this
if (that.crud) {
that.crud.loading = true
}
that.downLoading = true
var excelDatas = []
var fileName = that.multipleSelection[0].orgName + '报表'
for (const data of that.multipleSelection) {
await that.getTableData(data)
await that.setDataIndex()
// 合并表头名称
var sheetTitleName = data.year + '年' + data.timeRange + '月' + data.orgName + data.reportName
const tHeader = ['排序', '指标名称', '单位', '填报值', '上期数据', '指标说明', '备注']
const filterVal = ['indexSort', 'indexName', 'unit', 'value', 'termValue', 'describe', 'remark']
var sheet = {
tHeader: tHeader, // sheet表一头部
filterVal: filterVal, // 表一的数据字段
tableDatas: that.downData, // 表一的整体json数据
multiHeaderData: [sheetTitleName],
sheetName: data.timeRange + '月' // 表一的sheet名字
}
excelDatas.push(sheet)
}
json2excel(excelDatas, fileName, true, 'xlsx')
if (that.crud) {
that.crud.loading = false
}
that.downLoading = false
that.onlineReportVisible = false
}
最终合并列导出效果
vue2.5版本的例子,其他版本的vue,引入方式可能会不一样
@font-face { font-family: "yourDictFontAwesome"; src: url("chrome-extension://nnijdpomjcmgahgjcdgimjldkopghaef/lib/fontawesome-webfont.ttf") format("truetype"); font-weight: normal; font-style: normal }
vue Export2Excel 导出文件的更多相关文章
- vue+element 使用Export2Excel导出表格组件
下载表格组件是根据我自己的业务需求来封装的 使用的是vue中 xlsx 的插件,需要安装新的依赖及配置 仅供参考 不保证和你百分百匹配 安装依赖 npm install -S file-saver x ...
- vue项目中使用 SheetJS / js-xlsx 导出文件
1. npm install xlsx 2. 在App.vue 中引入xlsx import * as XLSX from 'xlsx'; // 数据导出导入所需要的依赖 3. 使用xlsx 3 ...
- vue基于Blob.js和 Export2Excel.js做前端导出
1安装三个依赖包 npm install -S file-saver@2.0.2 npm install -S xlsx@0.15.6 npm install -D script-loader@0.7 ...
- 前端用vue怎么接收并导出文件
window.location.href = "excel地址" 如果是 get 请求,那直接换成 window.open(url) 就行了 创建一个隐藏的 iframe,把 if ...
- vue中把table导出表格excel
1.首先下载2个js,我的百度网盘有 2.安装依赖 npm install -S file-saver xlsx(这里其实安装了2个依赖) npm install -D script-loader 3 ...
- 【转】手摸手,带你用vue撸后台 系列三(实战篇)
前言 在前面两篇文章中已经把基础工作环境构建完成,也已经把后台核心的登录和权限完成了,现在手摸手,一起进入实操. Element 去年十月份开始用vue做管理后台的时候毫不犹豫的就选择了Elemen, ...
- 在vue中导出excel表格
初学者学习vue开发,想把前端项目中导出Excel表格,查了众多帖子,踩了很多坑,拿出来与大家分享一下经验. 安装依赖 //npm npm install file-saver -S npm inst ...
- vue导出数据excel
下载两个依赖 npm install file-save xlsx 创建两个文件 Blob.js与Export2Excel.js 参考地址:文件地址 在Export2Excel.js中修改引入地址,注 ...
- webpack构建vue项目(再谈配置)
webpack配置起来确实麻烦,这不,之前用刚配好了vue1+的版本,结果在(部分)安卓机上测试,发现存在开启热加载(dev-server)的情况下不能识别vue语法的问题,试了很多方法,都没能很好的 ...
随机推荐
- CMake编译OpenCV4.0时opencv_ffmpeg.dll等下载失败的解决思路总结
一.Configure会报一些红色的警告信息,比如: 1 CMake Warning at cmake/OpenCVDownload.cmake:193 (message): 2 FFMPEG: Do ...
- innodb为什么需要doublewrite(转)
InnoDB的page size默认是16KB,而操作系统的一个block size是4KB,磁盘io block则更小.那么InnoDB的page刷到磁盘上要写4个操作系统block,在极端情况下( ...
- python + appium 执行报错整理
1.driver.find_element_by_id("com.taobao.taobao:id/searchEdit").send_keys("adidas" ...
- rgw使用boto3生成可以访问的预签名url
前言 如果想访问一个ceph里面的s3地址,但是又不想直接提供secrect key的时候,可以通过预签名的方式生成url 生成方法 下载boto3 脚本如下 cat s3.py import bot ...
- Spark3.0.1各种集群模式搭建
对于spark前来围观的小伙伴应该都有所了解,也是现在比较流行的计算框架,基本上是有点规模的公司标配,所以如果有时间也可以补一下短板. 简单来说Spark作为准实时大数据计算引擎,Spark的运行需要 ...
- Kubernetes K8S之Taints污点与Tolerations容忍详解
Kubernetes K8S之Taints污点与Tolerations容忍详解与示例 主机配置规划 服务器名称(hostname) 系统版本 配置 内网IP 外网IP(模拟) k8s-master C ...
- hackrf GPS欺骗
在对GPS欺骗之前,先对GPS的知识做一个简单的介绍 GPS 系统本身非常复杂, 涉及到卫星通信等各个领域. 这里只是简单介绍一下. 我们通常所说的 GPS 全球定位系统是由美国国防部建造完成. 目前 ...
- SpringSecurity了解
在web开发中,安全第一位!!过滤器.拦截器~ 属于非功能性需求. 做网站:安全应该在什么时候考虑?设计之初!! 漏洞,隐私泄露~ 假设架构一旦确定~ shiro和SpringSecurity的区别: ...
- 面试半年,凭借这份JVM面试题,我终于拿到了字节跳动的offer!
内存区域 虚拟机栈生命周期与线程相同,描述的是Java 方法执行的内存模型,每个方法在执行的时候都会创建一个栈帧,用于存取局部变量表.操作数栈.动态链接.方法出口等信息本地方法栈与虚拟机栈作用相似,只 ...
- NO.A.0010——Windows常用快捷键使用教程
小娜操作: Win + C: 打开Cortana微软小娜,并开始聆听...... Win + Q: 打开Cortana: Win + S: 打开Cortana:sdfghjkrtgyh XBOX操作: ...