一. 下载依赖
-
docxtemplater
介绍:docxtemplater是一种邮件合并工具,它以编程方式使用,处理条件、循环,并且可以扩展为表格、HTML、图像等。
npm i docxtemplater@^3.9.1
-
FileSaver
介绍:FileSaver.js 是在客户端保存文件的解决方案,非常适合需要生成文件,或者保存不应该发送到外部服务器的敏感信息的应用。
npm i file-saver@^1.3.8
-
jszip
介绍:jszip是一个用于创建、读取和编辑.zip文件的JavaScript库,且API的使用也很简单。
npm i jszip@^2.6.1
-
jszip-utils
介绍:jszip-utils是与jszip一起使用的跨浏览器的工具库。
npm i jszip-utils@^0.0.2
二. 创建模板
根据自己的业务需求新建一个
test.docx
文件当做模板,根据docxtemplater的语法,变量数据使用变量名代替。
注意:模板文件使用vue-cli2的时候,放在static目录下。使用vue-cli3的时候,放在public目录下。这里请注意会有一个坑的,一定要看清楚这里写的是 vue-cli2 不是在 vue2中 所以在 pakeage.json 文件中看自己项目的vue-cli版本就好了,我自己当时就是把 vue-cli2 看成 vue2了 所以一直报一个错,如下图所示。
其实这个错误就是在告诉我们找不到文件。我们把它模板word文件放在public目录下就好了。
三. 编写代码
<template>
<div>
<button @click="downloadprice">导出word</button>
</div>
</template>
<script>
import Docxtemplater from "docxtemplater";
import { saveAs } from "file-saver";
import JSZip from "jszip";
import JSZipUtils from "jszip-utils";
export default {
data() {
return {};
},
methods: {
downloadprice() {
// 读取并获得模板文件的二进制内容
console.log(JSZipUtils.getBinaryContent);
JSZipUtils.getBinaryContent("/test.docx", (error, content) => {
console.log("-----", content);
// pricenew.docx是模板。我们在导出的时候,会根据此模板来导出对应的数据
// 抛出异常
if (error) {
throw error;
}
// 创建一个JSZip实例,内容为模板的内容
let zip = new JSZip(content);
console.log("+++++", zip);
// 创建并加载docxtemplater实例对象
let doc = new Docxtemplater();
console.log("/////", doc);
doc.loadZip(zip);
console.log("=====", doc);
doc.setData({
first_name: "John",
last_name: "Doe",
phone: "0652455478",
description: "New Website",
});
try {
// 用模板变量的值替换所有模板变量
doc.render();
} catch (error) {
// 抛出异常
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, "text.docx");
});
},
},
};
</script>
还有一个注意点就是下图的 "/test.docx" 这个路径, 不管你的组件在哪一个层级中 只能写成 "/test.docx", 如果写成 “/public/test.docx” 或者 “../../public/test.docx”, 一样会报错。
JSZipUtils.getBinaryContent("/test.docx", (error, content) => {
以上就是我在 vue 中做导出 word 功能的总结,也是在网上看了好多博客 资料 整理出来的,也踩了坑,所以借此机会记录下来,分享出去,希望给各位看到的朋友能带来一些帮助。如果文章中有哪些错误的地方,也请帮忙指出,感谢各位!!!