在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()这个判断一值都是false
		let 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 
}
相关推荐
艾小逗5 分钟前
uniapp快速入门教程,内容来源于官方文档,仅仅记录快速入门需要了解到的知识点
小程序·uni-app·app·es6
鸭子嘎鹅子呱14 小时前
uniapp使用高德地图设置marker标记点,后续根据接口数据改变某个marker标记点,动态更新
uni-app·map·高德地图
计算机源码社19 小时前
分享一个基于微信小程序的居家养老服务小程序 养老服务预约安卓app uniapp(源码、调试、LW、开题、PPT)
android·微信小程序·uni-app·毕业设计项目·毕业设计源码·计算机课程设计·计算机毕业设计开题
Angus-zoe1 天前
uniapp+vue+微信小程序实现侧边导航
vue.js·微信小程序·uni-app
Pluto & Ethereal1 天前
uni-app尺寸单位、flex布局于背景图片
uni-app
天空下sky1 天前
uniapp+若依 开发租房小程序源码分享
uni-app
帅过二硕ฅ1 天前
uniapp点击跳转到对应位置
前端·javascript·uni-app
佩淇呢1 天前
uniapp vue3 梯形选项卡组件
前端·vue.js·uni-app
[廾匸]2 天前
uni-app获取设备唯一值、静态IP以及公网IP的方法
uni-app·ip·imei·唯一值
luckycoke2 天前
小程序的右侧抽屉开关动画手写效果
前端·javascript·微信小程序·uni-app