有几种方法可以导出Word文档,下面列举其中两种常见的方法:
- 使用js库
可以使用js库jszip和docxtemplater来导出Word文档。jszip库可以创建和读取压缩文件,docxtemplater库可以生成Word文档。以下是一个简单的例子:
// 引入库
const JSZip = require('jszip');
const Docxtemplater = require('docxtemplater');
const fs = require('fs');
const path = require('path');
// 读取Word模板
const content = fs.readFileSync(path.join(__dirname, './template.docx'), 'binary');
// 传入模板并渲染
const zip = new JSZip(content);
const doc = new Docxtemplater().loadZip(zip).setData({
name: '张三',
age: 30,
address: '中国北京市',
}).render();
// 导出
fs.writeFileSync(path.join(__dirname, './output.docx'), doc);
- 使用HTML和CSS
可以将HTML和CSS转换成Word文档。以下是一个简单的例子:
// 创建HTML和CSS
const html = `
<html>
<head>
<style>
body {
font-family: 'Times New Roman';
}
h1 {
text-align: center;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
</style>
</head>
<body>
<h1>学生列表</h1>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>地址</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>30</td>
<td>北京市</td>
</tr>
<tr>
<td>李四</td>
<td>28</td>
<td>上海市</td>
</tr>
</tbody>
</table>
</body>
</html>
`;
// 导出
const blob = new Blob([html], {
type: 'application/msword',
});
const link = document.createElement('a');
link.download = 'output.doc';
link.href = URL.createObjectURL(blob);
link.click();