欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 在uni-app中导出excel文件

在uni-app中导出excel文件

2024/10/25 14:32:00 来源:https://blog.csdn.net/xcg340123/article/details/141711780  浏览:    关键词:在uni-app中导出excel文件

目录

1、数据构造

1.1、首行标题定义

1.2、数据行

1.3、导出

2、工具excelExport.js


 

导出原理:以html表格源码形式,在头部定义excel格式,并借助 java.io的读写文件类

1、数据构造

1.1、首行标题定义

initHeader(){this.warr = ['100px','50px','150px','200px',]this.header = [{content: '列名1',color: 'blue',type: 'text',width: this.warr[0],height: '25px',fontSize: '16px'},{content: '列名2',color: 'blue',type: 'text',width: this.warr[1],height: '25px',fontSize: '16px'}, {content: '列名4',color: 'blue',type: 'text',width: this.warr[2],height: '25px',fontSize: '16px'}, ]
}

1.2、数据行

要求传入二维数组

var listData = []
listData.push(this.header)
let data = []// 遍历有序列表
let li = null;
for(var i=0; i < list.length; i++){let res = dict[list[i]];data = [];tempArr = []//color: 'blue',type: 'text',width: '200px',height: '25px',fontSize: '16px'})data.push({content: res.clanNo , type: 'text',width: this.warr[0]})data.push({content: res.storeroom , type: 'text',width: this.warr[1]})data.push({content: this.buildBoxNo(res), type: 'text',width: this.warr[2]})listData.push(data)
}

1.3、导出

import {doExport} from '@/common/exportExcel.js'doExport(filename, listData, function(res){uni.showToast({duration: 2000,title: "成功导出" + (listData.length -1 ) +"条"})
})

2、工具excelExport.js

文件最终存储在手机磁盘根路径下,名为rootpath的文件夹内

startXlsContent 函数提供了文件头部申明内容

formatTable 函数则是将数据列表转为table.tr元素,并使用java.io.FileWriter写入文件内容

let imgCount = 1;//图片计数器/*** 导出Excel* @param {Object} fileName 文件名 会自动拼接时间戳防止重名* @param {Object} data 数据内容 格式说明见下* @param {Object} callback 导出成功的回调方法 返回文件保存路径* * 二维数组 其中外层数组中的每个元素为数组 对应一行    内层数组中的每个元素为object对象 对应每个单元格 属性如下:* type 类型 text为文字 img为图片 默认文字* width 单元格宽度 请带单位 默认300px* height 单元格高度 请带单位 默认25px* color 文字颜色 默认黑色* fontSize 字号 请带单位 默认16px* textAlign 文字对齐方式 默认left* imgWidth 仅type为img时需要 图片宽度 无需带单位 默认25* imgHeight 仅type为img时需要 图片高度 无需带单位 默认25* content 单元格内容 type为img时为图片路径 仅支持base64* colspan 跨列 默认1* rowspan 跨行 默认1* * 示例:* [[{content: '姓名',color: 'blue',type: 'text',width: '200px',height: '25px',fontSize: '16px'}, {content: '性别',color: 'blue',type: 'text',width: '200px',height: '25px',fontSize: '16px'}, {content: '头像',color: 'blue',type: 'text',width: '200px',height: '25px',fontSize: '16px'}],[{content: '张三',color: 'blue',type: 'text',width: '200px',height: '25px',fontSize: '16px',colspan: 2,rowspan:2}, {content: 'base64图片',type: 'img',width: '200px',height: '25px',imgWidth: 25,imgHeight: 25}],[{content: '123',color: 'blue',type: 'text',width: '200px',height: '25px',fontSize: '16px'}]
]*/
let doExport = function (fileName,data,callback){imgCount = 1;let date = new Date();let year = date.getFullYear();let month = date.getMonth() + 1;let day = date.getDate();let hour = date.getHours();let minute = date.getMinutes();let second = date.getSeconds();if(month < 10){month = '0' + month;}if(day < 10){day = '0' + day;}if(hour < 10){hour = '0' + hour;}if(minute < 10){minute = '0' + minute;}if(second < 10){second = '0' + second;}let name = fileName || '导出的Excel';let reg = /\\|\//g;name = name.replace(reg,'|');name = name + '-' + year + month + day + hour + minute + second;console.log(name)uni.showLoading({title: '正在导出',mask: true});formatTable(name,data,callback);
}async function formatTable(documentName,data,callback){//native.js创建文件及删除文件let dir = '/rootpath';let environment = plus.android.importClass("android.os.Environment");var sdRoot = environment.getExternalStorageDirectory(); //文件夹根目录console.log(sdRoot); var File = plus.android.importClass("java.io.File");var BufferedReader = plus.android.importClass("java.io.BufferedReader");var FileReader = plus.android.importClass("java.io.FileReader");var FileWriter = plus.android.importClass("java.io.FileWriter");try {//不加根目录创建文件(即用相对地址)的话directory.exists()这个判断一值都是falselet current = sdRoot + dir;console.log(current)let directory = new File(current);if (!directory.exists()) {console.log('创建目录')directory.mkdirs(); //创建目录}if (!directory.exists()) {console.log('创建目录失败')} else {console.log('创建目录成功')}// 文件路径,注意和文件夹保持一致,从根目录开始let pathUrl = current + '/' + documentName + '.xls' console.log(pathUrl)let file = new File(pathUrl);console.log(file.exists())if (!file.exists()) {file.createNewFile(); //创建文件}let fos = new FileWriter(pathUrl, true);fos.write(startXlsContent());fos.write(`<table>`);let index = 0;for (let item of data) {let tr = '';tr += `<tr>`;for (let i of item) {let width = i.width || '300px';let height = i.height || '25px';let color = i.color || 'balck';let fontSize = i.fontSize || '16px';let textAlign = i.textAlign || 'left';let colspan = i.colspan || 1;let rowspan = i.rowspan || 1;tr += `<td style="width:${width};height:${height};color:${color};font-size:${fontSize};text-align:${textAlign}" colspan="${colspan}" rowspan="${rowspan}">${i.content}</td>`;}tr += `</tr>`;index++;fos.write(tr);if(index % 2000 == 0){fos.flush();}}fos.write(`</table>`);fos.write(endXlsContent());fos.close();// 成功导出数据;setTimeout(() => {uni.hideLoading();console.log(`导出成功,文件位置:${dir}/${documentName}.xls`);callback(`${dir}/${documentName}.xls`);}, 1000);return ;} catch (e) {console.log(e);}uni.showToast({title: '导出失败,请确认是否授权文件权限10',icon: 'none'});return ;}function startXlsContent(){let excelFile = "<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'>";excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';excelFile += '; charset=UTF-8">';excelFile += "<head>";excelFile += "<!--[if gte mso 9]>";excelFile += "<xml>";excelFile += "<x:ExcelWorkbook>";excelFile += "<x:ExcelWorksheets>";excelFile += "<x:ExcelWorksheet>";excelFile += "<x:Name>";excelFile += "sheet";excelFile += "</x:Name>";excelFile += "<x:WorksheetOptions>";excelFile += "<x:DisplayGridlines/>";excelFile += "</x:WorksheetOptions>";excelFile += "</x:ExcelWorksheet>";excelFile += "</x:ExcelWorksheets>";excelFile += "</x:ExcelWorkbook>";excelFile += "</xml>";excelFile += "<![endif]-->";excelFile += "</head>";excelFile += "<body>" // excelFile += data + "</body></html>";return excelFile;
}function endXlsContent(){return "</body></html>";
}export {doExport 
}

 

 

版权声明:

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

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