前端请求
先配置vue脚手架里的request请求,在响应请求前加入以下判断
const res = response.data // 处理post下载 if (response.data.type === 'application/vnd.openxmlformats') { return response.data } exportArticleStat({'cids':cids}).then(res=>{ const content = res; const blob = new Blob([content]); const fileName = "推送任务数据分析导出.xlsx"; if ("download" in document.createElement("a")) { // 非IE下载 const elink = document.createElement("a"); elink.download = fileName; elink.style.display = "none"; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); URL.revokeObjectURL(elink.href); // 释放URL 对象 document.body.removeChild(elink); } else { // IE10+下载 navigator.msSaveBlob(blob, fileName); } })后端请求处理:注意在响应前要加以下响应头
router.post('/mp/exportArticleStat', async (ctx, next) => { await Push.exportArticleStat(ctx).then(function(res) { ctx.set('Content-Type', 'application/vnd.openxmlformats'); ctx.set("Content-Disposition", "attachment; filename=" + "terminal.xlsx"); ctx.body = res; }).catch(err => { ctx.body = { code: -1, msg: err } }) })以下为下载excel的接口方法
/** * 图文分析数据导出 */ const exportArticleStat = function(ctx){ return new Promise(function (resolve, reject) { let cids = ctx.request.body.cids; async.map(cids,function (item,callback) { articleAnalysis(item.cid).then(res=>{ callback(null,{"pushname":item.pushname,"data":res}) }) },function (err,results) { excelUtils.articleStatExcel(results).then(res=>{ resolve(res) }) }) }) } var xlsx = require('node-xlsx'); const articleStatExcel = function(param){ return new Promise(function (resolve, reject) { let excelData = [] for(let items of param){ let data = [] let hearders = [ '微信号', '推送时间', '截至时间', '标题', '送达人数', '阅读人数', '阅读次数', '原文阅读次数', '原文阅读次数', '分享人数', '分享次数', '收藏人数', '收藏次数', ] data.push(hearders) //处理查询clickhouse 的数据 for (let item of items.data) { for(let it of item.details){ let arr = new Array() arr.push(item.platform) arr.push(it.time) arr.push(it.stat_date) arr.push(it.title) arr.push(it.target_user) arr.push(it.int_page_read_user) arr.push(it.int_page_read_count) arr.push(it.ori_page_read_user) arr.push(it.ori_page_read_count) arr.push(it.share_user) arr.push(it.share_count) arr.push(it.add_to_fav_user) arr.push(it.add_to_fav_count) data.push(arr) } } excelData.push({name: items.pushname,data: data}) } var buffer = xlsx.build(excelData) resolve(buffer) }) }
