word文档插入文字出错

Error inserting text into word document

我有一个 MS Word 加载项,其中包含在选择后插入文本的代码:

Word.run(function (context) {

    var selection = context.document.getSelection();           
    selection.insertText(text, Word.InsertLocation.after).select();

    return context.sync().then(function () {      
        console.log('Success');
    });

});

此代码已在多台不同机器上测试无误。然而,令我惊讶的是,我们的一位客户最近报告说他的文档中根本没有添加任何文本。

经过一些调试,我注意到消息 Success 从未打印到控制台(context.sync().then 未被调用)。只是为了确保这不是 Office API 的一些疯狂问题,我 运行 这个来自 office-js-docs 的示例直接在 F12Chooser 的控制台上并且有没有 个问题:

// Run a batch operation against the Word JavaScript API.
Word.run(function (context) {

    // Create a proxy object for the document body.
    var body = context.document.body;

    // Queue a command to load the text property of the proxy body object.
    context.load(body, 'text');

    // Queue a command to insert text into the end of the Word document body.
    body.insertText('This is text inserted after loading the body.text property',
                    Word.InsertLocation.end);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log("Body contents: " + body.text);
    });
})

(文本插入到文档末尾)

同样,我的代码 在许多不同的机器和设置中工作 ,这似乎只在这个人的机器上是个问题。他正在使用:

Office Professional Plus 2016
Microsoft Word 2016 MSO (16.0.4266.1001) 64 Bits
Windows 10 Pro
Internet Explorer 11.413.15063

有人可以帮我解决这个问题吗?谢谢!

该代码在该特定框中不起作用的原因是因为它是 Office 2016 MSI SKU(构建 42xx)(不是 Office365 aka Click-to-run sku)。 MSI SKU 有一些与有效 insertLocations 相关的错误,其中大部分错误已在 API 的 1.2 版本中修复。坏消息是 1.2+ 版本没有向后移植到 MSI 版本。

请尝试 insertLocation.end(而不是 InsertLocation.after),我认为您的代码应该可以工作(行为略有不同)

或者如果您的客户转移到 O365,问题将立即得到解决。