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 SPA 首屏加载优化实践

    浅谈Vue SPA 首屏加载优化实践

    本篇文章主要介绍了浅谈Vue SPA 首屏加载优化实践,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • vue中的inject学习教程

    vue中的inject学习教程

    本文通过实例代码给大家介绍了vue中的inject学习教程,非常不错,具有一定的参考借鉴价值,需要的朋友参考下吧
    2019-04-04
  • Vue CompositionAPI中watch和watchEffect的区别详解

    Vue CompositionAPI中watch和watchEffect的区别详解

    这篇文章主要为大家详细介绍了Vue CompositionAPI中watch和watchEffect的区别,文中的示例代码简洁易懂,希望对大家学习Vue有一定的帮助
    2023-06-06
  • ElementUI时间选择器限制选择范围disabledData的使用

    ElementUI时间选择器限制选择范围disabledData的使用

    本文主要介绍了ElementUI时间选择器限制选择范围disabledData的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-06-06
  • 详解Vue.js分发之作用域槽

    详解Vue.js分发之作用域槽

    本篇文章主要介绍了详解Vue.js分发之作用域槽,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • vue中使用闭包(防抖和节流)失效问题

    vue中使用闭包(防抖和节流)失效问题

    本文主要介绍了vue中使用闭包(防抖和节流)失效问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • Vue中key的作用及原理详解

    Vue中key的作用及原理详解

    本文主要介绍了Vue3中key的作用和工作原理,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-10-10
  • vue3使用video.js播放m3u8格式视频的操作指南

    vue3使用video.js播放m3u8格式视频的操作指南

    有时候我们需要播放 m3u8 格式的视频,或者实现视频播放器更多定制化需求,HTML 的 video 元素无法实现这些需求,这时候可以考虑使用 Video.js,本文给大家介绍了vue3使用video.js播放m3u8格式视频的操作指南,需要的朋友可以参考下
    2024-07-07
  • vue实现登陆登出的实现示例

    vue实现登陆登出的实现示例

    本篇文章主要介绍了vue实现登陆登出的实现示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • axios请求的一些常见操作实战指南

    axios请求的一些常见操作实战指南

    axios是一个轻量的HTTP客户端,它基于XMLHttpRequest服务来执行 HTTP请求,支持丰富的配置,支持Promise,支持浏览器端和 Node.js 端,下面这篇文章主要给大家介绍了关于axios请求的一些常见操作,需要的朋友可以参考下
    2022-09-09

最新评论