Vue项目导出word文档

关于Vue项目导出word文档,网上实在是有太多的方法,这里只介绍个人喜欢的一种:
使用到的依赖有docxtemplaterpizzipjszip-utilsfile-saver

  1. 安装依赖:
yarn add docxtemplater
yarn add pizzip
yarn add jszip-utils
yarn add file-saver
  1. 创建docx.js文件,引入依赖
import docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import JSZipUtils from 'jszip-utils';
import { saveAs } from 'file-saver';
  1. 定义导出函数
/**
 4. 导出docx
 5. @param { String } tempDocxPath 模板文件路径
 6. @param { Object } data 文件中传入的数据
 7. @param { String } fileName 导出文件名称
*/
export const exportDocx = (tempDocxPath, data, fileName) => {
  // 读取并获得模板文件的二进制内容
  JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {
    if (error) {
      throw error;
    }
    let zip = new PizZip(content);
    let doc = new docxtemplater().loadZip(zip);
    doc.setData(data);
    try {
      // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
      doc.render();
    } catch (error) {
      let e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties,
      };
      console.log({
        error: e
      });
      // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
      throw error;
    }
    let out = doc.getZip().generate({
      type: "blob",
      mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    }); //Output the document using Data-URI
    saveAs(out, fileName);
  });
};
  1. 定义模板文件temp.docx(示例)
    Vue项目导出word文档_第1张图片
  2. 使用
import { exportDocx } from './docx';
export default {
	methods: {
		download() {
			let data = {
				title: "趣头条脚本-不限1",
				... // other params
				table: [
					{
				        x: 1,
				        changjing: "场景1",
				        huamian: "画面1",
				        zimu: "字幕1",
				        shichang: 20,
				        note: "备注1"
					},
					{
				        x: 2,
				        changjing: "场景2",
				        huamian: "画面2",
				        zimu: "字幕2",
				        shichang: 30,
				        note: "备注2"
					}
				]
			}
			exportDocx("/static/assets/temp.docx", data, `脚本.docx`);
		}
	}
}
  1. 最终效果
    Vue项目导出word文档_第2张图片

你可能感兴趣的:(Vue)