Word:无法将 InsertText() 插入 Cell.body

Word: Can't InsertText() into a Cell.body

测试版库:https://appsforoffice.microsoft.com/lib/beta/hosted/office.js

Word 2016 Office 预览体验成员快速,版本 1610(内部版本 7416.1000)


我有一个 Word 文档,里面有一个简单的 Table(我每次测试时都使用生成一个 table,其中有几行和几列,没有现有数据) ,我正在遍历尝试用文本填充单元格的行。

尝试此操作时出现此错误:

Error: ItemNotFound: ItemNotFound
Debug info: {"errorLocation":"TableRowCollection.getItem"}

我的应用是MS visual studio创建的Demo WordWebAddin,我的代码是这样的:

Word.run(function (context) {
        var tables = context.document.body.tables
        tables.load({ expand:"rows/cells/items/body/text"})

        return context.sync().then(function () {
            var rows = tables.items[0].rows
            rows.items[1].cells.items[1].body.insertText("ryanasoefijasojef", Word.InsertLocation.replace)

            return context.sync();
        })
    })
    .catch(errorHandler);

我已经尝试了多种导航到单元格正文的机制 - 如果我使用 cells.items[0].body.text 我会成功取回单元格文本正文,所以我能够按照我想要的方式使用单元格预计。但无论我做什么,我都会遇到某种 itemNotFound 异常。我还尝试了各种值(或不是插入位置参数的值,包括(无)、对 InsertLocation 对象的引用和字符串 "replace" 等。绝对有可能我正在使用 API 不正确,但我相信我根据文档正确使用它。

编辑 我喜欢任何形式的确认。要么我做的是对的,要么是错的,要么它不适合你,要么什么的。感谢您的帮助!

我给你的建议是使用getCell method of the Table object。该方法获取table范围内所需的特定单元格的零基坐标,然后您可以轻松访问单元格主体。查看下面的示例代码,另请注意,您无需扩展任何内容即可使此代码正常工作。

顺便说一句,您可能需要切换回八月分叉 (16.7369.XXX),因为在九月分叉中引入的 Office.js 中有重大变化,我们重命名了一些方法,我们的计划是在 9 月叉发布后更新预览 CDN 上的 Office.js。感谢使用预览版!

 Word.run(function (context) {
            var tables = context.document.body.tables
            tables.load()
            return context.sync().then(function () {
               tables.items[0].getCell(0, 0).body.insertText("ryanasoefijasojef", Word.InsertLocation.replace)
               return context.sync();
            })
        })
    .catch(function (e) {
                app.showNotification(e.message);
            })
       
    }