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')},