vue2.x 将table 内容导出excel 下载(转换页面table数据)

目前仅支持chrome?downloadjs需自行引入加载 对应的tab HTMLCollection 也应根据你的UI组件进行替换



table.png


QQ图片20180122224557.png
<template lang="pug">
btn(:stype="stype",:size="size",@click="exportOffice(tid)")
slot
template(v-if="!$slots.default") {{label}}
</template>

<script>
/**
* bootstrap 4.x --> components --> table-->table
*
* @param {String} label 按钮名称
* @param {String} stype 样式
* @param {String} size 大小
*
* 注意以上参数为内置按钮参数 可根据你目前使用的UI组件进行修改
*
* @param {String} tid 表格ID
* @param {String} xlsname excel名称
* @param {String} filters 需过滤的cell className
*
* @date 2018-1-22
*
* @version v1.0.0 beta
*
* @important 注意目前仅支持chrome下使用
*
**/
import download from 'downloadjs'
import btn from '@/components/comp/button'
export default {
name: 'tableToExcel',
components: {
btn
},
props: {
// btn 组件参数
label: String,
stype: String,
size: {
type: String,
default: 'sm'
},
tid: String,
xlsname:String,
filters: String
},
methods: {
base64ToBlob: function(data, mime) {
let base64 = window.btoa(window.unescape(encodeURIComponent(data)))
let bstr = atob(base64)
let n = bstr.length
let u8arr = new Uint8ClampedArray(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], { type: mime })
},
exportOffice(tableID) {
let elms = document.getElementById(tableID).cloneNode(true)
let table = elms.childNodes[1].childNodes[0]
// table根据你的ui组件修改对应的HTMLCollection
let rows = table.rows.length
let cells = table.rows.item(0).cells.length
let tableArr = table.getElementsByClassName(this.filters)
for (let i = 0; i < rows; i++) {
table.rows<em>.deleteCell(cells-1)
}
let excelContent = table.innerHTML
let excelFile = `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html4 ... Bmeta name=ProgId content=Excel.Sheet> <meta name=Generator content="Microsoft Excel 11"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><!--[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>${excelContent}</table></body></html>`
let blob = this.base64ToBlob(excelFile, 'application/vnd.ms-excel')
download(blob, this.xlsname||this.$route.name+moment().format('x'), 'application/vnd.ms-excel')
}
}
}
</script>

0 个评论

要回复文章请先登录注册