dom部分
<template>
<div>
<button @click="wordExport">点击导出为word</button>
<div id="wordTest">
<p>这是一个word</p>
<table style="border:1px solid">
<thead>
<th>文本1</th>
<th>文本2</th>
<th>文本3</th>
<th>文本4</th>
</thead>
<tbody>
<tr>
<td>NO.1</td>
<td>NO.2</td>
<td>NO.3</td>
<td>NO.4</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
样式可以通过字符串拼接的方式将
wordExport() {
let header =
"<html xmlns:o='urn:schemas-microsoft-com:office:office' " +
"xmlns:w='urn:schemas-microsoft-com:office:word' " +
"xmlns='http://www.w3.org/TR/REC-html40'>" +
"<head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head><body>" +
"<style type='text/css'>p{text-align: center;};table{width:100%};th {background: red;color: blue;} th,tr,td{border:1px solid;text-align: center;};</style>";
let footer = "</body></html>";
let sourceHTML =
header + document.getElementById("wordTest").innerHTML + footer;
let source =
"data:application/vnd.ms-word;charset=utf-8," +
encodeURIComponent(sourceHTML);
let fileDownload = document.createElement("a");
document.body.appendChild(fileDownload);
fileDownload.href = source;
fileDownload.download = "document.doc";
fileDownload.click();
document.body.removeChild(fileDownload);
}
}
最后效果图显示:
页面中的效果:
导出的word效果: