微信小程序云开发数据导出为Excel下载并打开

该文描述了一个通过云函数处理数据,将数据写入Excel文件的过程。首先安装node-xlsx库,然后将数据保存到Excel并存储到云端。前端调用云函数,获取文件地址后下载Excel,并在下载完成后删除云端文件。
摘要由CSDN通过智能技术生成

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);
              }
            })
          })
        }
      })

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值