1、安装nodejs环境
到官网下载安装包(node-v12.14.1-x64.msi),点击下一步一直安装到底
2、使用命令行模式进入小程序项目云函数文件夹,执行安装excel-export命令,安装完成后,输入node -v测试一下是否安装成功
npm install excel-export
3、在微信开发者工具的小程序云函数文件夹上右键新建node.js云函数,随便输入一个名字,比如excelexport,然后把上一步下载下来的\cloudfunctions\node_modules\excel-export\example文件夹下的styles.xml文件拷贝到excelport文件夹下,这样这个新建的文件夹下就有三个文件
4、修改一下package.json文件,添加excel-export支持
5、修改index.js文件(重点)
// 云函数入口文件
const cloud = require('wx-server-sdk')
const nodeExcel = require('excel-export')
const path = require('path');
cloud.init()
// 云函数入口函数
exports.main = async(event, context) => {
var tableHead = event.excelhead;
var tableMap = {
styleXmlFile: path.join(__dirname, "styles.xml"),
name: Date.now() + "-export",
cols: [],
rows: [],
}
//添加表头 此处要注意格式type,会影响到rows
tableMap.cols = [{
caption: tableHead[0],
type: 'string'
}, {
caption: tableHead[1],
type: 'number'
}, {
caption: tableHead[2],
type: 'string'
}, {
caption: tableHead[3],
type: 'number'
}, {
caption: tableHead[4],
type: 'number'
}]
var output = event.excelbody
//添加每一行数据 此处字段数据需根据业务需求来重新定义
for (var i = 0; i < output.length; i++) {
tableMap.rows[tableMap.rows.length] = [
output[i].date, output[i].category, output[i].mark, output[i].paytype, output[i].money
]
}
console.log(tableMap);
//保存excelResult到相应位置
var excelResult = nodeExcel.execute(tableMap);
var filePath = "outputExcels";
var fileName = Date.now() + '.xlsx';
return await cloud.uploadFile({
cloudPath: path.join(filePath, fileName),
fileContent: new Buffer(excelResult, 'binary')
});
}
这里需要注意的就是表头的添加,格式一定要对,该是数字类型的就填number,该是布尔类型的就填bool等,不然生成的excel文件可能会比较乱,本人就是吃了这里的亏导致文件生成错误
6、右键上传云函数
7、云函数上传成功后,小程序端即可使用
getExcel: function (contentArr) {
wx.cloud.callFunction({
name: 'excelexport',
data: {
excelhead: ["日期", "分类", "说明", "支付方式", "金额"],
excelbody: contentArr
},
success: function (res) {
console.log(res.result.fileID);
},
fail: function (res) {
console.log(res);
}
})
},
此处的contentArr是一个从云数据库里查出来的列表,格式值类似
[{'date':'01','category':1,'mark':'第一个','paytype':1,'money':100
},{'date':'02','category':2,'mark':'第二个','paytype':2,'money':200}
],{'date':'03','category':3,'mark':'第三个','paytype':3,'money':300}
]
8、生成的excel文件会保存在云开发的存储的outputExcels文件夹里,文件内容如下