在必要的情況下,我們需要將數據庫的信息導入到Excel表格中。這時候,通過雲函數很容易可以實現該功能。
先看一下效果:
我們將分爲以下幾個步驟:
- 安裝導出Excel表格的模塊
- 編寫雲函數代碼
- 導出表格並複製下載鏈接
一、安裝模塊
新建雲函數,右鍵該雲函數在終端中開打。
輸入命令:
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
}
})
}
})
}
})
}
})
到這裏就完成了將數據從數據庫中導出來的功能,如果對你有用,就點個贊吧。