如何获取 excel 中选定范围内每个单元格的地址

How to get address of each individual cells of selected range in 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);
  });
}