项目需要导出excel表格,本来吧,这些完全可以调后端的接口获取生成好的excel文件,想想多简单方便啊。不过,爱折腾的我放弃了这中简单舒适的生活!况且,有后端小伙伴竟然认为前端无法生成excel文件!作为前端的我可不乐意啦哈!虽然前端在处理文件上的确比不上后端(实话),但是弄个小小的excel文件还是没问题的哦!
项目地址:
github :https://github.com/yl1988/exportexcel.git
码云:https://gitee.com/dongche/exportexcel.git
开始尝试
刚开始的时候,用了一个比较简单方便的办法,就是将数据塞进对应的table标签里面,在吧table塞到html里面,然后转码为base64,最后通过window.location.href来执行下载。
代码如下(仅展示相关方法)
getExcelData(data){
//data就是从后端获取到的数据,需要做下处理
//序号 日期 图片地址
let excelData = []
// 将对象属性名按要求排好
for (let i = 0; i < data.length; i++){
let {id,time,img}=data[i]
excelData.push({
id,
time,
img
})
}
let str = '<tr><td style="mso-number-format:\'\@\';">序号</td><td style="mso-number-format:\'\@\';">日期</td><td>图片地址</td></tr>'
console.log(excelData)
this.exportExcel(excelData,str)
},
/*导出excel*/
exportExcel(data,str) {
//循环遍历,每行加入tr标签,每个单元格加td标签
for (let i = 0; i < data.length; i++) {
str += '<tr>'
for (let item in data[i]) {
//增加\t为了不让表格显示科学计数法或者其他格式
let dataItem = ((data[i][item] === 0) || data[i][item]) ? data[i][item] : ''
str += `<td>${ dataItem.toString() + '\t'}</td>`
}
str += '</tr>'
}
//Worksheet名
let worksheet = 'Sheet1'
let uri = 'data:application/vnd.ms-excel;base64,'
//下载的表格模板数据
let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet> <x:Name>${worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>${str}</table></body></html>`;
//下载模板
window.location.href = uri + window.btoa(unescape(encodeURIComponent(template)))
},
这简单方便,而且也成功了,但是有点问题,比如我的序号是字符串,但是属于字符串类型数字,这样导出以后,序号直接变成科学计数了,还有日期,如果是2020-05-02,这样的没问题,但是如果是2020-05这样导出来就变成May-05,TMD啥情况啊。后来查阅啦相关资料,做了如下改变
//增加\t为了不让表格显示科学计数法或者其他格式
let dataItem = ((data[i][item] === 0) || data[i][item]) ? data[i][item] : ‘’
str += <td>${ dataItem.toString() + '\t'}</td>
给td里面加上样式style="mso-number-format:\'\@\';",
查阅资料说是让单元格以文本显示的,按道理说是没问题了,不过再次导出后,仍然么有解决!
新的方法
经过一番折腾和查阅资料后,找到新的方法,这个方法麻烦好多,不过效果也杠杆的。我将代码整理了一下,感觉还行。
首先需要用的的包:xlsx(用于将json数据写成excel类型格式数据),file-saver(用于下载文件,兼容ie10)
另外还需要将excel类型数据转成buffer,在转成blob格式数据
下面将整理好的代码贴上
vue创建项目
首先用vue-cli3创建一个项目,便于测试
vue create exceltest
创建好后安装依赖
npm install -S file-saver xlsx
npm install -D script-loader
为了方便测试,我把其他多余的文件都删了,然后再assets中新建blob.js和exportExcel.js。
项目目录结构如下:
exportExcel.js中暴露了两个导出excel的方法,一个是将后端获取的数据导出为excel文件,一个是将页面里面table标签的内容导出为excel文件,使用起来非常简单
看app.vue
<template>
<div id="app">
<button @click="exportExcel">导出</button>
<button @click="exportOnlieExcel">导出在线表格</button>
<table id="table">
<thead>
<tr>
<td>序号</td>
<td>事件</td>
<td>头像</td>
<td>头像2</td>
<td>头像3</td>
<td>头像4</td>
<td>头像5</td>
<td>头像6</td>
<td>头像7</td>
<td>头像8</td>
<td>头像9</td>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in imgList" :key="index">
<td >{{item.id}}</td>
<td >{{item.time}}</td>
<td >{{item.img}}</td>
<td >{{item.img2}}</td>
<td >{{item.img3}}</td>
<td >{{item.img4}}</td>
<td >{{item.img5}}</td>
<td >{{item.img6}}</td>
<td >{{item.img7}}</td>
<td >{{item.img8}}</td>
<td >{{item.img9}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import {export_json_to_excel,export_table_to_excel} from './assets/exportExcel'
export default {
data(){
return{
//假设这就是从后端获取的数据,当然这里在页面table标签里面也用它
imgList:[
{
id:'8998392393923849234',
time:'2020-05',
img:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img2:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img3:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img4:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img5:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img6:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img7:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img8:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
},
{
id:'8998392393923849234',
time:'2020-05',
img2:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img3:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img4:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img5:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img6:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
},
{
id:'8998392393923849234',
time:'2020/05/26',
img2:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img3:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img4:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img5:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img6:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
},
{
id:'89983923939232345234532849234',
time:'2020/05',
img2:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img3:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img5:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img6:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
}, {
id:'89983923939238243532452349234',
time:'2020-05',
img2:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img3:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img4:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img5:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img6:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
}, {
id:'899839239392345324523453849234',
time:'2020-05',
img2:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img3:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
img4:'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel',
}, {
id:'899839239392384934523542352352353234',
time:'2020-05-03',
img:'http://www.baidu.com?id=xxxdddddddddddddddddddddd',
name:'历史'
},
]
}
},
methods:{
// 导出表格(基于json数据)
exportExcel() {
const tHeader = ["序号", "日期", "图片地址"];// 设置Excel的表格第一行的标题,需要啥就设置啥
const filterVal = ["id", "time", "img"]; // 标题对应的tableData里对象的属性字段
const data = this.imgList.map(v => filterVal.map(j => v[j]))
export_json_to_excel(tHeader, data, "工资表"); //三个参数:标题,数据,文件名
},
// 导出table由标签数据生成的表格
exportOnlieExcel(){
export_table_to_excel('table','工资表')//两个参数:数据,文件名
}
}
}
</script>
<style lang="less">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>
用法和解释,代码里面都有,不多说。
封装麻烦点,用起来是真的简单很多
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));
exportExcel.js,整理了一下,献上,代码里面都做了相关注释和说明,就不多逼逼了
import './blob'
import XLSX from 'xlsx'
import saveAs from 'file-saver'
// 获取在线表格数据
function generateArray(table) {
let out = []
let rows = table.querySelectorAll('tr')
let ranges = []
for (let R = 0; R < rows.length; ++R) {
// let outRow = []
let row = rows[R]
let columns = row.querySelectorAll('td')
let outRow=getOutRowAndRanges(columns,ranges,R)
out.push(outRow)
}
// 表格有可能用了th做头部
let thead=rows[0].querySelectorAll('th')
let theadData=getOutRowAndRanges(thead,ranges,0)
theadData.length && (out[0]=theadData)
return [out, ranges]
}
//获取每一行的值和合并值
function getOutRowAndRanges(columns,ranges,R) {
let outRow = []
for (let C = 0; C < columns.length; ++C) {
let cell = columns[C]
let colspan = cell.getAttribute('colspan')
let rowspan = cell.getAttribute('rowspan')
let cellValue = cell.innerText.toString()
ranges.forEach(function(range) {
if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
for (let 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.toString() : null)
//Handle Colspan
if (colspan){
for (let k = 0; k < colspan - 1; ++k) outRow.push(null)
}
}
//ranges是传递进来的,不需要反出
return [...outRow]
}
// 时间格式函数
function datenum(v, date1904) {
if (date1904) v += 1462
let epoch = Date.parse(v)
return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000)
}
// 生成excel表数据
function sheet_from_array_of_arrays(data, opts) {
let ws = {}
let 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
let cell = {
v: data[R][C]
}
if (cell.v == null) continue
let 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 = {}
}
// 获取buffer
function getBuffer(s) {
let buf = new ArrayBuffer(s.length)
let view = new Uint8Array(buf)
for (let i = 0; i !== s.length ;++i) view[i] = s.charCodeAt(i) & 0xFF
return buf
}
// 将在线表格table表格转换成excel
export function export_table_to_excel(id,title) {
let theTable = document.getElementById(id)
let [out, ranges] = generateArray(theTable)
let ws_name = "SheetJS"
let wb = new Workbook(),
ws = sheet_from_array_of_arrays(out)
ws['!merges'] = ranges
wb.SheetNames.push(ws_name)
wb.Sheets[ws_name] = ws
let wbout = XLSX.write(wb, {
bookType: 'xlsx',
bookSST: false,
type: 'binary'
})
saveAs(new Blob([getBuffer(wbout)], {
type: "application/octet-stream"
}), (title || '表格')+".xlsx")
}
// 将json数据转换成excel
export function export_json_to_excel(th, data, defaultTitle) {
data.unshift(th)
let ws_name = "SheetJS"
let wb = new Workbook(),
ws = sheet_from_array_of_arrays(data)
wb.SheetNames.push(ws_name)
wb.Sheets[ws_name] = ws
let wbout = XLSX.write(wb, {
bookType: 'xlsx',
bookSST: false,
type: 'binary'
})
let title = defaultTitle || '列表'
saveAs(new Blob([getBuffer(wbout)], {
type: "application/octet-stream"
}), title + ".xlsx")
}
最后想说的是,虽然第二种方法目前是效果最好,但是我还是想喜欢第一种方法,不为别的,就因为代码更少。至于出现的问题,等后面有时间定去重新研究下,获取复杂的表格不能实用,不过简单点的相比没问题!
少写几行是几行啊,程序员就这点追求!!!