小程序josn数据生成excel文件
先从下载传送门将xlsx.mini.min.js拷贝下来,新建xlsx.js文件放入小程序项目文件夹下。
const XLSX = require('./xlsx')//在需要用的页面中引入
// 定义导出 Excel 报表的方法exportData() {const that = thislet newData = [{time:2021,value:111},{time:2022,value:222},{time:2023,value:333}]// 构建一个表的数据let lock = []let title = ['时间', '数值']lock.push(title)that.data.newData.forEach(item => {let rowcontent = []rowcontent.push(item.time)rowcontent.push(item.value)lock.push(rowcontent)})//自定义列宽const colWidth = [{wch: 10},{wch: 10},]// XLSX插件使用var ws = XLSX.utils.aoa_to_sheet(lock);// ws['!cols'] = colWidthvar wb = XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb, ws, "xxx数据");var fileData = XLSX.write(wb, {bookType: "xlsx",type: 'base64'});let filePath = `${wx.env.USER_DATA_PATH}/xxxx记录.xlsx`// 写文件const fs = wx.getFileSystemManager()fs.writeFile({filePath: filePath,data: fileData,encoding: 'base64',success(res) {console.log(res)const sysInfo = wx.getSystemInfoSync()// 导出if (sysInfo.platform.toLowerCase().indexOf('windows') >= 0) {// 电脑PC端导出wx.saveFileToDisk({filePath: filePath,success(res) {console.log(res)},fail(res) {console.error(res)util.tips("导出失败")}})} else {// 手机端导出// 打开文档wx.openDocument({filePath: filePath,//默认为false,true可在右上角进行分享转发showMenu: true,success: function (res) {console.log('打开文档成功')},fail: console.error})}},fail(res) {console.error(res)if (res.errMsg.indexOf('locked')) {wx.showModal({title: '提示',content: '文档已打开,请先关闭',})}}})},`