【问题标题】:Using for loop to write a paragraph inside .docx file using js with npm docx使用 for 循环在 .docx 文件中使用 js 和 npm docx 编写段落
【发布时间】:2020-12-02 04:31:59
【问题描述】:

主要问题:我想在 Microsoft Word 文档中插入 40 多个文本。 通过java脚本代码:

// 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);
})

我尝试了所有方法,但没有任何效果。

【问题讨论】:

    标签: javascript node.js npm node-modules docx


    【解决方案1】:

    我也有同样的问题......但这里有一个解决方法。 Docx.J 的库不允许在 TableCell 或 TableRow 中循环,因此最好在 Table() 之外循环。假设您有一个字符串列表...

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

    所以 buildParagrahp() 会给你一个你想要的段落数组,你可以把它作为孩子的值放在你的 Table() 中,这也应该适用于你可以尝试循环的其他事情......

    【讨论】:

    • 实际上我通过使用称为 docxtemplater 的不同依赖项解决了这个问题,但最后我发现我自己产生了一个新问题,所以最后我决定改变项目概念并从.docx 到 EJS 模块,解决问题并提高项目性能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多