如何用Office JS获取Word文档每个段落的HTML
How to get HTML of each paragraph of a Word document with Office JS
我有 MS Word 文档,其中 table 的内容是使用标题 1 到标题 4 构建的,是一个包含 100 多个项目的层次结构。
我想使用 Office JS 开发一个 add-in 以将这些文档作为一组页面导入 WordPress,这些页面与 table 内容之一具有相同的层次结构。
每个 WP 页面将包含每个标题级别下包含的所有段落的 HTML。
查看 Office JS 示例,我已经能够将文档中所有段落的大纲级别记录到控制台,但我无法获取 HTML。
我觉得这可能是我理解错了context.sync()
.
这是我的代码:
$("#exportToCMS").click(() => tryCatch(exportToCMS));
function exportToCMS() {
return Word.run(function (context) {
// Create a proxy object for the paragraphs collection
var paragraphs = context.document.body.paragraphs;
// Queue a command to load the outline level property for all of the paragraphs
paragraphs.load("outlineLevel");
return context.sync().then(function () {
// Queue a a set of commands to get the HTML of each paragraph.
paragraphs.items.forEach((paragraph) => {
// Queue a command to get the HTML of the paragraph.
var ooxml = paragraph.getOoxml();
return context.sync().then(function () {
console.log(ooxml.value);
console.log(paragraph.outlineLevel);
});
});
});
});
}
/** Default helper for invoking an action and handling errors. */
function tryCatch(callback) {
Promise.resolve()
.then(callback)
.catch(function (error) {
console.error(error);
});
}
如果我注释掉记录 ooxml.value
的行,脚本运行正常。
取消注释时,我收到错误“未处理的承诺拒绝”。
当循环中有 context.sync
时,承诺链损坏很常见。从性能的角度来看,这也很糟糕。修复代码的第一步是按照本文中的指导将 context.sync
从 forEach
循环中移除:Avoid using the context.sync method in loops.
我有 MS Word 文档,其中 table 的内容是使用标题 1 到标题 4 构建的,是一个包含 100 多个项目的层次结构。
我想使用 Office JS 开发一个 add-in 以将这些文档作为一组页面导入 WordPress,这些页面与 table 内容之一具有相同的层次结构。
每个 WP 页面将包含每个标题级别下包含的所有段落的 HTML。
查看 Office JS 示例,我已经能够将文档中所有段落的大纲级别记录到控制台,但我无法获取 HTML。
我觉得这可能是我理解错了context.sync()
.
这是我的代码:
$("#exportToCMS").click(() => tryCatch(exportToCMS));
function exportToCMS() {
return Word.run(function (context) {
// Create a proxy object for the paragraphs collection
var paragraphs = context.document.body.paragraphs;
// Queue a command to load the outline level property for all of the paragraphs
paragraphs.load("outlineLevel");
return context.sync().then(function () {
// Queue a a set of commands to get the HTML of each paragraph.
paragraphs.items.forEach((paragraph) => {
// Queue a command to get the HTML of the paragraph.
var ooxml = paragraph.getOoxml();
return context.sync().then(function () {
console.log(ooxml.value);
console.log(paragraph.outlineLevel);
});
});
});
});
}
/** Default helper for invoking an action and handling errors. */
function tryCatch(callback) {
Promise.resolve()
.then(callback)
.catch(function (error) {
console.error(error);
});
}
如果我注释掉记录 ooxml.value
的行,脚本运行正常。
取消注释时,我收到错误“未处理的承诺拒绝”。
当循环中有 context.sync
时,承诺链损坏很常见。从性能的角度来看,这也很糟糕。修复代码的第一步是按照本文中的指导将 context.sync
从 forEach
循环中移除:Avoid using the context.sync method in loops.