vue前端html页面导出word文件,Vue-纯前端导出word文档

在项目中,我们可以借助后端返回文件流实现文件下载。如果前端有数据,也可以借助前端框架进行下载。本文将介绍如何在前端纯js实现word文档导出。

1. 组件介绍

要实现前端纯js导出word文档,我们需要用到docxtemplater,jszip-utils,file-saver三个组件,接下来简要的介绍以下三个组件。

1.1 docxtemplater

docxtemplater 使用 JSON 数据格式作为输入,可以处理docx 和 ppt模板。不像一些其它的工具,比如 docx.js, docx4j, python-docx 等,需要自己编写代码来生成文件,docxtemplater只需要用户通过标签的形式编写模板,就可以生成文件。

贴一贴官网给的例子,我们将参考以下例子来实现。

var PizZip = require('pizzip');

var Docxtemplater = require('docxtemplater');

var fs = require('fs');

var path = require('path');

//Load the docx file as a binary

var content = fs

.readFileSync(path.resolve(__dirname, 'input.docx'), 'binary');

var zip = new PizZip(content);

var doc = new Docxtemplater();

doc.loadZip(zip);

//set the templateVariables

doc.setData({

first_name: 'John',

last_name: 'Doe',

phone: '0652455478',

description: 'New Website'

});

try {

// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)

doc.render()

}

catch (error) {

你可能感兴趣的:(vue前端html页面导出word文件,Vue-纯前端导出word文档)