uniapp json數據導出excel文件 微信小程序/app段兼容

  這裏用到小程序和app段的api

微信小程序

wx.getFileSystemManager()
獲取全局唯一的文件管理器

返回值
FileSystemManager

在調用 writeFile 方法 功能描述 寫文件 參數 Object object |屬性|類型|默認值| 必填| 說明| | -- | ---- | :---- | ---- | ---- | |filePath|string||是|要寫入的文件路徑 (本地路徑)| |data|string/Array|Buffer|是|要寫入的文本或二進制數據| |encoding|string|utf8|否 |指定寫入文件的字符編碼

wx.openDocument 預覽文件

wx.openDocument({
	filePath,
	showMenu:true, //是否右上角菜單,這樣就可以轉發給好友了
	success: res => console.log('打開文檔成功。文件位置', filePath),
	fail: err => console.log(err)
})

<template>
	<view>
		<button @click="tableToExcel">導出一個表來看</button>
		<view>{{ successTip }}</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				successTip: ''
			}
		},
		methods: {
			uuid() {
				return 'xxx-xxx-xxx'.replace(/[xy]/g, c => {
					var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)
					return v.toString(16)
				})
			},

			tableToExcel() {
				// 要導出的json數據
				const jsonData = [
					{ name: '科比', phone: '123456', email: '科比@163.com' },
				]
				// 列標題
				let worksheet = 'sht1'
				let str = '<tr><td style="text-align: center">姓名</td><td style="text-align: center">電話</td><td style="text-align: center">郵箱</td></tr>'
				// 循環遍歷,每行加入tr標籤,每個單元格加td標籤
				for (let i = 0; i < jsonData.length; i++) {
					str += '<tr>'
					for (let item in jsonData[i]) {
						// 增加\t爲了不讓表格顯示科學計數法或者其他格式
						str += `<td>${jsonData[i][item] + '\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>`
				// 下載模板
				// #ifdef APP-PLUS
				this.appExportFile(template)
				// #endif
				// 下載模板
				// #ifdef MP-WEIXIN
				this.wxExportFile(template)
				// #endif
			},

			// 導出文件到手機 fileData:要寫入到文件的數據,返回參數爲文檔路徑
			appExportFile(fileData, documentName = '項目Excel文件') {
				// PUBLIC_DOCUMENTS: 程序公用文檔目錄常量
				plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => {
					let rootObj = fs.root, fullPath = rootObj.fullPath
					console.log('開始導出數據********')
					// 創建文件夾
					rootObj.getDirectory(documentName, {
						create: true
					}, dirEntry => {
						// 創建文件,防止重名
						let fileName = 'excel' + this.uuid() + '.xlsx'
						dirEntry.getFile(fileName, {
							create: true
						}, fileEntry => {
							fileEntry.createWriter(writer => {
								writer.onwritestart = res => console.log('正在導出')
								//  /storage/emulated/0指的就是系統路徑
								let pathStr = fullPath.replace('/storage/emulated/0', '')
								// 成功導出數據
								writer.onwrite = res => {
									// 文件路徑
									let filePath = res.target.fileName
									uni.hideLoading()
									setTimeout(() => {
										console.log('成功導出')
										this.successTip = `文件位置:${filePath}`
										
										uni.openDocument({
											filePath,
											success: res => console.log('打開文檔成功'),
											fail: err => console.log(err)
										})
									}, 500)
								}
								// 寫入內容
								writer.write(fileData)
							}, err => console.log(err.message))
						})
					})
				})
			},

			wxExportFile(template, documentName = '項目Excel文件') {
				const fs = wx.getFileSystemManager()
				// 創建文件名字, 防止重名
				let filePath = wx.env.USER_DATA_PATH + '/' + (documentName + this.uuid()) + '.xls'
				fs.writeFile({
					filePath,
					data: template,
					encoding: 'utf8',
					success: res => {
						
						wx.openDocument({
							filePath,
						showMenu:true,
							success: res => console.log('打開文檔成功。文件位置', filePath),
							fail: err => console.log(err)
						})
					},
					fail: err => console.info(err)
				})
			}
		}
	}
</script>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章