赞
踩
1.创建excelDev.js文件
- export default {
- exportExcel(fileData, documentName = 'excel') {
- plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {
- let rootObj = fs.root
- let fullPath = rootObj.fullPath
- console.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')
- },
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。