小程序云函数从云数据下载excal

小程序云函数从云数据下载excal

看效果
在这里插入图片描述

1.新建云函数

在这里插入图片描述

2.部署依赖

在getexcal的云函数下面右键选择在终端打开

npm install node-xlsx

在这里插入图片描述
安装好的标志
在这里插入图片描述

3.云函数代码
const cloud = require('wx-server-sdk')
cloud.init({
    env: "school-5g4jy58j60c7811c"   //编写云开发环境
})
const xlsx = require('node-xlsx')    //导入Excel类库
const db = cloud.database()   //声明数据库对象
const _ = db.command
exports.main = async (event, context) => {   //主函数入口
    try {
        let StuInfo = await db.collection('rundata').get()   //将获取到的数据对象赋值给变量,接下来需要用该对象向Excel表中添加数据
        let dataCVS = `studentInfo-${Math.floor(Math.random()*1000000000)}.xlsx`
        //声明一个Excel表,表的名字用随机数产生
        let alldata = [];
        let row = ['姓名', '标识','跑步时间','里程数','跑步日期']; //表格的属性,也就是表头说明对象
        alldata.push(row);  //将此行数据添加到一个向表格中存数据的数组中
//接下来是通过循环将数据存到向表格中存数据的数组中
        for (let key = 0; key<StuInfo.data.length; key++) {
            let arr = [];
            arr.push(StuInfo.data[key].name);
            arr.push(StuInfo.data[key].openid);
            arr.push(StuInfo.data[key].runtime);
            arr.push(StuInfo.data[key].lichenshun);
            arr.push(StuInfo.data[key].pbrq);
            alldata.push(arr)
            }
            var buffer = await xlsx.build([{   
            name: "mySheetName",
            data: alldata
            }]); 
            //将表格存入到存储库中并返回文件ID
            return await cloud.uploadFile({
            cloudPath: dataCVS,
            fileContent: buffer, //excel二进制文件
            })
    } catch (error) {
        console.error(error)
    }
}

4.index
<view>
   <view class="info">学生信息的导出</view>
</view>
  <!-- 下载excel -->
  <view class="uploader" >
    <view class="uploader-text" bindtap="downloadexcel">
      <text>生成excel</text>
    </view>
  </view>
  <view wx:if="{{tempFileURL}}">
  <view class="uploader" >
    <view class="uploader-text" catchtap='downloadFile'>
      <text>打开excel</text>
    </view>
  </view>
</view>
5.js
// pages/runmessage/runmessage.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
   url:'',
   tempFileURL:'',
   showUrl:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  downloadexcel:function(){
  wx.cloud.callFunction({
    name:"getexcal",
    // data:{
    //   arropenid:arropenid
    // },
     complete:res=>{
       wx.cloud.getTempFileURL({      //获取文件下载地址(24小时内有效)
         fileList:[res.result.fileID],
         success:res=>{
           this.setData({
             tempFileURL:res.fileList[0].tempFileURL,
             showUrl:true
           })
           wx.setClipboardData({   //复制刚获取到链接,成功后会自动弹窗提示已复制
         data:this.data.tempFileURL,
         success (res) {
           wx.getClipboardData({
             success (res) {
               this.setData({
                 url:res.data
               })
               console.log(res.data) // data
             }
           })
         }
       })
         }
       })
     }
   })
  },




    //下载excel
 /**
* 下载文件并预览
*/
downloadFile: function(e) {
  console.log(e);
  let type = e.currentTarget.dataset.type;
  let url = e.currentTarget.dataset.url;
  switch (type) {
  case "pdf":
      url += 'pdf';
      break;
  case "word":
      url += 'docx';
      break;
  case "excel":
      url += 'xlsx';
      break;
  default:
      url += 'pptx';
      break;
  }
  wx.downloadFile({
      url: this.data.tempFileURL,
      header: {},
      success: function(res) {
          var filePath = res.tempFilePath;
          console.log(filePath);
          wx.openDocument({
              filePath: filePath,
              success: function(res) {
                  console.log('打开文档成功')
              },
              fail: function(res) {
                  console.log(res);
              },
              complete: function(res) {
                  console.log(res);
              }
          })
      },
      fail: function(res) {
          console.log('文件下载失败');
      },
      complete: function(res) {},
  })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
6.注意事项

每次云函数更新后都要部署。
不部署每次都会找不见或者是报错。
云函数的env一定要换成自己的appid

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code袁

你的支持是我莫大的幸运

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值