前端Vue.js实现json数据导出到doc

 更新时间:2022年09月15日 09:53:56   作者:baldwin​​​​​​​  
这篇文章主要介绍了前端Vue.js实现json数据导出到doc,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下

前言:

先说下需求:如何批量导出表格中勾选的数据,导出格式为word,并具有一定的格式!

开发环境:vue3、node v14.15.0

组件选择

因为导出word需要保留一定的格式,所以这里选择docxtemplater,利用定制导出模板的方式限制数据的导出格式。

实现一个最简单的导出

安装(后续的demo依赖相同)

yarn add docxtemplater pizzip file-saver

用法:

onst PizZip = require("pizzip");
const Docxtemplater = require("docxtemplater");
const fs = require("fs");
const path = require("path");
// Load the docx file as binary content
const content = fs.readFileSync(
    path.resolve(__dirname, "input.docx"),
    "binary"
);
const zip = new PizZip(content);
const doc = new Docxtemplater(zip, {
    paragraphLoop: true,
    linebreaks: true,
});
// Render the document (Replace {first_name} by John, {last_name} by Doe, ...)
doc.render({
    first_name: "John",
    last_name: "Doe",
    phone: "0652455478",
    description: "New Website",
});
const buf = doc.getZip().generate({
    type: "nodebuffer",
    // compression: DEFLATE adds a compression step.
    // For a 50MB output document, expect 500ms additional CPU time
    compression: "DEFLATE",
});

单条数据导出到word

配置导出模板,并上传CDN,模板格式如下:

导出的数据结构:

{
    "title": "第一篇",
    "gradeId": "三年级上",
    "genreDesc": "议论文",
    "subjectMatterInfo": "叙事",
    "content": "\t一个晴朗的星期天,爸爸和妈妈带我到北海公园去玩儿。那天秋高气爽,太阳在蓝",
    "remark": "点评1"
}

导出wrod截图

具体实现:

import Docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import PizZipUtils from 'pizzip/utils/index.js';
import {saveAs} from 'file-saver';

function loadFile(url, callback) {
    PizZipUtils.getBinaryContent(url, callback);
}

export const renderDoc = data => {
    loadFile('你上传导出模板的CDN链接.docx', (error, content) => {
        if (error) {
            throw error;
        }
        const zip = new PizZip(content);
        const doc = new Docxtemplater(zip, {linebreaks: true});
        doc.setData(data);
        try {
            // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
            doc.render();
        }
        catch (error) {
            // The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
            function replaceErrors(key, value) {
                if (value instanceof Error) {
                    return Object.getOwnPropertyNames(value).reduce((error, key) => {
                        error[key] = value[key];
                        return error;
                    }, {});
                }
                return value;
            }
            console.log(JSON.stringify({error}, replaceErrors));

            if (error.properties && error.properties.errors instanceof Array) {
                const errorMessages = error.properties.errors
                    .map(error => error.properties.explanation)
                    .join('\n');
                console.log('errorMessages', errorMessages);
                // errorMessages is a humanly readable message looking like this :
                // 'The tag beginning with "foobar" is unopened'
            }
            throw error;
        }
        const out = doc.getZip().generate({
            type: 'blob',
            mimeType:
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        });
        // Output the document using Data-URI
        saveAs(out, '导出word.docx');
    });
};

批量数据导出到wrod

配置导出模板,并上传CDN,模板格式如下:

#articles为循环开始,/为循环结束,中间是循环体

导出的数据结构:

{
    "articles": [
        {
            "title": "第一篇",
            "gradeId": "三年级上",
            "genreDesc": "议论文",
            "subjectMatterInfo": "叙事",
            "content": "\t一个晴朗的星期天,爸爸和妈妈带我到北海公园去玩儿。那天秋高气爽,太阳在蓝",
            "remark": "点评1"
        },
        {
            "title": "第二篇",
            "gradeId": "三年级下",
            "genreDesc": "记叙文",
            "subjectMatterInfo": "写人",
            "content": "\t一个晴朗的星期天,爸爸和妈妈带我到北海公园去玩儿妈带我到北海公园去玩儿。那天秋高气爽,太阳在蓝。\n问女何所思,问女何所忆。女亦无所思,女亦无所忆。昨夜见军帖,可汗大点兵,军书十二卷,卷卷有爷名。阿爷无大儿,木兰无长兄,愿为市鞍马,从此替爷征。问女何所思,问女何所忆。女亦无所思,女亦无所忆。昨夜见军帖,可汗大点兵,军书十二卷,卷卷有爷名。阿爷无大儿,木兰无长兄,愿为市鞍马,从此替爷征。",
            "remark": "点评2"
        }
    ]
}

导出wrod截图:

具体实现:

import Docxtemplater from 'docxtemplater';
import PizZip from 'pizzip';
import PizZipUtils from 'pizzip/utils/index.js';
import {saveAs} from 'file-saver';

function loadFile(url, callback) {
    PizZipUtils.getBinaryContent(url, callback);
}
export const renderDoc = data => {
    loadFile('你上传导出模板的CDN链接.docx', (error, content) => {
        if (error) {
            throw error;
        }
        const zip = new PizZip(content);
        // paragraphLoop段落循环
        const doc = new Docxtemplater(zip, {paragraphLoop: true, linebreaks: true});
        doc.setData(data);
        try {
            // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
            doc.render();
        }
        catch (error) {
            // The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
            function replaceErrors(key, value) {
                if (value instanceof Error) {
                    return Object.getOwnPropertyNames(value).reduce((error, key) => {
                        error[key] = value[key];
                        return error;
                    }, {});
                }
                return value;
            }
            console.log(JSON.stringify({error}, replaceErrors));

            if (error.properties && error.properties.errors instanceof Array) {
                const errorMessages = error.properties.errors
                    .map(error => error.properties.explanation)
                    .join('\n');
                console.log('errorMessages', errorMessages);
                // errorMessages is a humanly readable message looking like this :
                // 'The tag beginning with "foobar" is unopened'
            }
            throw error;
        }
        const out = doc.getZip().generate({
            type: 'blob',
            mimeType:
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        });
        // Output the document using Data-URI
        saveAs(out, '导出word.docx');
    });
};

到此这篇关于前端Vue.js实现json数据导出到doc的文章就介绍到这了,更多相关Vue.js json数据导出doc内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • vue 本地环境跨域请求proxyTable的方法

    vue 本地环境跨域请求proxyTable的方法

    今天小编就为大家分享一篇vue 本地环境跨域请求proxyTable的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-09-09
  • 单页面Vue页面刷新出现闪烁问题及解决

    单页面Vue页面刷新出现闪烁问题及解决

    这篇文章主要介绍了单页面Vue页面刷新出现闪烁问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • element-ui中el-form-item内的el-select该如何自适应宽度

    element-ui中el-form-item内的el-select该如何自适应宽度

    自从用了element-ui,确实好用,该有的组件都有,但是组件间的样式都固定好了,下面这篇文章主要给大家介绍了关于element-ui中el-form-item内的el-select该如何自适应宽度的相关资料,需要的朋友可以参考下
    2022-11-11
  • Vue 中 Promise 的then方法异步使用及async/await 异步使用总结

    Vue 中 Promise 的then方法异步使用及async/await 异步使用总结

    then 方法是 Promise 中 处理的是异步调用,异步调用是非阻塞式的,在调用的时候并不知道它什么时候结束,也就不会等到他返回一个有效数据之后再进行下一步处理,这篇文章主要介绍了Vue 中 Promise 的then方法异步使用及async/await 异步使用总结,需要的朋友可以参考下
    2023-01-01
  • Vue 数据绑定事件绑定样式绑定语法示例

    Vue 数据绑定事件绑定样式绑定语法示例

    这篇文章主要为大家介绍了Vue 数据绑定事件绑定样式绑定语法示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • vue 3.0 vue.config.js文件常用配置方式

    vue 3.0 vue.config.js文件常用配置方式

    这篇文章主要介绍了vue 3.0 vue.config.js文件常用配置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • Vue.js 中 ref 和 reactive 的区别及用法解析

    Vue.js 中 ref 和 reactive 的区别及用法解析

    在Vue.js中,ref主要用于创建响应式的引用,通过.value属性来访问和修改值,特别适用于需要频繁更改整个值的场景,而reactive则用于创建深度响应的对象或数组,本文给大家介绍Vue.js 中 ref 和 reactive 的区别及用法,感兴趣的朋友跟随小编一起看看吧
    2024-09-09
  • 详解IOS微信上Vue单页面应用JSSDK签名失败解决方案

    详解IOS微信上Vue单页面应用JSSDK签名失败解决方案

    这篇文章主要介绍了详解IOS微信上Vue单页面应用JSSDK签名失败解决方案,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-11-11
  • vue项目实现github在线预览功能

    vue项目实现github在线预览功能

    这篇文章主要介绍了vue项目实现github在线预览功能,本文通过提问两个问题带领大家一起学习整个过程,需要的朋友可以参考下
    2018-06-06
  • vue2.0 axios跨域并渲染的问题解决方法

    vue2.0 axios跨域并渲染的问题解决方法

    下面小编就为大家分享一篇vue2.0 axios跨域并渲染的问题解决方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-03-03

最新评论