How to export word document using js

There are several ways to export a Word document, two of the common methods are listed below:

  1. Use js library

You can use the js library jszip and docxtemplater to export Word documents. The jszip library can create and read compressed files, and the docxtemplater library can generate Word documents. Here is a simple example:

// 引入库
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);
  1. Using HTML and CSS

Can convert HTML and CSS into Word documents. Here is a simple example:

// 创建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();

Guess you like

Origin blog.csdn.net/weixin_42317757/article/details/132656438