我需要在我的服务器中有一个 word 文档。当有人点击保存按钮时,我需要将数据保存在文档中。我使用以下内容创建一个 word 文档。它为我创建了一个新文档,但我想将数据附加到现有文档。
const fs = require('fs');
const docx = require('docx');
let doc = new docx.Document();
let paragraph = new docx.Paragraph("welcome to my document");
//when client loads a new page and clicks save button
app.post('/newpg',(req,res)=>{
paragraph.addRun(new docx.TextRun("Another line to be added"));
doc.addParagraph(paragraph);
**let packer = new docx.Packer();
packer.toBuffer(doc).then((buffer)=>{
fs.writeFileSync("sample.docx",buffer);
});**
最佳答案
这段代码应该可以工作,它与您已有的代码非常相似,我只是添加了响应和错误处理。
const fs = require('fs');
const docx = require('docx');
let doc = new docx.Document();
let paragraph = new docx.Paragraph("welcome to my document");
//when client loads a new page and clicks save button
app.post('/newpg', (req, res) => {
paragraph.addRun(new docx.TextRun("Another line to be added"));
doc.addParagraph(paragraph);
let packer = new docx.Packer();
packer.toBuffer(doc).then((buffer) =>{
fs.writeFileSync("sample.docx",buffer);
res.status(201).json({ status: "Doc updated"} );
}).catch(err => {
res.status(500).json({ status: "An error occurred updating document." });
});
});
关于javascript - 如何使用 docx 包附加文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56785194/