纯vue导出word

参考:https://www.jianshu.com/p/b3622d6f8d98

这里是通过docxtemplater这个库。需要以下这些依赖,以及一个模板。

npm i docxtemplater jszip-utils pizzip file-saver --s

import docxtemplater from 'docxtemplater';
import JSZipUtils from 'jszip-utils';
import Pizzip from 'pizzip';
import { saveAs } from 'file-saver';

这里会有个问题jszip会有版本问题,3的版本太高,可以换成2.6.1版本,就可以兼容jszip-utils。这个jszip跟pizzip功能一致。

 

这里我也附带代码,区别上面的:上面导出后在docx中会有存在换行问题,核心代码:new docxtemplater(zip, { linebreaks: true }) 可以解决导出换不了行的问题。然后次方法不支持导出图片,导出图片是返回undefineds。出现最多的问题:

在这里插入图片描述

解决就是加 ./  。

private exportWord() {
        const That = this;
        const outname = That.data.post_title + '_' + That.data.realname + '.docx';
        JSZipUtils.getBinaryContent('./template/input.docx', (error: any, content: any) => {
            if (error) {
                throw error;
            }
            const zip = new Pizzip(content);
            const doc = new docxtemplater(zip, { linebreaks: true });
            doc.setData({
                title: That.data.post_title,
                realname: That.data.realname,
                content: That.data.content
            });
            try {
                doc.render();
            } catch (err) {
                const e = {
                    message: error.message,
                    name: error.name,
                    stack: error.stack,
                    properties: error.properties
                };
                console.log(JSON.stringify({ error: e }));
                throw err;
            }
            const out = doc.getZip().generate({
                type: 'blob',
                mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            });
            saveAs(out, outname);
        });
    }

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值