第一章 vue学习实践
前言
根据需求,需要将页面表格和echarts图表导出到一张word文档中。由于之前没有涉及到此类的要求,走了很多坑,最终实现。然而,里面还是有很多不清晰的,后续有时间再研究。
一、准备工作
先使用vue3铺好页面(页面比较潦草,数据使用mock模拟的数据),然后设计点击下载的组件。将页面的数据按照模板保存在桌面。
二、使用步骤
1.引入库
先导入需要的库:pizzip、docxtemplater、docxtemplater-image-module-free、jszip-utils、file-saver
import PizZip from "pizzip";
import docxtemplater from "docxtemplater";
import ImageModule from "docxtemplater-image-module-free";
import JSZipUtils from "jszip-utils";
import { saveAs } from "file-saver";
下载依赖 eg: yarn pizzip
yarn add docxtemplater-image-module-free:yarn安装失败的情况,package.json文件设置"dependencies": {“docxtemplater-image-module-free”: “^1.1.1”, …} 然后yran即可。
如果报错,无法找到模块“file-saver”的声明文件等,在***.d.ts文件声明即可
declare module "file-saver";
declare module "jszip-utils";
declare module "docxtemplater-image-module-free";
2.部分代码
代码如下(示例):
const props = defineProps<{
tableData: any[]; //传入的table表格数组
setItemRef: any[]; //传入的base64的图片列表
[key: string]: any[]; //其他可能传入的值
}>();
// 导出echarts图片,格式转换,官方自带,不需要修改
const base64DataURLToArrayBuffer = (dataURL: string) => {
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
const exportWord = function () {
const imagelist = toRefs(props.setItemRef).map((val: any) => ({ imgurl: val.value.imgurl }));
//处理父组件传入的图片路径, [{imgurl: ''}, {imgurl: ''}]
// 读取并获得模板文件的二进制内容,放在项目中即可
//input.docx文件。在vue2文档模板需要放在static文件夹下。vue3文档模板需要放在public文件夹下。文档需要以.docx后缀名,直接从.doc重命名不行,需要另存为.docx。直接放文件名。
JSZipUtils.getBinaryContent("input.docx", function (error: any, content: any) {
if (error) {
throw error;
}
// 图片处理
let opts = {};
opts = {
centered: true, //图像是否居中,true:在word中图片居中
getImage: (chartId: any) => {
return base64DataURLToArrayBuffer(chartId);
},
//自定义指定图像大小,此处可动态调试各别图片的大小
getSize: (img: any, tagValue: any, tagName: any) => {
if (tagName === "imgurl") return [700, 350]; //设置图片宽高,tagName :传入的变量
return [600, 350];
}
};
// 创建一个PizZip实例,内容为模板的内容
let zip = new PizZip(content);
// 创建并加载docxtemplater实例对象
let doc = new docxtemplater();
doc.attachModule(new ImageModule(opts));
doc.loadZip(zip);
// 设置模板变量的值
doc.setData({
table: props.tableData, //word文档变量
imagels: imagelist
});
try {
// 用模板变量的值替换所有模板变量
doc.render();
} catch (error: any) {
// 抛出异常
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, "demo.docx");
});
};
3.错误
1)Can‘t find end of central directory:is this a zip file?
可能的原因1:文件名不对。
按照上面方法放文件,代码中模板地址不能加斜杠。
可能原因2:模板文件后缀名不对。
另存为.docx模板文件。
2)End of data reached (data length = 0, asked index = 4). Corrupted zip ?
模板文件为空文件。
3)Uncaught Error: TemplateError: Multi error at XMLHttpRequest.xhr.onreadystatechange
word模板表格开头要以{#table}开头,{/table}结束
4)图片输出为空白,还有一条报错信息(忘了具体报错信息)
检查echarts导出的图片信息是否为空白。
//检查
<img ref="imgurl" alt="" />
let imgurl = ref();
imgurl.value.src = chartV.value.getDataURL({});
//chartV为echarts图表的ref
//图片若为空白的,第一种echarts图表的option属性的animation: false(网上找的方法,我的依然没出现)
//第二种方法,用定时器获取图片地址(我的图片出现了)
onMounted(() => {
setTimeout(() => {
imgurl.value = chartV.value.getDataURL({
type: "png",
pixelRatio: 1,
backgroundColor: "#fff"
});
}, 0);
});
//此时导出图片地址,保存即可
defineExpose({ //最后导出
imgurl
});
结果展示
文档模板:数组用{#数组名}开头, {/数组名}结尾。其中变量以 花括号的形式展示。图片变量以%开头
三、总结
提示:具体代码在middleground/tabEcharts的文件夹下
以上就是vue的图表以及表格转为word的全部记录。若有改动,想起再修改。
参考文献:
方某某.(2020).vue导出echarts图表及文本到word.CSDN博客.取自https://blog.csdn.net/laiAhaha/article/details/111267297