参考: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);
});
}