1. 程式人生 > 其它 >vue中匯出圖表資料成為word文件(含echats)

vue中匯出圖表資料成為word文件(含echats)

技術標籤:文字操作vuevuexmljs

安裝依賴

	// 下載
	npm install docxtemplater pizzip  --save
	npm install jszip-utils --save 
	npm install jszip --save
	npm install file-saver --save
	//在需要匯出Word的vue檔案匯入
	import JSZipUtils from 'jszip-utils'import docxtemplater from 'docxtemplater'import { saveAs } from 'file-saver'
import PizZip from 'pizzip'

設定模板

在這裡插入圖片描述
注意:vue cli2 放在static目錄下,vue cli3 放在public

獲取echats的base64

  const myChart = echarts.init(element)
      const img = new Image()
      // 獲取圖表base64
      img.src = myChart.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
})

注意要圖片格式一定要是png的,如果獲取不到對應的base64,一個是把echats的動畫關掉,一個是定時器延時獲取。

匯出word文件

    // 這裡是官網寫的應該是處理圖片的程式碼,照著寫就行,沒動過
    base64DataURLToArrayBuffer (dataURL) {
      console.log(dataURL, 'dataURL')
      const base64Regex = /^data:image\/(png|jpg|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 exportWord () { // 這裡要引入處理圖片的外掛,下載docxtemplater後,引入的就在其中了 const ImageModule = require('docxtemplater-image-module-free') const that = this // 這裡是我的Word路徑,在static檔案下 JSZipUtils.getBinaryContent('../../../static/input.docx', function (error, content) { if (error) { throw error } const opts = {} opts.centered = true opts.fileType = 'docx' opts.getImage = (tag) => { return that.base64DataURLToArrayBuffer(tag) } opts.getSize = () => { return [600, 400]// 這裡可更改輸出的圖片寬和高 } const zip = new PizZip(content) const doc = new docxtemplater() doc.attachModule(new ImageModule(opts)) doc.loadZip(zip) //這個地方的資料就是word的變數名是用一個,是需要解析的。 doc.setData({ txt: that.txt, imgBase64: that.imgBase64, imgBase64_two: that.imgBase64_two, imgBase64_type: that.imgBase64_type, imgBase64_level: that.imgBase64_level // 一切要匯出的資料名稱 }) try { doc.render() } catch (error) { const e = { message: error.message, name: error.name, stack: error.stack, properties: error.properties, } console.log(JSON.stringify({ error: e })) throw error } const out = doc.getZip().generate({ type: 'blob', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', }) saveAs(out, `資料分析.docx`) }) }, }

小坑

mock不要和匯出檔案一起用,需要關掉。圖片載入不出來,看看是不是沒有加載出來;先用瀏覽器開啟base64的圖片。
在這裡插入圖片描述
點選對面的copy進行復制,不要自己手動去複製。

參考專案:https://github.com/weitangshi/study.git
參考部落格:https://blog.csdn.net/target_for/article/details/108122644
https://www.jianshu.com/p/b3622d6f8d98