您的位置:首页 > 游戏 > 手游 > uniapp 在手机上导出excel

uniapp 在手机上导出excel

2024/10/5 22:29:39 来源:https://blog.csdn.net/cjy_fly/article/details/140230284  浏览:    关键词:uniapp 在手机上导出excel

1.创建excelDev.js文件

export default {exportExcel(fileData, documentName = 'excel') {plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {let rootObj = fs.rootlet fullPath = rootObj.fullPathconsole.log("开始导出数据")// 创建文件夹rootObj.getDirectory(documentName, {create: true}, function(dirEntry) {// 创建文件,防止重名let fileName = new Date().getTime()console.log(fileName)dirEntry.getFile(`${fileName}.xlsx`, {create: true}, function(fileEntry) {fileEntry.createWriter(function(writer) {writer.onwritestart = (e) => {uni.showLoading('正在导出')}writer.onwrite = (e) => {// 成功导出数据uni.hideLoading()setTimeout(() => {uni.showToast('导出成功')const path =`file://${fullPath}${documentName}/${fileName}.xlsx`console.log('文件位置:', path)// 打开文件uni.openDocument({filePath: path,success: res => {console.log('打开文档成功',res)},fail: e => {console.log('打开失败', e)}})}, 500)}// 写入内容writer.write(fileData)}, function(e) {console.log(e.message)})})})})}
}

2.可在main.js文件中引入(单独去页面引入也可以)

import excelDev from './excelDev.js'

// 挂载到vue原型上

Vue.prototype.$excelDev = excelDev

3.在相应页面调用

// 导出excel
tableToExcel() {//要导出的json数据// this.jsonData = [{"id":"2","content":"你好!","fromId":"123","toId":"321","flag":"1"}]let worksheet = 'sheet1'let str = '<tr><td>id</td><td>content</td><td>fromId</td><td>toId</td><td>flag</td></tr>'//循环遍历,每行加入tr标签,每个单元格加td标签for (let i = 0; i < this.jsonData.length; i++) {str += '<tr>'for (let key in this.jsonData[i]) {//增加\t为了不让表格显示科学计数法或者其他格式str += `<td>${ this.jsonData[i][key] + '\t'}</td>`}str += '</tr>'}//下载的表格模板数据let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"xmlns:x="urn:schemas-microsoft-com:office:excel"xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>${worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>${str}</table></body></html>`//下载模板this.$excelDev.exportExcel(template, 'excel')},

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com