javascript - 使用for循环在.docx文件中使用js和npm docx写一段

标签 javascript node.js npm node-modules docx

主要问题:我想在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);
})

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

最佳答案

我遇到了同样的问题...但这里有一个解决方法。 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() 会给你一个段落数组,就像你想要的那样,你可以把它作为 child 的值放在你的 Table() 中,这也应该适用于你可能尝试循环的其他事情......

关于javascript - 使用for循环在.docx文件中使用js和npm docx写一段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62757767/

相关文章:

javascript - 我的 javascript 如何确定它是由 WScript 还是浏览器调用的?

javascript - 如何对html文档中的所有行使用函数

node.js - Backbonejs,在 Collections.each 中设置模型属性时出现 "Object #<Object> has no method apply"

javascript - 查询mongodb中的javascript日期对象

npm - 软件包未安装 - "Error: tunneling socket could not be established"

javascript - 在 jquery 中使用 fontawesome

javascript - 从使用 jquery 创建的 iframe 调用父函数

node.js - 使用 Jest 进行单元测试 Inquirer

node.js - fatal error : JS Allocation failed when try to publish npm module

linux - npm install 会导致诸如 npm ERR 之类的错误! Debian 上的 tar.unpack 解压错误