如何使用docx包附加文件

时间:2019-06-27 06:32:53

标签: javascript node.js

我需要在服务器中输入一个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);
    });**

1 个答案:

答案 0 :(得分:0)

此代码应该可以工作,它与您已经拥有的代码非常相似,我只是添加了响应和错误处理。

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." });
    });
});