首页 > 解决方案 > 如何在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));
      }
    }
  }
}

标签: exceloffice-jsexcel-addins

解决方案


您可以使用 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);
  });
}

推荐阅读