Export word files in Vue front-end

Many times at work, we will encounter the need to export word files completely from the front end, so I specially record some of the more commonly used methods.

1. Provide a word template

This method provides a word template file, and the data is passed into the word file through parameter replacement. It has poor flexibility and is suitable for simple file export. Required dependencies: docxtemplater, file-saver, jszip-utils, pizzip .

Insert image description here

javascript
复制代码
import Docxtemplater from "docxtemplater";
import { saveAs } from "file-saver";
import JSZipUtils from "jszip-utils";
import PizZip from "pizzip";

export function downloadWithTemplate(path, data, fileName) {
  JSZipUtils.getBinaryContent(path, (error, content) => {
    if (error) throw error;

    const zip = new PizZip(content);
    const doc = new Docxtemplater().loadZip(zip);
    doc.setData({
      ...data.form,
      // 循环项参数
      list: data.list,
      outsideList: data.outsideList,
    });

    try {
      doc.render();
    } catch (error) {
      const e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties,
      };
      ElMessage.error("文件格式有误!");
      throw error;
    }
    const out = doc.getZip().generate({
      type: "blob",
      mimeType:
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    });
    saveAs(out, fileName);
  });
}

let data = {
    form: {
      title: "这是word标题",
      test: "这是表单1的数据",
      test1: "111",
      test2: 222,
      test3: 333,
    },
    outsideList: [
      {
        list: [
          {
            index: 0,
            table: "表格第一项",
            table1: "表格第二项",
            table2: "表格第三项",
          },
          {
            index: 1,
            table: "表格第一项",
            table1: "表格第二项",
            table2: "表格第三项",
          },
        ],
      },
      {
        list: [
          {
            index: 0,
            table: "表格第一项",
            table1: "表格第二项",
            table2: "表格第三项",
          },
          {
            index: 1,
            table: "表格第一项",
            table1: "表格第二项",
            table2: "表格第三项",
          },
        ],
      },
    ],
  };
  
  downloadWithTemplate("template.docx", data, "模板word.docx")
  

Call the downloadWithTemplate method to export the following files: Insert image description here
Note: The path parameter in the above method is the location where you store the public files in the vue project. In vue2, it is under the static folder, and in vue3, it is under the public folder.

2. Convert to word file based on html code (recommended)

As the name suggests, this method is to directly convert the HTML code we write on the page into a word file. This is also the method I recommend most, because most of the styles are controllable, and after all, it is a method we are more familiar with. Requires plug-ins: html-docx-js-typescript, file-saver.

xml
复制代码
import { saveAs } from "file-saver";
import { asBlob } from "html-docx-js-typescript";

 export function downloadWordWithHtmlString(html, name) {
  let htmlString = `
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>
  <body>
    ${html}
  </body>
  </html>
  `;
  asBlob(htmlString).then((data) => {
    saveAs(data, `${name}.docx`);
  });
}
  `

Use Cases:

ini
复制代码
<div ref="word">
  <h3 style="text-align: center">word标题</h3>
  <table
    border="1"
    cellspacing="0"
    width="600"
    style="font-size: 12px; color: #000; text-align: center"
  >
    <tr height="50">
      <td width="100">1111</td>
      <td widt="200" colspan="2">合并单元格</td>
      <td width="300">最长的一项</td>
    </tr>
    <tr height="100">
      <td width="100">222</td>
      <td width="100">222</td>
      <td width="100">222</td>
      <td width="100">222</td>
    </tr>
  </table>
  <table width="600" border="1" cellspacing="0">
    <tr height="50">
      <td width="100">1111</td>
      <td rowspan="3">合并包括此行在内的下面三行</td>
    </tr>
    <tr height="100">
      <td>222</td>
    </tr>
    <tr height="300">
      <td>3333</td>
    </tr>
    <tr>
      <td>50</td>
    </tr>
  </table>
</div>

let word = ref(null);
downloadWordWithHtmlString(word.value.innerHTML, 'html字符串word.docx');

The generated word file can be seen to have the same effect as the html code in the web page:

Insert image description here
Another thing to note is that if you need to add page breaks in word, just add the CSS attribute page-break-before to the content that needs to be paged . At this time, if you print out the innerHTML value on the browser, you will find:

Insert image description here

The page-break-before attribute introduced on mdn has been replaced by the break-before attribute. However, after my actual testing, I found that when the HTML string is page-break: always, the generated word file has no paging effect. Instead, it is replaced with page- The paging effect is achieved after break-before. If anyone knows what this problem is, I hope you can enlighten me. Therefore, you need to add a regular sentence to the downloadWordWithHtmlString method: htmlString = htmlString.replace( /break-(after|before): page/g, "page-break-$1: always;" );, and the paging effect can be achieved.

3. Use docx plug-in

A very fatal problem with the second method is that it cannot add image headers to the generated word files. I searched npm and only found a plug-in that can add text headers: html-docx-ts To achieve this If required, you need to use the docx plug-in. The introduction of the docx official website is "Easily generate and modify .docx files with JS/TS. Works for Node and on the Browser.", which means it is a file specially used to generate and modify word. This plug-in needs to configure the items you want to generate one by one, and then combine them into a word. A simple case is:

css
复制代码
import {
  Document,
  Paragraph,
  Header,
  TextRun,
  Table,
  TableRow,
  TableCell,
  WidthType,
  Packer,
} from "docx";
import { saveAs } from "file-saver";

const document = new Document({
    sections: [
      {
        headers: {
          default: new Header({
            children: [new Paragraph("我是页眉")],
          }),
        },
        children: [
          new Paragraph({
            children: [
              new TextRun({
                text: "我是文字内容",
                size: 16,
                bold: true,
              }),
            ],
          }),
          new Table({
            columnWidths: [1500, 7500],
            rows: [
              new TableRow({
                children: [
                  new TableCell({
                    width: {
                      size: 1500,
                      type: WidthType.DXA,
                    },
                    children: [
                      new Paragraph({
                        alignment: "center",
                        children: [
                          new TextRun({
                            text: "测试",
                            size: 24,
                            font: {
                              name: "楷体",
                            },
                          }),
                        ],
                      }),
                    ],
                  }),
                ],
              }),
            ],
          }),
        ],
      },
    ],
  });
  
  Packer.toBlob(document).then((blob) => {
    saveAs(blob, "test.docx");
  });

The exported word file format is:

Insert image description here
The following is my personal summary of the more common functions and configuration items that can be used:

css
复制代码
// 导出文字
1.new Paragraph(text) -> 默认字体样式: 宋体,五号字
2.new Paragraph({
    children: [
      new TextRun({
        text: "我是文字内容",
        size: 16, // 对应word中的字体大小8
        bold: true, // 是否加粗
        underline: {
          type: UnderlineType.SINGLE,
          color: "#2e32ee",
        }, // 下划线类型及颜色
        font: {
          name: "仿宋", // 只要是word中有的字体类型都可以生效
        },
      }),
    ],
    indent: {
      left: 100,
    }, // 离左边距离 类似于margin-left
    spacing: {
      before: 150,
      after: 200,
    }, // 离上边和下边的距离 类似于margin-top/bottom
    alignment: "center", // 对齐方式
    pageBreakBefore: true, // 是否在这段文字前加入分页符
  })
  
 // 导出表格
new Table({
  columnWidths: [1500, 7500], // 表示单行有几项,总宽度是9000,对应宽度;
  rows: [
    new TableRow({
      children: [
        new TableCell({
          width: {
            size: 1500, // 需与columnWidths的第一项对应
            type: WidthType.DXA, // 官网的介绍是Value is in twentieths of a point
            // 因为表格的总宽度是以twips(每英寸的1/20)为单位进行计算的
          },
          children: [
            new Paragraph({
              alignment: "center",
              children: [
                new TextRun({
                  text: "测试",
                  size: 24,
                  font: {
                    name: "楷体",
                  },
                }),
              ],
            }),
          ],
        }),
        new TableCell({
          width: {
            size: 7500,
            type: WidthType.DXA,
          },
          children: [
            new Paragraph('ccc'),
          ],
          margins: {
            top: 500,
            bottom: 500,
            left: 500
          } // 类似于单元格内容的padding
        }),
      ],
    }),
  ],
})

// 导出图片
new Paragraph({
  children: [
    new ImageRun({
      data: "base64", // 图片需转成base64的形式
      transformation: {
        width: 100,
        height: 30,
      }, // 图片宽高
    }),
  ],
})

// 设置页眉页脚
headers: {
  default: new Header({
    children: [new Paragraph("我是页眉")],
  }),
},
footers: {
  default: new Footer({
    children: [new Paragraph("我是页脚")],
  }),
}

Here is a complete use case:

css
复制代码
const document = new Document({
  sections: [
    {
      headers: {
        default: new Header({
          children: [
            new Paragraph({
              children: [
                new ImageRun({
                  data: "data:image/jpeg;base64,...",
                  transformation: {
                    width: 150,
                    height: 150,
                  },
                }),
              ],
            }),
          ],
        }),
      },
      footers: {
        default: new Footer({
          children: [new Paragraph("我是页脚")],
        }),
      },
      children: [
         new Paragraph("第一行直接默认形式"),
         new Paragraph({
           children: [
             new TextRun({
               text: "下一页",
             }),
           ],
           pageBreakBefore: true,
         }),
         new Table({
           columnWidths: [1500, 7500],
           rows: [
             new TableRow({
               children: [
                 new TableCell({
                   width: {
                     size: 1500,
                     type: WidthType.DXA,
                   },
                   children: [
                     new Paragraph({
                       alignment: "center",
                       children: [
                         new TextRun({
                           text: "测试",
                           size: 24,
                           font: {
                             name: "楷体",
                           },
                         }),
                       ],
                     }),
                   ],
                 }),
                 new TableCell({
                   width: {
                     size: 7500,
                     type: WidthType.DXA,
                   },
                   children: [
                     new Paragraph({
                       children: [
                         new ImageRun({
                           data: "data:image/jpeg;base64,...",
                           transformation: {
                             width: 150,
                             height: 150,
                           },
                         }),
                       ],
                     }),
                   ],
                   margins: {
                     top: 500,
                     bottom: 500,
                    left: 500,
                  },
                }),
              ],
            }),
          ],
        }),
      ],
    },
  ],
});

Packer.toBlob(document).then((blob) => {
  saveAs(blob, "test.docx");
});

The exported word file at this time is as follows:

Insert image description here
To learn more about vue development, please download the CRMEB open source mall attachment.

Guess you like

Origin blog.csdn.net/CRMEB/article/details/133278226