excel - 如何在excel中获取所选范围内每个单元格的地址
问题描述
我正在使用 JavaScript 中的 excel office 插件。在这个加载项中,我需要获取数组中选定范围的每个单元格的单独地址。例如,如果用户选择 M1 到 T31 的范围,我需要数组 = ["M1", "N1", "O1" ... to ... "P31", "Q31", "R31", "S31", "T31 ”]。我的程序代码正在运行,如下所示。你可以看到它await context.sync()
会被执行很多次,这使得这段代码的执行速度很慢。我可以改进这段代码吗?
async function selectDataRange() {
await Excel.run(async (context) => {
// Get selected range
var range = context.workbook.getSelectedRange();
range.load(['rowCount', 'columnCount', 'cellCount']);
await context.sync();
// Get address of each cell
var arrAddress = [];
for (let iRow = 0; iRow < range.rowCount; iRow++) {
for (let iCol = 0; iCol < range.columnCount; iCol++) {
const addOfCell = range.getCell(iRow, iCol)
addOfCell.load('address')
await context.sync();
arrAddress.push(addOfCell.address.slice(addOfCell.address.lastIndexOf('!') + 1));
}
}
}
}
解决方案
您可以使用 Range.getCellProperties API。请尝试以下代码段:
async function run() {
await Excel.run(async (context) => {
// Get selected range
var range = context.workbook.getSelectedRange();
range.load(["rowCount", "columnCount", "cellCount"]);
const propertiesToGet = range.getCellProperties({
address: true
});
await context.sync();
var arrAddress = [];
for (let iRow = 0; iRow < range.rowCount; iRow++) {
for (let iCol = 0; iCol < range.columnCount; iCol++) {
const cellAddress = propertiesToGet.value[iRow][iCol];
arrAddress.push(cellAddress.address.slice(cellAddress.address.lastIndexOf("!") + 1));
}
}
console.log(arrAddress);
});
}
推荐阅读
- python - 嗨,我可以向 Visual Studio 寻求帮助,因为它没有显示结果
- database - 有没有办法从>给定日期备份数据库,然后继续使用从给定日期到现在存在的数据库?谢谢
- oracle - ORACLE Forms (WHEN-BUTTON-PRESSED) 事件问题
- r - 如何在一列中设置一行中某个值以下几列的数据个数?
- java - 向 Mongo db 集合插入多个用户输入值时出现异常
- python - 无法在 PyCharm 中运行子进程
- scala - 是否可以在 OIDC 或 OpenAuth2.0 的身份验证提供程序前面添加代理?
- javascript - 在 JavaScript 中添加命名空间会导致意外的令牌“。” 错误
- html - Django使用对象ID重定向?
- arrays - 如何在 yaml 中使用布尔变量和数组变量?