vue实现导出word文档功能

vue yekong 700℃

vue实现导出word文档功能,导出数据表格,结合html2canvas实现导出图片

vue实现导出word文档功能

演示地址

vue实现导出word文档功能

代码

/**
* @Author: 858834013@qq.com
* @Name: exportDocument
* @Date: 2024年03月13日
* @Desc: 导出文档
*/
<template>
  <div class="exportDocument" ref="exportDocument">
    <div @click="saveWord" class="exportDocumentBut">导出word</div>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import {s2ab} from "./utils/utils";
import fileSaver from 'file-saver'
import {MyDoc} from './utils/mydoc'

export default {
  name: "exportDocument",
  data: function () {
    return {
      list: [
        ['标题1', '标题2', '标题3', '标题4'],
        ['内容1', '内容2', '内容3', '内容4'],
      ]
    }
  },
  mounted() {

  },
  methods: {
    saveWord() {
      var that = this;
      let doc = new MyDoc()
      document.body.scrollTop = document.documentElement.scrollTop = 0
      html2canvas(this.$refs.exportDocument, {scrollY: 0}).then(canvas => {
        let dataURL = canvas.toDataURL("image/png");
        doc.addHeader('标题1', '1', {'textAlign': 'center'})
        doc.addHeader('标题2', '2', '')
        doc.addHeader('标题3', '3', '')
        doc.addHeader('标题4', '4', '')
        doc.addHeader('标题5', '5', '')
        doc.addHeader('标题6', '6', '')
        doc.addImage(dataURL, 580, 350)
        doc.addTable(that.list, '')
        let data = doc.generate()
        let blob = new Blob([s2ab(atob(data))], {
          type: 'data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,'
        })
        try {
          fileSaver.saveAs(blob, '测试文档.docx')
        } catch (e) {
          console.log(e)
        }
        doc.generate()
      })
    }
  },
}
</script>

<style lang="scss">
.exportDocument {
  position: fixed;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: nowrap;
  flex-direction: row;
  align-content: flex-start;

  .exportDocumentBut {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: nowrap;
    flex-direction: row;
    width: 120px;
    font-size: 16px;
    cursor: pointer;
    height: 50px;
    background: #0e75c1;
    border-radius: 5px;
  }
}

</style>

实例代码

代码基于vue3 vite js node.js 开发 请确保有相关的开发经验

vue3框架vue2写法

相关文件下载地址
此资源需支付 ¥1 后下载
支付宝购买扫右侧红包码购买更优惠,如无法下载请联系微信:17331886870
喜欢 (0)
vue实现导出word文档功能