首页 > 解决方案 > excel office JS中是否有在所选表格列旁边插入表格列的功能?

问题描述

我试图通过office JS模仿excel本身提供的以下功能,我可以在excel中选择一个表格列并在左侧插入一个新列:

在左侧添加表格列

我知道我可以Excel.TableColumnCollection.add(index, values, name)使用 index 参数通过 Method 插入列:

index
number
Optional. Specifies the relative position of the new column. 
If null or -1, the addition happens at the end. 
Columns with a higher index will be shifted to the side. Zero-indexed.

但是如何在表格中找到所选列的索引?我知道如何获取选定的范围,但不知道表的选定列索引。

提前感谢您的帮助。

标签: office-js

解决方案


您可以通过 getItem() 获取列对象,并且您可以从列对象获取索引。

这是示例代码,它将在您选择的列标题的左侧插入列

  await Excel.run(async (context) => {
    const sheet = context.workbook.worksheets.getItem("Sample");
    const expensesTable = sheet.tables.getItem("ExpensesTable");
    var range = context.workbook.getSelectedRange();
    range.load("values");
    await context.sync();
    var colname = range.values[0][0];
    var col = expensesTable.columns.getItem(colname);
    col.load("index");
    await context.sync();
    
    expensesTable.columns.add(col.index, [
      ["Deductable?"],
      ["Yes"],
      ["Yes"],
      ["No"],
      ["No"],
      ["Yes"],
      ["Yes"],
      ["No"],
      ["Yes"],
      ["Yes"],
      ["No"]
    ]);

    sheet.getUsedRange().format.autofitColumns();
    sheet.getUsedRange().format.autofitRows();

    await context.sync();
  });

推荐阅读