使用javascript替换Excel中的占位符文本



我们有一个excel报告模板,它有一些占位符文本(键(,在创建报告时会被某些值替换。

我们到处搜索,但找不到任何使用javascript的解决方案(我知道我们可以使用c#/.Net来完成,但我们的项目是使用AngularCLI的,操作是使用javascript完成的(。

我们已经看到/阅读了exceljs,但它仍然不满足这个要求。

有没有任何方法或JS库能够完成特定的任务,或者我们运气不好?

我们实现的解决方案是使用docxtemplater,但我们使用word(docx(而不是excel。

docxtemplator是一个库,用于从docx/pptx模板。它可以用数据替换{占位符},还可以支持循环和条件。模板可由编辑非程序员,例如,您的客户

可用作npm:docxtemplater

从文档中提取的示例代码:

const 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",
});
// buf is a nodejs Buffer, you can either write it to a
// file or res.send it with express for example.
fs.writeFileSync(path.resolve(__dirname, "output.docx"), buf);

最新更新