vue實現導出word文檔的示例代碼
更新時間:2024年01月23日 08:18:24 作者:Grant丶
這篇文章主要為大家詳細介紹了如何使用vue實現導出word文檔(包括圖片),文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
vue 導出word文檔(包括圖片)
1.打開終端,安裝依賴
-- 安裝 docxtemplater npm install docxtemplater pizzip --save -- 安裝 jszip-utils npm install jszip-utils --save -- 安裝 jszip npm install jszip --save -- 安裝 FileSaver npm install file-saver --save -- 安裝 angular-expressions npm install angular-expressions --save -- 安裝 image-size npm install image-size --save
2.創(chuàng)建exportFile.js文件(導出word方法)
文件存放目錄自定義
import PizZip from 'pizzip'
import docxtemplater from 'docxtemplater'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'
/**
* 將base64格式的數據轉為ArrayBuffer
* @param {Object} dataURL base64格式的數據
*/
function base64DataURLToArrayBuffer (dataURL) {
const base64Regex = /^data:image\/(png|jpg|jpeg|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,支持圖片
* @param {Object} tempDocxPath 模板文件路徑
* @param {Object} wordData 導出數據
* @param {Object} fileName 導出文件名
* @param {Object} imgSize 自定義圖片尺寸
*/
export const exportWord = (tempDocxPath, wordData, fileName, imgSize) => {
// 這里要引入處理圖片的插件
var ImageModule = require('docxtemplater-image-module-free');
const expressions = require("angular-expressions");
// 讀取并獲得模板文件的二進制內容
JSZipUtils.getBinaryContent(tempDocxPath, function (error, content) {
if (error) {
throw error;
}
expressions.filters.size = function (input, width, height) {
return {
data: input,
size: [width, height],
};
};
// function angularParser (tag) {
// const expr = expressions.compile(tag.replace(/'/g, "'"));
// return {
// get (scope) {
// return expr(scope);
// },
// };
// }
// 圖片處理
let opts = {}
opts = {
// 圖像是否居中
centered: false
};
opts.getImage = (chartId) => {
// console.log(chartId);//base64數據
// 將base64的數據轉為ArrayBuffer
return base64DataURLToArrayBuffer(chartId);
}
opts.getSize = function (img, tagValue, tagName) {
// console.log(img);//ArrayBuffer數據
// console.log(tagValue);//base64數據
// console.log(tagName);//wordData對象的圖像屬性名
// 自定義指定圖像大小
if (imgSize.hasOwnProperty(tagName)){
return imgSize[tagName];
} else {
return [600, 350];
}
}
// 創(chuàng)建一個PizZip實例,內容為模板的內容
let zip = new PizZip(content);
// 創(chuàng)建并加載docxtemplater實例對象
let doc = new docxtemplater();
doc.attachModule(new ImageModule(opts));
doc.loadZip(zip);
doc.setData(wordData);
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, fileName);
});
}3.組件調用
注意:引用文件的路徑是你創(chuàng)建文件的路徑
<template>
<a-form-model
ref="ruleForm"
:model="form"
:rules="rules"
:label-col="labelCol"
:wrapper-col="wrapperCol"
>
<a-form-model-item label="名稱" prop="name">
<a-input-number v-model="form.name" style="width:100%;"/>
</a-form-model-item>
<a-form-model-item label="日期" prop="date">
<a-input v-model="form.date" />
</a-form-model-item>
<a-form-model-item label="文件">
<a-input v-model="form.imgUrl" read-only/>
<a-upload name="file" :showUploadList="false" :customRequest="customRequest">
<a-button type="primary" icon="upload">導入圖片</a-button>
</a-upload>
</a-form-model-item>
<a-form-model-item label="操作">
<a-button type="primary" icon="export" @click="exportWordFile">導出word文檔</a-button>
</a-form-model-item>
</a-form-model>
</template>
<script>
import {exportWord} from '@/assets/js/exportFile.js'
export default {
name: 'ExportFile',
data () {
return {
labelCol: { span: 6 },
wrapperCol: { span: 16 },
form: {},
rules: {
name: [
{ required: true, message: '請輸入名稱!', trigger: 'blur' },
],
date:[
{ required: true, message: '請輸入日期!', trigger: 'blur' },
],
},
};
},
created (){},
methods: {
customRequest (data){
//圖片必須轉成base64格式
var reader = new FileReader();
reader.readAsDataURL(data.file);
reader.onload = () => {
// console.log("file 轉 base64結果:" + reader.result);
this.form.imgUrl = reader.result; //imgUrl必須與模板文件里的參數名一致
};
reader.onerror = function (error) {
console.log("Error: ", error);
};
},
exportWordFile (){
let imgSize = {
imgUrl:[65, 65], //控制導出的word圖片大小
};
exportWord("./static/test.docx", this.form, "demo.docx", imgSize);
//參數1:模板文檔
//參數2:字段參數
//參數3:輸出文檔
//參數4:圖片大小
}
},
};
</script>4.創(chuàng)建test.docx文檔模板
注:使用vue-cli2的時候,放在static目錄下;使用vue-cli3的時候,放在public目錄下。
模板參數名需與字段一致,普通字段:{字段名},圖片字段:{%字段名}
文檔內容:

5.導出demo.docx
結果展示:


以上就是vue實現導出word文檔的示例代碼的詳細內容,更多關于vue導出word的資料請關注腳本之家其它相關文章!
相關文章
Vue?CompositionAPI中watch和watchEffect的區(qū)別詳解
這篇文章主要為大家詳細介紹了Vue?CompositionAPI中watch和watchEffect的區(qū)別,文中的示例代碼簡潔易懂,希望對大家學習Vue有一定的幫助2023-06-06
ElementUI時間選擇器限制選擇范圍disabledData的使用
本文主要介紹了ElementUI時間選擇器限制選擇范圍disabledData的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06

