uniapp app导出表格excel

1,646 阅读1分钟

app环境中,xlsxjs基本没用,csv我记得以前用过一次,好像是可以。

在写入文件时候,文件对象写入方法writer.write(template)中只能传入string。
我并不知道xlsx的编码格式是什么。用html的table代替,wps认识这样的格式。

uniapp app 复制过去就可以用

html-----
<button type="default" @click="EXCEL">导出</button>    
js------           
EXCEL() {
        //要导出的数据
	const res = [{
		name: "jack",
		age: 123,
		gender: "man"
	    },
	    {
		name: "marry",
		age: 666,
		gender: "man"
	    },
	    {
		name: "sun",
		age: 88888888,
		gender: "man"
	    }]
	let str = res.map(m => {

	let str2 = Object.values(m).map(mp => {
		return `<td>${mp}</td>`
	}).join('')
	return `<tr>${str2}</tr>`}).join('')

	let str1 = Object.keys(res[0]).map(mp => {
	return `<td>${mp}</td>`
	}).join('')
	str = `<tr>${str1}</tr>${str}`
	console.log(str);

	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>sheet1</x:Name>
	<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
	</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
	</head><body><table>${str}</table></body></html>`;

	plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
		// 可通过fs进行文件操作 
		console.log("Request file system success!");
		console.log(fs.name);
		fs.root.getFile(
			`ceshi.xlsx`, {
				create: true,
				exclusive: false
			},
			fileEntry => {
				console.log(1);
				fileEntry.createWriter(
				writer => {
				writer.onwrite = e => {
				// that.count = 100;
				// that.tap = `成功导出[${length}]条数据,文件路径为:${e.target.fileName}`;
				console.log(e.target.fileName);
				setTimeout(function() {
				// that.proshow = false;
				uni.openDocument({
					ilePath: `file://${e.target.fileName}`, //这里必须加file://否则会报错打不开文件
						success: function(res) {
							console.log(2233, res);

						},
						fail(res) {
							console.log(res);
						}
				});
				}, 2000);
				};
				`在这里插入代码片`
				writer.write(template);
				},
				function(e) {
				uni.showToast({
					title: '导出文件失败,请检查你的权限',
					icon: 'none'
				});
				}
				);
				},
				e => {
					console.log(e);
				}

				);

				}, function(e) {
					alert("Request file system failed: " + e.message);
				});
			}