【问题标题】:How to get address of each individual cells of selected range in excel如何在excel中获取所选范围内每个单元格的地址
【发布时间】:2021-07-26 16:11:40
【问题描述】:

我正在使用 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));
      }
    }
  }
}

【问题讨论】:

    标签: excel office-js excel-addins


    【解决方案1】:

    您可以使用 Range.getCellProperties API。请尝试以下 sn-p 代码:

    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);
      });
    }
    

    【讨论】:

    • 在哪里可以找到 range.getCellProperties 的文档?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    相关资源
    最近更新 更多