我很好奇是否可以附加到我用 Js 和 docx 模块创建的生成的 Word 文档。 目前我可以生成文档并格式化它。 然而,我在他们的文档中没有看到任何有关向现有文档追加或添加段落的内容(有一个关于导出的部分,但它总是创建一个新文件,即使其名称相同)。 这是 JavaScript 的限制吗? 我假设由于我想在系统文件中查找文档,这会产生安全问题(来自浏览器的 JS 在最终用户系统中查找文件),因此为什么 docx 不这样做。 非常感谢对此的任何指导。 另外,如果不是的话,使用 Word API 可以解决这个问题吗?
附注我可以分享生成文档的代码,但这部分运行良好,我只需要知道我想要的是否可能,或者我是否在浪费时间。
这是我尝试过并从 stackoverflow 找到的一个功能,但它是针对网络应用程序的,这是一个 chrome 扩展。 我环顾四周,找不到其他可以尝试的东西。 理想情况下,我想写入生成的文档并添加到其中。
// pretty sure I cann't utilize a function like this unfornately
// all code is functional before this is call
function writeToDocument(doc, text){
let paragraph = new docx.Paragraph();
// invalid code
// paragraph.addRun(new docx.TextRun(text));
// doc.addParagraph(paragraph);
let packer = new docx.Packer();
docx.packer.toBuffer(doc).then((buffer) =>{
fs.writeFileSync(docName + ".docx",buffer);
});
}
看来这是图书馆的限制。有 addSection() 但它是私有的。此外,没有方法可以打开以前生成的文件。
唯一的方法是:先创建内容,然后创建文档并保存:
let paragraphs = [];
//any way to add element to array, eg
paragraphs[paragraphs.length] = new Paragraph({
children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo Bar",
bold: true,
}),
new TextRun({
text: "\tGithub is the best",
bold: true,
}),
],
});
//paragraphs[paragraphs.length] = addAnotherParagraph()
//create document
const doc = new Document({
sections: [
{
properties: {},
children: paragraphs,
},
],
});
//and save it in fauvorite way
Packer.toBuffer(doc).then((buffer) => {
//why in `docx` documentation uses sync versioin?... You should avoid it
fs.writeFileSync("My Document.docx", buffer);
});
因此您(现在)可以使用 docx“修补”文档。使用 KV 对,您可以指定要插入的相当高级的对象,但我认为它仅限于段落(即您不能创建节等)。实际上,您可以使用标记来执行高级“查找和替换”来识别要查找的内容。