如何获取Microsoft Word文档的HTML个内容?

How to get HTML content of Microsoft Word document?

我使用下面的代码来获取 Microsoft Word DocumentHTML 内容:

Word.run(function (context) {
                    var body = context.document.body;
                    context.load(body, 'html');
                    console.log(body.getHtml());

                    return context.sync().then(function () {
                        console.log("Content is fetched:", body.getHtml().value);
                    });
                })
                .catch(function(error){
                    // Log additional information, if applicable:
                    if (error instanceof OfficeExtension.Error) {
                        console.log(error.debugInfo);
                    }
                });

在上面的代码中,body.getHtml() 打印了一个对象,其中包含我期望的内容。为了检索该数据,我使用 .value 来获取实际的 HTML 内容,但它给出了以下错误:

There is an error in word data fetch RichApi.Error: "The value of the result object has not been loaded yet. Before reading the value property, call "context.sync()" on the associated request context."

我发出了context.sync(),但是出现同样的错误。有什么帮助吗?

这里的根本问题是你通过方法调用获得 HTML,你不会加载这样的东西,它是隐式的,但你想确保在获取值之前同步 :)

这是它的工作原理检查下面的示例:

Word.run(function (context) {
        var myHTML  = context.document.body.getHtml();
    
        return context.sync()
            .then(function() {
                console.log(myHTML.value);
            });
    });