ms-word - 从 Word 文档中获取所有书签 ID
问题描述
我想扫描整个文档,其中包含样式为标题 1、标题 2、普通文本和几个项目符号/其他文本(基本上是技术报告)的文本。扫描后,我想提取分配给“标题 2”元素的书签,它们也充当报告中的子标题。
getBookmarks()
在 Preview / Beta API 中定义,如果我的光标放在“Heading 2”元素上,它会起作用,如下所示:
async function getBookmarks() {
Word.run(function(context) {
var range = context.document.getSelection();
var bkmrk = range.getBookmarks(true, true);
return context.sync().then(function() {
console.log("The bookmarks read from the document was: " + bkmrk.value);
});
}).catch(function(error) {
console.log("Error: " + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
}
从 API 文档的示例代码中可以看出,我已经设法扫描了整个文档并获得了“样式”属性:
async function getParagraphAll() { await Word.run(async (context) => {
// Gets the complete sentence (as range) associated with the insertion point.
let paragraphs = context.document.body.paragraphs
paragraphs.load("text, style");
await context.sync();
// Expands the range to the end of the paragraph to get all the complete sentences.
let completeParagraph = paragraphs.items[0]
.getRange()
.expandTo(
context.document
.getSelection()
.paragraphs.getFirst()
.getRange("End")
)
paragraphs.load("text, style, hyperlink");
await context.sync();
for (let i = 0; i < paragraphs.items.length; i++) {
console.log(paragraphs.items[i].style);
//let range = paragraphs.items[i].getRange() - Why is this not working ?
//let bkmrk = range.getBookmarks(true, false) - This doesnt get me the bookmark while its in
//the loop scanning the entire document. Is it because it fails on "Normal" style?
// Should I filter out "Normal" and only run "getBookmarks" on "Heading" style ?
console.log(paragraphs.items[i].style);
} }); }
我在预览 API 链接中提供了对库的引用:https ://appsforoffice.microsoft.com/lib/beta/hosted/office.js
我很难理解为什么我可以在光标级别获取书签但是当我想为整个文档获取它时,它只会显示
在加载任何属性之前执行 context.sync() 。不需要负载。
解决方案
推荐阅读
- mysql - SQL 创建视图以计算订单总数
- javascript - 使用 Multer 在 Node.js 中保存使用 Postman 发送的 .wav 文件
- java - 安卓设备或模拟器上的 Files.walkTree 和 File.list()
- c++ - makefile 给了我 collect2: error: 1d returned 1 exit status of other things
- r - 如何计算 R 中每一列数据框的 z 分数?
- split - Cmder 中的 Sublime Text 3 - 如何启动 Sublime 并将终端移动到屏幕的左侧或顶部?
- python - 如何从多个 DataFrame 更新 pandas DataFrame 的计数列?
- java - Hibernate - 如何急切地加载惰性字段?
- r - 当两个特定列总和为零时删除数据帧行
- python - 使用 selenium 和 BeautifulSoap 进行网页抓取