1.创建云函数
2.安装node-xlsx
类库(node类库
)
打开终端安装node-xlsx
类库并重现上传部署
npm install node-xlsx
3.把数据存在excel里面,把excel存在云存储里并返回对应的云文件地址
前端传数据到云函数,云函数接收数据数组,添加到excel中
async function get_excel(data) {
let today_order = data;
let dataCVS = `order-${Math.floor(Math.random()*1000000000)}.xlsx` //excel文件名
let alldata = [];
let row = ['售点名称', '订单号','商品名称','购买数量', '顾客姓名', '联系方式']; //excel首行字段
alldata.push(row);
//遍历添加数组,和上面的首行字段要一一对应
for(let i=0; i<today_order.length; i++){
let arr = [];
arr.push(today_order[key].point_name);
arr.push(today_order[i]._id);
arr.push(today_order[i].goods_name);
arr.push(today_order[i].goods_count);
arr.push(today_order[i].username);
arr.push(today_order[i].phone);
alldata.push(arr)
}
var buffer = await xlsx.build([{
name: "mySheetName",
data: alldata
}]);
return await cloud.uploadFile({
cloudPath: dataCVS,
fileContent: buffer,
}).then(res=>{
return {
code: 200,
data: res
}
})
}
4.拿到地址后下载excel文件
wx.showLoading({
success: res => {
let today_order = this.data.today_order
wx.cloud.callFunction({
name: 'index',
data: {
action: 'get_excel',
data: today_order
}
}).then(res => {
wx.hideLoading()
const fileID = res.result.data.data.fileID
wx.cloud.downloadFile({
fileID: fileID,
success: res => {
const filePath = res.tempFilePath
wx.showToast({
title: '文件下载成功',
icon: "none",
duration: 1500
})
wx.cloud.deleteFile({
fileList: [fileID],
success(res) {
console.log('删除文件成功')
},
fail(err) {
console.log(err)
}
})
setTimeout(() => {
wx.openDocument({
filePath: filePath,
success: function (res) {
console.log('打开文档成功')
}
})
}, 1000)
},
fail: err => {
console.log("文件下载失败", err);
}
})
})
}
})