获取内容
场景说明
获取表格单元格的内容,支持通过书签定位单元格,并提供处理合并单元格的解决方案。
适用场景:
- 单元格内容读取
- 数据提取和分析
- 表格内容遍历
相关 API 文档
示例代码
通过表格中的书签获取单元格内容
适用场景:当书签位于表格单元格内时,通过
Range.information()获取书签所在的行列号(用户视角,已处理合并单元格),然后配合getCellByVisibleIndex()辅助方法获取该单元格的内容。
主要方法
async function getCellContentByBookmark() {
// 前提条件:书签必须在表格单元格内
// 获取书签位置
const bookmark = await Application.ActiveDocument.Bookmarks.item('myBookmark');
const range = await bookmark.range;
// 通过 information 获取书签所在的行列(合并后的视角,用户实际看到的)
const rowNumber = await range.information(Word.WdInformation.wdEndOfRangeRowNumber);
const colNumber = await range.information(Word.WdInformation.wdEndOfRangeColumnNumber);
console.log(`书签位置在第 ${rowNumber} 行,第 ${colNumber} 列`);
// 获取表格
const table = await Application.ActiveDocument.Tables.item(1);
const row = await table.Rows.item(rowNumber);
// 使用辅助方法获取单元格内容(统一 information 和 Cells.item 的维度)
// 注意:若当前获取的单元格为被合并的单元格,则返回 undefined
const cell = await getCellByVisibleIndex(row, colNumber);
if (cell) {
const cellRange = await cell.range;
const text = await cellRange.text;
console.log(`单元格内容: ${text}`);
} else {
console.log('未找到单元格(可能是被合并的单元格)');
}
}
辅助方法:统一 information 和 Cells.item 的维度
该方法用于解决 Range.information() 返回合并后的列号,而 Cells.item() 返回合并前的单元格这一维度不一致的问题。
async function getCellByVisibleIndex(row, visibleIndex) {
// 获取行中的单元格总数(包括被合并的单元格)
const cellCount = await row.Cells.count;
let visibleNum = 1; // 可见单元格序号(用户视角,与 information 返回的列号对应)
// 遍历所有单元格
for (let i = 1; i <= cellCount; i++) {
const currentCell = await row.Cells.item(i);
// 只计数非 undefined 的单元格(被合并的单元格为 undefined)
if (currentCell) {
if (visibleNum === visibleIndex) {
return currentCell;
}
visibleNum += 1;
}
}
return null;
}
注意事项
- 前提条件:书签必须在表格单元格内,此方法才能正确获取单元格内容
- 关键差异:
Range.information()获取的是合并后的行列号(用户视角),而Cells.item()获取的是合并前的实际单元格(被合并的单元格返回undefined) - 解决方案:使用
getCellByVisibleIndex()辅助方法配合information使用,统一两个 API 的维度差异