微信小程序云开发之将云数据库信息导出到Excel表格并复制下载链接

在必要的情况下,我们需要将数据库的信息导入到Excel表格中。这时候,通过云函数很容易可以实现该功能。

先看一下效果:
在这里插入图片描述
在这里插入图片描述
我们将分为以下几个步骤:

  1. 安装导出Excel表格的模块
  2. 编写云函数代码
  3. 导出表格并复制下载链接

一、安装模块
新建云函数,右键该云函数在终端中开打。
输入命令:

npm install node-xlsx

在这里插入图片描述
安装成功如下图所示:
在这里插入图片描述
二、编写云函数代码

打开index.js文件,我们编写云函数代码:

const cloud = require('wx-server-sdk')
cloud.init({
    env: "campusdada-45zin"   //编写云开发环境
})
const xlsx = require('node-xlsx')    //导入Excel类库
const db = cloud.database()   //声明数据库对象
const _ = db.command
exports.main = async (event, context) => {   //主函数入口
    try {
        let StuInfo = await db.collection('managementfo').where({
            openID:_.in(event.arropenid)
        }).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].managename);
            arr.push(StuInfo.data[key].managesex);
            arr.push(StuInfo.data[key].manageplace);
            arr.push(StuInfo.data[key].manageparment);
            arr.push(StuInfo.data[key].manageclass);
            arr.push(StuInfo.data[key].managedorm);
            arr.push(StuInfo.data[key].managetele);
            arr.push(StuInfo.data[key].manageorganization);
            arr.push(StuInfo.data[key].managebranch);
            arr.push(StuInfo.data[key].managede);
            arr.push(StuInfo.data[key].managedeapp);
            arr.push(StuInfo.data[key].managedemanage);
            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)
    }
}

三、导出表格并复制下载链接

在引用云函数的js文件中编写代码:

wx.cloud.callFunction({
     name:"StuExcel",
      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) {
		            console.log(res.data) // data
		          }
		        })
		      }
		    })
          }
        })
      }
    })

到这里就完成了将数据从数据库中导出来的功能,如果对你有用,就点个赞吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章