先上个图,这个是在电脑上测试导出来的表
大致远离就是用的原生td,tr去导出的,
代码
<template>
<view>
<button @click="tableToExcel">导出一个表来看</button>
</view>
</template>
<script>
export default {
data() {
return {
successTip: "",
};
},
methods: {
tableToExcel() {
// 要导出的json数据
const jsonData = [
{
name: "科比",
phone: "123456",
email: "科比@163.com",
},
{
name: "科比",
phone: "123456",
email: "科比@163.com",
},
{
name: "科比",
phone: "123456",
email: "科比@163.com",
},
{
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>`;
let documentName = new Date().getTime()
this.wxExportFile(template, documentName);
},
wxExportFile(template, documentName) {
const fs = wx.getFileSystemManager();
// 创建文件名字, 防止重名
let filePath =
wx.env.USER_DATA_PATH + "/" + documentName + ".xls";
console.log(filePath);
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>