在Word文档中插入带有文本插入的换行符

时间:2018-12-13 06:23:58

标签: ms-word office-js word-addins

使用javascript(office.js)构建文字插件。到目前为止,未格式化的文本带有.insertText。如果我要插入以下内容,应使用哪个功能?

  • 格式化的文本(例如大小,字体,样式)
  • 换行符
  • 子弹点

代码:

results.items[i].insertText("Any text going here.", "replace");

例如,如何在“此处有任何文本”中插入换行符?

2 个答案:

答案 0 :(得分:2)

使用JavaScript,使用字符串{{1}添加一个“换行符”(我假设您的意思与在UI中按ENTER相同-从技术上讲,这是新段落) }。因此,例如:

"\n"

答案 1 :(得分:0)

  • 使用insertBreak插入不同类型的分隔符。可能是换行符,段落分隔符,分节符等。
insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void;
  • 用于添加诸如要点之类的列表。使用startNewList
startNewList(): Word.List;

列表示例

//This example starts a new list stating with the second paragraph.
await Word.run(async (context) => {
    let paragraphs = context.document.body.paragraphs;
    paragraphs.load("$none"); //We need no properties.

    await context.sync();

    var list = paragraphs.items[1].startNewList(); //Indicates new list to be started in the second paragraph.
    list.load("$none"); //We need no properties.

    await context.sync();

    //To add new items to the list use start/end on the insert location parameter.
    list.insertParagraph('New list item on top of the list', 'Start');
    let paragraph = list.insertParagraph('New list item at the end of the list (4th level)', 'End');
    paragraph.listItem.level = 4; //Sets up list level for the lsit item.
    //To add paragraphs outside the list use before/after:
    list.insertParagraph('New paragraph goes after (not part of the list)', 'After');

    await context.sync();
});
  • 要设置文本格式,请查看此处设置字体家族和颜色的examples以获得提示。
//adding formatting like html style
var blankParagraph = context.document.body.paragraphs.getLast().insertParagraph("", "After");
blankParagraph.insertHtml('<p style="font-family: verdana;">Inserted HTML.</p><p>Another paragraph</p>', "End");
// another example using modern Change the font color
// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Create a range proxy object for the current selection.
    var selection = context.document.getSelection();

    // Queue a commmand to change the font color of the current selection.
    selection.font.color = 'blue';

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log('The font color of the selection has been changed.');
    });
})
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});

Word插件tutorial对于带有代码示例的常见任务有很多漂亮的技巧。