当前位置:首页 > VUE

vue实现word文档

2026-03-28 17:06:33VUE

使用vue-office库生成Word文档

vue-office是一个专门用于Vue.js的库,支持Word、Excel和PDF文档的在线预览和导出。安装依赖:

npm install @vue-office/docx vue-demi

创建Word导出组件:

<template>
  <button @click="exportToDocx">导出Word</button>
</template>

<script>
import VueOfficeDocx from '@vue-office/docx'
import { saveAs } from 'file-saver'

export default {
  components: {
    VueOfficeDocx
  },
  methods: {
    exportToDocx() {
      const content = '<h1>标题</h1><p>这是Word文档内容</p>'
      VueOfficeDocx.renderAsync(content).then(blob => {
        saveAs(blob, 'document.docx')
      })
    }
  }
}
</script>

使用docx.js库创建复杂Word文档

docx.js提供了更精细的Word文档控制能力。安装依赖:

npm install docx

创建带格式的文档:

import { Document, Paragraph, TextRun, Packer } from 'docx'

export default {
  methods: {
    async generateDocx() {
      const doc = new Document({
        sections: [{
          properties: {},
          children: [
            new Paragraph({
              children: [
                new TextRun({
                  text: "标题",
                  bold: true,
                  size: 28
                })
              ]
            }),
            new Paragraph({
              children: [
                new TextRun({
                  text: "正文内容",
                  size: 24
                })
              ]
            })
          ]
        }]
      })

      const blob = await Packer.toBlob(doc)
      saveAs(blob, "document.docx")
    }
  }
}

使用html-docx-js转换HTML

将HTML转换为Word文档:

npm install html-docx-js

实现代码:

import htmlDocx from 'html-docx-js/dist/html-docx'

export default {
  methods: {
    exportHtmlToWord() {
      const html = `
        <h1>文档标题</h1>
        <p>段落内容</p>
        <ul>
          <li>项目1</li>
          <li>项目2</li>
        </ul>
      `
      const converted = htmlDocx.asBlob(html)
      saveAs(converted, 'document.docx')
    }
  }
}

服务端生成方案

对于大型应用,可以考虑服务端生成:

// 客户端
axios.post('/api/generate-word', {
  content: '文档内容'
}, { responseType: 'blob' })
.then(response => {
  const url = window.URL.createObjectURL(new Blob([response.data]))
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', 'document.docx')
  document.body.appendChild(link)
  link.click()
})

// 服务端(Node.js示例)
const express = require('express')
const { Document, Paragraph, TextRun, Packer } = require('docx')

app.post('/api/generate-word', async (req, res) => {
  const doc = new Document({
    sections: [{
      children: [
        new Paragraph({
          children: [new TextRun(req.body.content)]
        })
      ]
    }]
  })

  const buffer = await Packer.toBuffer(doc)
  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
  res.send(buffer)
})

模板化解决方案

创建可复用的Word模板:

vue实现word文档

// templates.js
export const reportTemplate = (data) => ({
  sections: [{
    children: [
      new Paragraph({
        children: [new TextRun({
          text: data.title,
          bold: true
        })]
      }),
      ...data.items.map(item => new Paragraph({
        children: [new TextRun(item)]
      }))
    ]
  }]
})

// 组件中使用
import { reportTemplate } from './templates'

const doc = new Document(reportTemplate({
  title: '月度报告',
  items: ['项目A', '项目B', '项目C']
}))

以上方案可根据项目需求选择,vue-office适合简单预览和导出,docx.js适合复杂格式控制,服务端方案适合处理大量数据,模板化方法适合需要标准格式的场景。

标签: 文档vue
分享给朋友:

相关文章

vue alert实现

vue alert实现

使用 Vue 实现 Alert 组件 在 Vue 中实现 Alert 组件可以通过自定义组件或结合第三方库完成。以下是几种常见方法: 自定义 Alert 组件 创建一个可复用的 Alert 组件,通…

vue 实现排序

vue 实现排序

Vue 实现排序的方法 使用计算属性实现排序 通过计算属性对数组进行排序,可以保持原始数据不变。示例代码展示了如何对列表按名称升序排序: <template> <div>…

vue实现上传

vue实现上传

Vue 文件上传实现方法 使用 Vue 实现文件上传可以通过原生 HTML5 的 <input type="file"> 元素结合 Vue 的事件处理和数据绑定来实现。 基础实现步骤…

vue实现slot

vue实现slot

Vue 中的 Slot 实现方法 Vue 的 slot 是一种内容分发机制,允许父组件向子组件插入内容。以下是几种常见的 Slot 实现方式: 默认 Slot 子组件通过 <slot>…

vue 实现拖拉

vue 实现拖拉

Vue 实现拖拽功能的方法 使用 HTML5 原生拖放 API HTML5 提供了原生的拖放 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 dr…

vue实现computed

vue实现computed

Vue 中 computed 的实现原理 computed 属性是 Vue 的一个核心特性,它基于响应式依赖进行缓存,仅在依赖发生变化时重新计算。以下是 computed 的实现方式: 基本用法 在…