vue. 导出excel或cdv

js

export default {
data() {
return {
tableHeight: 32 * 20 + 34,
bossChannelTypeList: [],
bossBusinessTypeList: [],
platformProductsList: [],
usingPlatformProductsList: []
}
},
computed: {
},
created() {
},
methods: {
/**
* 导出数据为csv
* 
* 
@exportCsv({
title: ["客户编码", "第二列"],
titleForKey: ["accountSn", "accountType"],
data: this.tableData,
head:'名字'
}) 
* 
*/
exportCsv(obj) {
var title = obj.title;
var titleForKey = obj.titleForKey;
var data = obj.data;
for(let i in data){
data[i] = data[i]
for(let j in data[i]){
if(data[i][j]){
data[i][j] = data[i][j] + "\t"
}
if(data[i][j] == null){
data[i][j] = ''
}
}
}
var str = [];
str.push("\uFEFF" + obj.title.join(",") + "\n");
for (var i = 0; i < data.length; i++) {
var temp = [];
for (var j = 0; j < titleForKey.length; j++) {
temp.push(data[i][titleForKey[j]]+"");
}
str.push("\uFEFF" + temp.join(",") + "\n");
}
var blob = new Blob(str, {
type: 'text/plain'
});
var link = document.createElement('a');
link.download = obj.head+'.csv';
link.href = window.URL.createObjectURL(blob);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
},

/**
* 导出数据为excel
* 
* 
* @param {any} [params={}] 
* @param {Array} [params.tableHead] // excel 表头 [{'key':'value'},{},{}]  –  key代表在对应的value表头下 ,要插入哪条信息的key值,value:代表表头要显示的信息
* @param {Array} [params.tableData] // excel 数据
* @param {String}[params.fileName] // 下载文件名称
* 
*/
exportResultToExcel(params) {
let paramsClone = JSON.parse(JSON.stringify(params))
let titleForKey = paramsClone.tableHead.map(i => Object.keys(i)[0])
let excelHeader = paramsClone.tableHead.map(i => i[Object.keys(i)[0]])
let excelTableData = paramsClone.tableData.map(v => paramsClone.tableHead.map((j, ind) => v[titleForKey[ind]]))
let excelData = []
excelData.push(excelHeader)
excelTableData = excelData.concat(excelTableData)
let now = this.DateFormat(+new Date(), 'yyyy-MM-dd hh:mm:ss')
this.downExcel(excelTableData, `${params.fileName}-${now}`)
},
downExcel(json, downName, type) {
let keyMap = []
for (let k in json[0]) {
keyMap.push(k)
}
let tmpdata = [] // 用来保存转换好的json
json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
v: v[k],
position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
}))).reduce((prev, next) => prev.concat(next)).forEach(function (v) {
tmpdata[v.position] = {
v: v.v
}
})
let outputPos = Object.keys(tmpdata) // 设置区域,比如表格从A1到D10
let tmpWB = {
SheetNames: ['mySheet'], // 保存的表标题
Sheets: {
'mySheet': Object.assign({},
tmpdata, // 内容
{
'!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] // 设置填充区域
})
}
}
let tmpDown = new Blob([this.s2ab(xlsx.write(tmpWB,
{ bookType: (type === undefined ? 'xlsx' : type), bookSST: false, type: 'binary' } // 这里的数据是用来定义导出的格式类型
))], {
type: ''
}) // 创建二进制对象写入转换好的字节流
var href = URL.createObjectURL(tmpDown) // 创建对象超链接
let link = document.createElement('a')
link.href = href // 绑定a标签
link.download = downName + '.xlsx'//配置下载的文件名
link.click() // 模拟点击实现下载
setTimeout(function () { // 延时释放
URL.revokeObjectURL(tmpDown) // 用URL.revokeObjectURL()来释放这个object URL
}, 100)
},
s2ab: function (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
},
getCharCol: function (n) { // 将指定的自然数转换为26进制表示。映射关系:[0-25] -> [A-Z]。
let s = ''
let m = 0
while (n > 0) {
m = n % 26 + 1
s = String.fromCharCode(m + 64) + s
n = (n - m) / 26
}
return s
},
// 日期格式化工具
DateFormat: (ms, fmt) => {
if (ms == null || ms == undefined || (Object.prototype.toString.call(ms) === '[object String]' && ms.length == 0)) return
let val = new Date(ms)
let o = {
"M+": val.getMonth() + 1, //月份 
"d+": val.getDate(), //日 
"h+": val.getHours(), //小时 
"m+": val.getMinutes(), //分 
"s+": val.getSeconds(), //秒 
"q+": Math.floor((val.getMonth() + 3) / 3), //季度 
"S": val.getMilliseconds() //毫秒 
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (val.getFullYear() + "").substr(4 - RegExp.$1.length))
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
}
}
return fmt
}
}
}

methods{
      // 函数请求
     csv请求格式:
        this.exportCsv({
            title: ["对账单号","对账日期"],
            titleForKey: ["billNo","checkDate"],
            data: arr,
            head: '交易对账结果'+Date.parse(new Date())
       })

       xlsx请求格式:
       this.exportResultToExcel({
           tableHead: [
                {'billNo': '对账单号'},
                {'checkDate': '对账日期'},
                 ... ...
            ],
            tableData: arr,
            fileName: '交易对账结果'+Date.parse(new Date())
         })
}

你可能感兴趣的:(vue. 导出excel或cdv)