表示例

这些示例展示了与 Excel 表的常见交互。

创建排序表

此示例从当前工作表的已用区域创建一个表,然后根据第一列对其进行排序。

function main(workbook: ExcelScript.Workbook) {
  // Get the current worksheet.
  const selectedSheet = workbook.getActiveWorksheet();

  // Create a table with the used cells.
  const usedRange = selectedSheet.getUsedRange();
  const newTable = selectedSheet.addTable(usedRange, true);

  // Sort the table using the first column.
  newTable.getSort().apply([{ key: 0, ascending: true }]);
}

筛选表

此示例使用其中一列中的值筛选现有表。

function main(workbook: ExcelScript.Workbook) {
  // Get the table in the workbook named "StationTable".
  const table = workbook.getTable("StationTable");

  // Get the "Station" table column for the filter.
  const stationColumn = table.getColumnByName("Station");

  // Apply a filter to the table that will only show rows 
  // with a value of "Station-1" in the "Station" column.
  stationColumn.getFilter().applyValuesFilter(["Station-1"]);
}

提示

使用 Range.copyFrom在工作簿中复制筛选的信息。 将以下行添加到脚本的末尾,以使用筛选的数据创建一个新工作表。

  workbook.addWorksheet().getRange("A1").copyFrom(table.getRange());

筛选出一个值

前面的示例基于包含值的列表筛选表。 若要从表中排除特定值,需要提供列中所有其他值的列表。 此示例使用 函数 columnToSet 将列转换为一组唯一值。 然后,该集具有排除的值 (“Station-1”) 删除。

function main(workbook: ExcelScript.Workbook) {
  // Get the table in the workbook named "StationTable".
  const table = workbook.getTable("StationTable");

  // Get the "Station" table column for the filter.
  const stationColumn = table.getColumnByName("Station");

  // Get a list of unique values in the station column.
  const stationSet = columnToSet(stationColumn);

  // Apply a filter to the table that will only show rows
  // that don't have a value of "Station-1" in the "Station" column. 
  stationColumn.getFilter().applyValuesFilter(stationSet.filter((value) => {
      return value !== "Station-1";
  }));
}

/**
 * Convert a column into a set so it only contains unique values.
 */
function columnToSet(column: ExcelScript.TableColumn): string[] {
    const range = column.getRangeBetweenHeaderAndTotal().getValues() as string[][];
    const columnSet: string[] = [];
    range.forEach((value) => {
        if (!columnSet.includes(value[0])) {
            columnSet.push(value[0]);
        }
    });

    return columnSet;
}

删除表格列筛选器

此示例基于活动单元格位置从表列中删除筛选器。 该脚本检测单元格是否是表的一部分,确定表列,并清除对其应用的所有筛选器。

下载可供使用工作簿 的table-with-filter.xlsx 。 添加以下脚本以亲自试用示例!

function main(workbook: ExcelScript.Workbook) {
  // Get the active cell.
  const cell = workbook.getActiveCell();

  // Get the tables associated with that cell.
  // Since tables can't overlap, this will be one table at most.
  const currentTable = cell.getTables()[0];

  // If there's no table on the selection, end the script.
  if (!currentTable) {
    console.log("The selection is not in a table.");
    return;
  }

  // Get the table header above the current cell by referencing its column.
  const entireColumn = cell.getEntireColumn();
  const intersect = entireColumn.getIntersection(currentTable.getRange());
  const headerCellValue = intersect.getCell(0, 0).getValue() as string;

  // Get the TableColumn object matching that header.
  const tableColumn = currentTable.getColumnByName(headerCellValue);

  // Clear the filters on that table column.
  tableColumn.getFilter().clear();
}

在清除列筛选器之前, (请注意活动单元格)

清除列筛选器之前的活动单元格。

清除列筛选器后

清除列筛选器后的活动单元格。

提示

如果想要详细了解如何在清除筛选器之前保存筛选器 (并在以后) 重新应用,请参阅 通过保存筛选器跨表移动行,这是一个更高级的示例。

动态引用表值

此脚本使用“@COLUMN_NAME”语法在表列中设置公式。 无需更改此脚本即可更改表中的列名称。

function main(workbook: ExcelScript.Workbook) {
  // Get the current worksheet.
  const table = workbook.getTable("Profits");

  // Get the column names for columns 2 and 3.
  // Note that these are 1-based indices.
  const nameOfColumn2 = table.getColumn(2).getName();
  const nameOfColumn3 = table.getColumn(3).getName();

  // Set the formula of the fourth column to be the product of the values found
  // in that row's second and third columns.
  const combinedColumn = table.getColumn(4).getRangeBetweenHeaderAndTotal();
  combinedColumn.setFormula(`=[@[${nameOfColumn2}]]*[@[${nameOfColumn3}]]`);
}

在脚本之前

价格 销售单位 总计
1 月 45 5
2 月 45 3
三月 45 6

脚本之后

价格 销售单位 总计
1 月 45 5 225
2 月 45 3 135
三月 45 6 270