vue实现导出word文档的示例代码

 更新时间:2024年01月23日 08:18:24   作者:Grant丶  
这篇文章主要为大家详细介绍了如何使用vue实现导出word文档(包括图片),文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

vue 导出word文档(包括图片)

1.打开终端,安装依赖

-- 安装 docxtemplater
npm install docxtemplater pizzip  --save

-- 安装 jszip-utils
npm install jszip-utils --save 

-- 安装 jszip
npm install jszip --save

-- 安装 FileSaver
npm install file-saver --save

-- 安装 angular-expressions
npm install angular-expressions --save

-- 安装 image-size
npm install image-size --save

2.创建exportFile.js文件(导出word方法)

文件存放目录自定义

import PizZip from 'pizzip'
import docxtemplater from 'docxtemplater'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'
 
/**
 * 将base64格式的数据转为ArrayBuffer
 * @param {Object} dataURL base64格式的数据
 */
function base64DataURLToArrayBuffer (dataURL) {
  const base64Regex = /^data:image\/(png|jpg|jpeg|svg|svg\+xml);base64,/;
  if (!base64Regex.test(dataURL)) {
    return false;
  }
  const stringBase64 = dataURL.replace(base64Regex, "");
  let binaryString;
  if (typeof window !== "undefined") {
    binaryString = window.atob(stringBase64);
  } else {
    binaryString = new Buffer(stringBase64, "base64").toString("binary");
  }
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    const ascii = binaryString.charCodeAt(i);
    bytes[i] = ascii;
  }
  return bytes.buffer;
}
 
/**
 * 导出word,支持图片
 * @param {Object} tempDocxPath 模板文件路径
 * @param {Object} wordData 导出数据
 * @param {Object} fileName 导出文件名
 * @param {Object} imgSize 自定义图片尺寸
 */
export const exportWord = (tempDocxPath, wordData, fileName, imgSize) => {
  // 这里要引入处理图片的插件
  var ImageModule = require('docxtemplater-image-module-free');
 
  const expressions = require("angular-expressions");
 
  // 读取并获得模板文件的二进制内容
  JSZipUtils.getBinaryContent(tempDocxPath, function (error, content) {
 
    if (error) {
      throw error;
    }
 
    expressions.filters.size = function (input, width, height) {
      return {
        data: input,
        size: [width, height],
      };
    };
 
    // function angularParser (tag) {
    //   const expr = expressions.compile(tag.replace(/'/g, "'"));
    //   return {
    //     get (scope) {
    //       return expr(scope);
    //     },
    //   };
    // }
 
    // 图片处理
    let opts = {}
 
    opts = {
      // 图像是否居中
      centered: false
    };
 
    opts.getImage = (chartId) => {
      // console.log(chartId);//base64数据
      // 将base64的数据转为ArrayBuffer
      return base64DataURLToArrayBuffer(chartId);
    }
 
    opts.getSize = function (img, tagValue, tagName) {
      // console.log(img);//ArrayBuffer数据
      // console.log(tagValue);//base64数据
      // console.log(tagName);//wordData对象的图像属性名
      // 自定义指定图像大小
      if (imgSize.hasOwnProperty(tagName)){
        return imgSize[tagName];
      } else {
        return [600, 350];
      }
    }
 
    // 创建一个PizZip实例,内容为模板的内容
    let zip = new PizZip(content);
    // 创建并加载docxtemplater实例对象
    let doc = new docxtemplater();
    doc.attachModule(new ImageModule(opts));
    doc.loadZip(zip);
 
    doc.setData(wordData);
 
    try {
      // 用模板变量的值替换所有模板变量
      doc.render();
    } catch (error) {
      // 抛出异常
      let e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties
      };
      console.log(JSON.stringify({
        error: e
      }));
      throw error;
    }
 
    // 生成一个代表docxtemplater对象的zip文件(不是一个真实的文件,而是在内存中的表示)
    let out = doc.getZip().generate({
      type: "blob",
      mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    });
    // 将目标文件对象保存为目标类型的文件,并命名
    saveAs(out, fileName);
  });
}

3.组件调用

注意:引用文件的路径是你创建文件的路径

<template>
  <a-form-model
    ref="ruleForm"
    :model="form"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
  >
    <a-form-model-item label="名称" prop="name">
      <a-input-number v-model="form.name" style="width:100%;"/>
    </a-form-model-item>
    <a-form-model-item label="日期" prop="date">
      <a-input v-model="form.date" />
    </a-form-model-item>
    <a-form-model-item label="文件">
      <a-input v-model="form.imgUrl" read-only/>
      <a-upload name="file" :showUploadList="false" :customRequest="customRequest">
        <a-button type="primary" icon="upload">导入图片</a-button>
      </a-upload>
    </a-form-model-item>
    <a-form-model-item label="操作">
      <a-button type="primary" icon="export" @click="exportWordFile">导出word文档</a-button>
    </a-form-model-item>
  </a-form-model>
</template>
<script>
import {exportWord} from '@/assets/js/exportFile.js'
export default {
  name: 'ExportFile',
  data () {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      form: {},
      rules: {
        name: [
          { required: true, message: '请输入名称!', trigger: 'blur' },
        ],
        date:[
          { required: true, message: '请输入日期!', trigger: 'blur' },
        ],
      },
    };
  },
  created (){},
  methods: {
    customRequest (data){
      //图片必须转成base64格式
      var reader = new FileReader();
      reader.readAsDataURL(data.file);
      reader.onload = () => {
        // console.log("file 转 base64结果:" + reader.result);
        this.form.imgUrl = reader.result; //imgUrl必须与模板文件里的参数名一致
      };
      reader.onerror = function (error) {
        console.log("Error: ", error);
      };
    },
    exportWordFile (){
      let imgSize = {
        imgUrl:[65, 65], //控制导出的word图片大小
      };
      exportWord("./static/test.docx", this.form, "demo.docx", imgSize);
      //参数1:模板文档 
      //参数2:字段参数
      //参数3:输出文档
      //参数4:图片大小
    }
  },
};
</script>

4.创建test.docx文档模板

注:使用vue-cli2的时候,放在static目录下;使用vue-cli3的时候,放在public目录下。

模板参数名需与字段一致,普通字段:{字段名},图片字段:{%字段名}

文档内容:

5.导出demo.docx

结果展示:

以上就是vue实现导出word文档的示例代码的详细内容,更多关于vue导出word的资料请关注脚本之家其它相关文章!

相关文章

  • Vue输入框状态切换&自动获取输入框焦点的实现方法

    Vue输入框状态切换&自动获取输入框焦点的实现方法

    这篇文章主要介绍了Vue输入框状态切换&自动获取输入框焦点的实现,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-05-05
  • 解决vue使用vant轮播组件swipe + flex时文字抖动问题

    解决vue使用vant轮播组件swipe + flex时文字抖动问题

    这篇文章主要介绍了解决vue使用vant轮播组件swipe + flex时文字抖动问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2021-01-01
  • 如何处理vue router 路由传参刷新页面参数丢失

    如何处理vue router 路由传参刷新页面参数丢失

    这篇文章主要介绍了如何处理vue router 路由传参刷新页面参数丢失,对vue感兴趣的同学,可以参考下
    2021-05-05
  • Vue组件之高德地图地址选择功能的实例代码

    Vue组件之高德地图地址选择功能的实例代码

    这篇文章主要介绍了Vue组件之 高德地图地址选择功能的实例代码,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-06-06
  • 如何使用Vue3设计实现一个Model组件浅析

    如何使用Vue3设计实现一个Model组件浅析

    v-model在Vue里面是一个语法糖,数据的双向绑定,本质上还是通过 自定义标签的attribute传递和接受,下面这篇文章主要给大家介绍了关于如何使用Vue3设计实现一个Model组件的相关资料,需要的朋友可以参考下
    2022-08-08
  • 在Vue3项目中使用MQTT获取数据的方法示例

    在Vue3项目中使用MQTT获取数据的方法示例

    这篇文章主要介绍了在Vue3项目中使用MQTT.js库实现数据获取的步骤,包括安装库、创建MQTT连接、发送和接收消息、配置安全选项等,并提供了一个完整的示例代码和常见问题解决方法,需要的朋友可以参考下
    2025-11-11
  • 关于element el-input的autofocus失效的问题及解决

    关于element el-input的autofocus失效的问题及解决

    这篇文章主要介绍了关于element el-input的autofocus失效的问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • vue-calendar-component日历组件报错Clock is not defined解决

    vue-calendar-component日历组件报错Clock is not defi

    这篇文章主要为大家介绍了vue-calendar-component日历组件报错Clock is not defined解决,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-11-11
  • Vue实现自定义组件改变组件背景色(示例代码)

    Vue实现自定义组件改变组件背景色(示例代码)

    要实现 Vue 自定义组件改变组件背景色,你可以通过 props 将背景色作为组件的一个属性传递给组件,在组件内部监听这个属性的变化,并将其应用到组件的样式中,下面通过示例代码介绍Vue如何实现自定义组件改变组件背景色,感兴趣的朋友一起看看吧
    2024-03-03
  • 详解vue-cli3多页应用改造

    详解vue-cli3多页应用改造

    这篇文章主要介绍了详解vue-cli3多页应用改造,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-06-06

最新评论