Using for loop to write a paragraph inside .docx file using js with npm docx

Viewed 1808

the main issue: i want to insert more than 40 text to the Microsoft word document. through java script code :

// requiring modules
const fs = require('fs'),
    docx = require('docx');

// create a new doc
const doc = new docx.Document();

// get paragraph text
const getData = new docx.Paragraph({
    children:[
        new docx.TextRun({
            text: 'Welcome from getData',
             size: 72
        }),
    ],
})

//add a section to document to render the paragraph
doc.addSection({
    children:[
        getData
    ]
});

//write the buffer to the file.docx
docx.Packer.toBuffer(doc).then((Buffer)=>{
    fs.writeFileSync("text.docx" , Buffer);
})

i tried every thing but nothing work with me.

1 Answers

I'd the same issue... But here is a work around. The Docx.J's library doesn't allow loop in either TableCell or TableRow, so it's best you loop outside Table(). Assuming you have a list of string...

let myStrings = ['firstString', 'secondString', 'thirdString'];


const buildParagraph = async(arr)=>{
 let paragraphArray = []
 arr.map((cur , index)=> {       
        paragraphArray.push(new Paragraph(cur))
    });
return paragraphArray;
};

So buildParagrahp() will give you an array of paragraphs like you intended and you can just place it as the value of the children in your Table(), this should also apply to other things you may try looping...

Related