Word 文書をエクスポートするにはいくつかの方法があります。一般的な方法のうちの 2 つを以下に示します。
- 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();