uniapp (UI框架:uview2.x) JSON数据导出生成excel

一、生成下载的表格模板数据

代码如下:

// 建立一个工具类函数文件 utils.js
export function tableToExcel(jsonData, str) {
    //要导出的json数据
    let worksheet = 'sheet1'
    // let str = '姓名电话邮箱'
    //循环遍历,每行加入tr标签,每个单元格加td标签
    console.log('jsonData: ', jsonData);
    for (let i = 0; i < jsonData.length; i++) {
        str += ''
        for (let key in jsonData[i]) {
            console.log('key: ', key);
            console.log('jsonData[i][key]: ', jsonData[i][key]);
            //增加\t为了不让表格显示科学计数法或者其他格式
            str += `${jsonData[i][key] + '\t'}`
        }
        str += ''
        console.log('str: ', str);
    }
    //下载的表格模板数据
    let template = `
      
      ${str}
` //下载模板 return template }

二、如何导出Excel

代码如下:

// 同上放在 utils.js
export function exportExcel(fileData, documentName = 'excel') {
    /*
    PRIVATE_DOC: 应用私有文档目录常量
    PUBLIC_DOCUMENTS: 程序公用文档目录常量
    */
    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) => {
                        showLoading('正在导出')
                    }
                    writer.onwrite = (e) => {
                        // 成功导出数据
                        hideLoading()
                        setTimeout(() => {
                            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)
                })
            })
        })
    })
}

function showToast(title = '') {
    uni.hideLoading()
    uni.showToast({
        title,
        icon: 'none',
        duration: 1500
    })
}
/**
 * loading
 * @param title
 */
function showLoading(title = '加载中') {
    uni.hideLoading()
    uni.showLoading({
        title,
        mask: true
    })
}
/**
 * hideLoading
 */
function hideLoading() {
    uni.hideLoading()
}

三、如何使用

// 先引入
import { tableToExcel, exportExcel } from '@/util/utils'

// 导出函数 
exportInfo() {
			let carInfoStr = ''
			if (this.carList.length) {
				this.carList.forEach((ele) => {
					carInfoStr += `车辆类型:${ele.selectField101},车牌号:${ele.comInputField102};`
				})
			}

			let jsonData = [
				{
					comInputField103:
						this.householderInfo.comInputField103 || '',
					selectField102_name:
						this.householderInfo.selectField102_name || '',
					comInputField104:
						this.householderInfo.comInputField104 || '',
					radioField113_name:
						this.householderInfo.radioField113_name || '',
					selectField114: this.householderInfo.selectField114 || '',
					carInfo: carInfoStr,
					comInputField109:
						this.householderInfo.comInputField109 || '',
					comInputField105:
						this.householderInfo.comInputField105 || '',
					selectField107_name:
						this.householderInfo.selectField107_name || '',
					comInputField108:
						this.householderInfo.comInputField108 || '',
				},
			]

           // 定义表头
			let str =
				'户主姓名性别身份证号是否党员群体车辆信息手机号职业学历住址'
			// 生成template 模板
			let template = tableToExcel(jsonData, str)
			// 导出Excel
			exportExcel(template, '户主信息')
		},

你可能感兴趣的:(uniapp,uni-app,json,excel)