vue 导出word(含多个echarts 图表)

722 阅读1分钟

最近在做一个功能,需要讲报告类的页面导出成word文档,网上找了些方法,记录一下,先npm安装以下依赖

Snipaste_2022-11-02_08-56-43.png

在vue页面引入

import $ from 'jquery'

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

import saveAs from 'file-saver'

在需要导出的标签上加个ref="report",另外需要注意的是写在里的样式导出会失效,需要通过内联方式写在标签内部

`

exportDocx () {
  // 克隆报告HTML
  const contentDocument = $.clone(this.$refs.report)
  this.convertChartsToBase64(contentDocument)
  const content = `<!DOCTYPE html><html>
                <head>
                    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
                </head>
                <style>
                </style>
                <body>
                    ${contentDocument.innerHTML}
                </body>
            </html>`
  const converted = htmlDocx.asBlob(content)
  saveAs(
    converted,
    `${this.info.title}.docx`
  )
  const link = this.createDownloadLink(
    converted,
    `${this.info.title}.docx`
  )
  this.$refs.downloadArea.innerHTML = ''
  this.$refs.downloadArea.appendChild(link)
},
convertChartsToBase64 (contentDocument) {
  // 多个图表
  const canvases = contentDocument.querySelectorAll('.chart-class')
  console.log(canvases)
  canvases.forEach((item, i) => {
    const echart = echarts.init(item)
    const canvas = item.querySelectorAll('canvas')[0]
    const url = echart.getDataURL()
    const img = document.createElement('img')
    img.src = url
    canvas.parentNode.replaceChild(img, canvas)
  })
  // 单个图表
  // const myChart = echarts.init(document.getElementById('chartOne'))
  // const canvas = contentDocument.querySelectorAll('canvas')[0]
  // console.log('149====', document.getElementById('chartOne'))
  // console.log('150====', myChart)
  // console.log('151====', canvas)
  // const url = myChart.getDataURL()
  // const img = document.createElement('img')
  // img.src = url
  // canvas.parentNode.replaceChild(img, canvas)
},
// 生成下载链接
createDownloadLink (fileObj, fileName) {
  const link = document.createElement('a')
  link.href = URL.createObjectURL(fileObj)
  link.download = fileName || 'document.docx'
  link.appendChild(document.createTextNode('如果没有自动下载,点这里'))
  return link
}

` 最后附个参考链接:wenku.baidu.com/view/010d86…