vue export word

In a recent project, some content in Vue needs to be exported into word form. I have never done this before. Special note. Since I am a beginner, I have compiled this template. Note: This is a template, not related fields. Parsing, I still don’t know exactly what each field is used for, and I will slowly add my own understanding in the future.

I saw a very good article, very detailed: vue export word - Zhihu

1. First install the required dependency packages in the project. I installed six

npm install file-saver
npm install docxtemplater
npm install pizzip
npm install jszip-utils
npm install angular-expressions
npm install lodash

 2. Introduce the core code file exportBriefDataDocx.js

To reference in the component, I write the file in utils in the root directory:

import { ExportBriefDataDocx } from '../utils/exportBriefDataDocx'

Contents in the file exportBriefDataDocx.js:

import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'

export const ExportBriefDataDocx = (tempDocxPath, data, fileName) => {
  console.log(tempDocxPath, data, fileName, 111)
  var expressions = require('angular-expressions')
  var assign = require('lodash/assign')
  expressions.filters.lower = function(input) {
    // This condition should be used to make sure that if your input is
    // undefined, your output will be undefined as well and will not
    // throw an error
    if (!input) return input
    // toLowerCase() 方法用于把字符串转换为小写。
    return input.toLowerCase()
  }
  function angularParser(tag) {
    tag = tag
      .replace(/^\.$/, 'this')
      .replace(/(’|‘)/g, "'")
      .replace(/(“|”)/g, '"')
    const expr = expressions.compile(tag)
    return {
      get: function(scope, context) {
        let obj = {}
        const scopeList = context.scopeList
        const num = context.num
        for (let i = 0, len = num + 1; i < len; i++) {
          obj = assign(obj, scopeList[i])
        }
        return expr(scope, obj)
      }
    }
  }
  JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
    if (error) {
      console.log(error)
    }

    // 创建一个JSZip实例,内容为模板的内容
    // let zip = new JSZip(content); //用PizZip替代
    const zip = new PizZip(content)
    // 创建并加载 Docxtemplater 实例对象
    const doc = new Docxtemplater(zip, { parser: angularParser })
    // 设置模板变量的值
    doc.setData(data)
    try {
      // 呈现文档,会将内部所有变量替换成值,
      doc.render()
    } catch (error) {
      const e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties

      }
      console.log({ error: e })
      // 当使用json记录时,此处抛出错误信息
      throw error
    }
    // 生成一个代表Docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
    const out = doc.getZip().generate({
      type: 'blob',
      mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    })
    // 将目标文件对象保存为目标类型的文件,并命名
    saveAs(out, fileName)
  })
}

3. Then design the word template that needs to be exported, and create a new document locally with the suffix name .docx. I saved this file in the public directory in the root directory.

The data I want to pass into the template is this.docxData, so all the data will be saved in this.docxData. For example: it has three fields: array tableData, number year, and number month, as follows:

tableData :

tableData: [{
            date: '2016-05-02',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1518 弄'
          }, {
            date: '2016-05-04',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1517 弄'
          }, {
            date: '2016-05-01',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1519 弄'
          }, {
            date: '2016-05-03',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1516 弄'
          }]

 docxData:

this.docxData.tableData = this.tableData
this.docxData.year = 2022
this.docxData.month = 9

 Here's what's in the template docs:

Documentation notes:

1) The template file must be a docx file. The doc file cannot be changed to docx by modifying the suffix. You must select the docx type when saving it to achieve the type change.
2) Use curly braces in English;
3) There should be no spaces before and after the key name in the curly braces, and it must be consistent with the key name of the data object in the program;
4) The data that you want to add in a loop in the table needs to be in Add {#keyname} at the beginning and {/keyname} at the end, which generally correspond to the name of the array that needs to be looped.
5) Do not use {%%image2} to center the picture

6) When making a judgment, start with {#keyname} and end with {/}


4. Trigger export event

methods: {
    // 导出docx
    exportDocx() {
      console.log('导出');
      this.docxData.tableData = this.tableData
      this.docxData.year = 2022
      this.docxData.month = 9
      // ExportBriefDataDocx 是我导入的一个文件,里边写的是导出文本的核心代码
      ExportBriefDataDocx('模板文件', 要传入模板的数据, '文档名字.docx')
      // ExportBriefDataDocx('/text.docx', this.docxData, '文档导出.docx') // text.docx放在了根目录下的public文件夹下
    }
  }

Rendering:

Attach the code for the complete component part:

ExportDocx.vue:

<template>
  <div class="docx">
    <el-button @click="exportDocx">导出</el-button>
    <h2>{
   
   {2022}}年{
   
   {9}}月</h2>
    <el-table
        :data="tableData"
        border
        style="width: 100%">
      <el-table-column
          prop="date"
          label="日期"
          width="180">
      </el-table-column>
      <el-table-column
          prop="name"
          label="姓名"
          width="180">
      </el-table-column>
      <el-table-column
          prop="address"
          label="地址">
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { ExportBriefDataDocx } from '../utils/exportBriefDataDocx'
export default {
  name: "Docx",
  data() {
    return {
      tableData: [{
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1517 弄'
      }, {
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄'
      }, {
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1516 弄'
      }],
      docxData:{}
    }
  },
  methods: {
    // 导出docx
    exportDocx() {
      console.log('导出');
      this.docxData.tableData = this.tableData
      this.docxData.year = 2022
      this.docxData.month = 9
      ExportBriefDataDocx('/text.docx', this.docxData, '文档导出.docx')
    }
  },
}
</script>

<style scoped>

</style>

Guess you like

Origin blog.csdn.net/qq_46372045/article/details/126780973