如何在Office JS中获取Word文档插入的脚注编号?
高效获取Office JS中脚注编号的方案
单脚注场景:直接读取引用Range的文本
Word.NoteItem对象的reference属性对应文档里显示的上标编号所在的Range,直接加载该Range的text属性就能拿到编号,完全不用遍历所有脚注:
await Word.run(async (context) => { // 创建新脚注 const newFootnote = context.document.body.insertFootnote(Word.FootnoteLocation.end, "示例脚注内容"); // 加载脚注引用Range的文本内容 newFootnote.reference.load("text"); await context.sync(); // 输出脚注编号 console.log(newFootnote.reference.text); });
多脚注批量处理:一次性加载属性
如果要处理文档中所有脚注,别逐个同步拖慢性能,直接批量加载所有脚注的reference.text属性,仅需一次同步操作:
await Word.run(async (context) => { const allFootnotes = context.document.body.footnotes; // 批量加载所有脚注的引用文本 allFootnotes.load("items/reference/text"); await context.sync(); // 遍历获取每个脚注的编号 allFootnotes.items.forEach(footnote => { console.log(`脚注编号:${footnote.reference.text}`); }); });
备用方案:解析引用Range的OOXML
如果遇到自定义脚注编号格式导致上述方法失效的情况,可以解析脚注引用Range的OOXML提取编号:
await Word.run(async (context) => { const footnote = context.document.body.insertFootnote(Word.FootnoteLocation.end, "自定义编号脚注"); footnote.reference.load("ooxml"); await context.sync(); // 用正则匹配OOXML中的编号文本 const numberMatch = footnote.reference.ooxml.match(/<w:t>(\d+)<\/w:t>/); if (numberMatch) { console.log(`脚注编号:${numberMatch[1]}`); } });
内容的提问来源于stack exchange,提问作者Peter Henry
相关产品推荐
相关产品推荐

