1.首先构建node.js云函数,安装类库
右键点击创建的云函数,在外部终端输入npm install node-xlsx下载安装
npm install node-xlsx
npm install --production
云函数代码(上传并部署云函数依赖)
const cloud = require('wx-server-sdk')
cloud.init({
env: "云开发环境"
})
//操作excel用的类库
const xlsx = require('node-xlsx');
// 云函数入口函数
exports.main = async(event, context) => {
try {
let user= event.user
let dataCVS = `{Math.floor(Math.random()*1000000000)}.xlsx`
let alldata = [];
let row = ['序号', '呢称','openid']; //表属性
alldata.push(row);
for (let key in user) {
let arr = [];
arr.push(export[key].id);
arr.push(export[key].name);
arr.push(export[key].openid);
alldata.push(arr)
}
//把数据保存到excel里
var buffer = await xlsx.build([{
name: "mySheetName",
data: alldata
}]);
//把excel文件保存到云存储里
return await cloud.uploadFile({
cloudPath: dataCVS,
fileContent: buffer, //excel二进制文件
})
} catch (e) {
console.error(e)
return e
}
}
js代码
data: {
fileUrl: ""//存储文件地址
},
async savaExcel() {
let that = this
console.log(that.data.id)
var id=that.data.id
let count_y=await wx.cloud.database().collection('job_word').where({
id: id
}).count()
count_y=count_y.total
console.log('====',count_y);
let arr=[]
for (let x = 0; x < count_y; x+=20) {
let list=await wx.cloud.database().collection('job_word').where({
id: id
}).skip(x).get()
arr=arr.concat(list.data)
console.log('====',list);
}
wx.cloud.callFunction({
name: "export",
data: {
user: arr
},
success(res) {
console.log("保存成功", res)
that.getFileUrl(res.result.fileID)
},
fail(res) {
console.log("保存失败", res)
}
})
},
//获取云存储文件下载地址,这个地址有效期一天
getFileUrl(fileID) {
let that = this;
wx.cloud.getTempFileURL({
fileList: [fileID],
success: res => {
console.log("文件下载链接", res.fileList[0].tempFileURL)
that.setData({
fileUrl: res.fileList[0].tempFileURL
})
wx.showToast({
title: '数据导出成功',
icon: 'success',
duration: 2000
})
},
fail: err => {
}
})
},
// 预览文件
open(){
var that=this
wx.downloadFile({
url: that.data.fileUrl,
success: (res) => {
that.setData({
httpfile: res.tempFilePath
})
console.log(that.data.httpfile)
//预览文件
wx.openDocument({
filePath: that.data.httpfile,
success: res => {
},
fail: err => {
console.log(err);
}
})
}
})
},
//复制excel文件下载链接
copyFileUrl() {
let that=this
wx.setClipboardData({
data: that.data.fileUrl,
success(res) {
wx.getClipboardData({
success(res) {
console.log("复制成功",res.data)
}
})
}
})
},
wxml(自己设置点击事件)