vue element ui 导出word文件方法

1首先安装导出word需要的依赖

-- 安装 docxtemplater
npm install docxtemplater pizzip  --save
 
-- 安装 jszip-utils
npm install jszip-utils --save
 
-- 安装 jszip
npm install jszip --save
 
-- 安装 FileSaver
npm install file-saver --save

2.然后在需要导入的页面引入

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

3.需要准备一个word模板文件(按自己所需格式),放到项目public文件夹下,如图所示:

vue element ui 导出word文件方法_第1张图片

 4.前端页面部分如图

vue element ui 导出word文件方法_第2张图片

 代码如下

      
导出申请表
所在部门: 姓名: 性别:
年龄: 出差天数: 职务:
时间:
工作详情:

data数据如下

      organ: '',
      name: '',
      gender: '',
      age: '',
      days: '',
      worker: '',
      date: '',
      work: '',

      wordData: {
        title: '出差申请表',
        organ: '',
        name: '',
        gender: '',
        age: '',
        days: '',
        worker: '',
        date: '',
        work: ''
      },

点击导出方法事件如下

    outword () {
      this.wordData.organ = this.organ
      this.wordData.name = this.name
      this.wordData.gender = this.gender
      this.wordData.age = this.age
      this.wordData.days = this.days
      this.wordData.worker = this.worker
      this.wordData.date = this.date
      this.wordData.why = this.why

      const that = this
      const word = '/出差申请表.docx'
      const wordname = '出差申请表.docx'
      JSZipUtils.getBinaryContent(word, function (error, content) {
        if (error) {
          throw error
        }
        const zip = new PizZip(content)
        const doc = new Docxtemplater().loadZip(zip)
        doc.setData({
          ...that.wordData
        })

        try {
          doc.render()
        } catch (error) {
          const e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties
          }
          console.log(JSON.stringify({ error: e }))
          throw error
        }
        const out = doc.getZip().generate({
          type: 'blob',
          mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        })
        saveAs(out, wordname)
      })
    },

5.注意word文件格式一定要以.docx结尾,文件名一定要对应上,不然会报错,报错的话就看引入的word文件

你可能感兴趣的:(vue.js,前端,javascript)