ExcelScript.Table interface

Representa uma tabela do Excel.

Comentários

Exemplos

/**
 * This script creates a table from the current sheet's used range.
 * It then adds a total row to the table with the SUM of the last column.
 */
function main(workbook: ExcelScript.Workbook) {
    // Get the used range of the current worksheet.
    const sheet = workbook.getActiveWorksheet();
    const range = sheet.getUsedRange();

    // Create a table that has headers from that range.
    const table = sheet.addTable(range, true);

    // Have the table display the SUM for the last column.
    table.setShowTotals(true);
    const lastColumn = table.getColumn(table.getColumns().length);
    lastColumn.getTotalRowRange().setFormula(`=SUBTOTAL(109,[${lastColumn.getName()}])`);
}

Métodos

addColumn(index, values, name)

Adiciona uma nova coluna à tabela.

addRow(index, values)

Adiciona uma linha à tabela.

addRows(index, values)

Adiciona uma ou mais linhas à tabela.

clearFilters()

Limpa todos os filtros aplicados à tabela no momento.

convertToRange()

Converte a tabela em um intervalo de células normal. Todos os dados são preservados.

delete()

Exclui a tabela.

deleteRowsAt(index, count)

Exclua um número especificado de linhas em um determinado índice.

getAutoFilter()

Representa o AutoFilter objeto da tabela.

getColumn(key)

Obtém um objeto de coluna por nome ou ID. Se a coluna não existir, esse método retornará undefined.

getColumnById(key)

Obtém um objeto de coluna por ID. Se a coluna não existir, retornará indefinido.

getColumnByName(key)

Obtém um objeto de coluna por Nome. Se a coluna não existir, retornará indefinido.

getColumns()

Representa uma coleção de todas as colunas na tabela.

getHeaderRowRange()

Obtém o objeto de intervalo associado à linha de cabeçalho da tabela.

getHighlightFirstColumn()

Especifica se a primeira coluna contém formatação especial.

getHighlightLastColumn()

Especifica se a última coluna contém formatação especial.

getId()

Retorna um valor que identifica de forma exclusiva a tabela em uma determinada pasta de trabalho. O valor do identificador permanece o mesmo, ainda que a tabela seja renomeada.

getLegacyId()

Retorna uma ID numérica.

getName()

Nome da tabela.

getPredefinedTableStyle()

Valor constante que representa o estilo de tabela. Os valores possíveis são: "TableStyleLight1" por meio de "TableStyleLight21", "TableStyleMedium1" por "TableStyleMedium28", "TableStyleDark1" até "TableStyleDark11". Também é possível usar um estilo definido pelo usuário que esteja presente na planilha.

getRange()

Obtém o objeto de intervalo associado a toda a tabela.

getRangeBetweenHeaderAndTotal()

Obtém o objeto de intervalo associado ao corpo de dados da tabela.

getRowCount()

Obtém a quantidade de linhas na tabela.

getShowBandedColumns()

Especifica se as colunas mostram formatação em banda na qual colunas ímpares são realçadas de forma diferente das até mesmo, para facilitar a leitura da tabela.

getShowBandedRows()

Especifica se as linhas mostram formatação em banda na qual linhas ímpares são realçadas de forma diferente das até mesmo, para facilitar a leitura da tabela.

getShowFilterButton()

Especifica se os botões de filtro estão visíveis na parte superior de cada cabeçalho de coluna. Essa configuração só será permitida se a tabela tiver uma linha de cabeçalho.

getShowHeaders()

Especifica se a linha de cabeçalho está visível. Esse valor pode ser definido para mostrar ou remover a linha do cabeçalho.

getShowTotals()

Especifica se a linha total está visível. Esse valor pode ser definido para mostrar ou remover a linha do total.

getSort()

Representa a classificação da tabela.

getTotalRowRange()

Obtém o objeto de intervalo associado à linha de totais da tabela.

getWorksheet()

A planilha que contém a tabela atual.

reapplyFilters()

Aplica novamente todos os filtros à tabela.

resize(newRange)

Redimensione a tabela para o novo intervalo. O novo intervalo deve se sobrepor ao intervalo de tabela original e os cabeçalhos (ou a parte superior da tabela) devem estar na mesma linha.

setHighlightFirstColumn(highlightFirstColumn)

Especifica se a primeira coluna contém formatação especial.

setHighlightLastColumn(highlightLastColumn)

Especifica se a última coluna contém formatação especial.

setName(name)

Nome da tabela.

setPredefinedTableStyle(predefinedTableStyle)

Valor constante que representa o estilo de tabela. Os valores possíveis são: "TableStyleLight1" por meio de "TableStyleLight21", "TableStyleMedium1" por "TableStyleMedium28", "TableStyleDark1" até "TableStyleDark11". Também é possível usar um estilo definido pelo usuário que esteja presente na planilha.

setShowBandedColumns(showBandedColumns)

Especifica se as colunas mostram formatação em banda na qual colunas ímpares são realçadas de forma diferente das até mesmo, para facilitar a leitura da tabela.

setShowBandedRows(showBandedRows)

Especifica se as linhas mostram formatação em banda na qual linhas ímpares são realçadas de forma diferente das até mesmo, para facilitar a leitura da tabela.

setShowFilterButton(showFilterButton)

Especifica se os botões de filtro estão visíveis na parte superior de cada cabeçalho de coluna. Essa configuração só será permitida se a tabela tiver uma linha de cabeçalho.

setShowHeaders(showHeaders)

Especifica se a linha de cabeçalho está visível. Esse valor pode ser definido para mostrar ou remover a linha do cabeçalho.

setShowTotals(showTotals)

Especifica se a linha total está visível. Esse valor pode ser definido para mostrar ou remover a linha do total.

Detalhes do método

addColumn(index, values, name)

Adiciona uma nova coluna à tabela.

addColumn(
            index?: number,
            values?: (boolean | string | number)[],
            name?: string
        ): TableColumn;

Parâmetros

index

number

Opcional. Especifica a posição relativa da nova coluna. Se for null ou -1, a adição ocorre no final. Colunas com um índice superior serão deslocadas para o lado. Indexado com zero.

values

(boolean | string | number)[]

Opcional. Uma matriz unidimensional de valores não formatados da coluna de tabela.

name

string

Opcional. Especifica o nome da nova coluna. Se for null, o nome padrão será usado.

Retornos

Exemplos

/**
 * This script adds a new column to a table.
 */
function main(workbook: ExcelScript.Workbook) {
  // Get the first table in the workbook.
  const table = workbook.getTables()[0];

  // Append an empty column to the table with the header "Total". 
  table.addColumn(-1, null, "Total");
}

addRow(index, values)

Adiciona uma linha à tabela.

addRow(index?: number, values?: (boolean | string | number)[]): void;

Parâmetros

index

number

Opcional. Especifica a posição relativa da nova linha. Se for null ou -1, a adição ocorre no final. Todas as linhas abaixo da linha inserida serão deslocadas para baixo. Indexado com zero.

values

(boolean | string | number)[]

Opcional. Uma matriz unidimensional de valores não formatados da linha de tabela.

Retornos

void

Exemplos

/**
 * This script adds a row to an existing table.
 */
function main(workbook: ExcelScript.Workbook) {
    // Get the first table in the current worksheet.
    const selectedSheet = workbook.getActiveWorksheet();
    const table = selectedSheet.getTables()[0];

    // Initialize the data to be added as a table row.
    // Note that length of the array must match the number of columns in the table.
    let rowData = ["Carrots", "Vegetable", 750];

    // Add a row to the end of the table.
    table.addRow(-1, rowData);
}

addRows(index, values)

Adiciona uma ou mais linhas à tabela.

addRows(index?: number, values?: (boolean | string | number)[][]): void;

Parâmetros

index

number

Opcional. Especifica a posição relativa da nova linha. Se for null ou -1, a adição ocorre no final. Todas as linhas abaixo da linha inserida serão deslocadas para baixo. Indexado com zero.

values

(boolean | string | number)[][]

Opcional. Uma matriz bidimensional de valores não formatados da linha da tabela.

Retornos

void

Exemplos

/**
 * This script adds multiple rows to an existing table.
 */
function main(workbook: ExcelScript.Workbook) {
    // Get the first table in the current worksheet.
    const selectedSheet = workbook.getActiveWorksheet();
    const table = selectedSheet.getTables()[0];

    // Initialize the data to be added as table rows.
    // Note that length of the array must match the number of columns in the table.
    let rowData = [["Apples", "Fruit", 5000],
                  ["Celery", "Vegetable", 600],
                  ["Onions", "Vegetable", 1500]];

    // Add the rows to the end of the table.
    table.addRows(-1, rowData);
}

clearFilters()

Limpa todos os filtros aplicados à tabela no momento.

clearFilters(): void;

Retornos

void

convertToRange()

Converte a tabela em um intervalo de células normal. Todos os dados são preservados.

convertToRange(): Range;

Retornos

Exemplos

/**
 * This script converts a table to a range and removes the formatting.
 */
function main(workbook: ExcelScript.Workbook) {
    // Get the first table in the current worksheet.
    const selectedSheet = workbook.getActiveWorksheet();
    const table = selectedSheet.getTables()[0];

    // Convert the table to a range.
    const formerTable = table.convertToRange();

    // Remove the formatting from the table
    formerTable.clear(ExcelScript.ClearApplyTo.formats);
}

delete()

Exclui a tabela.

delete(): void;

Retornos

void

Exemplos

/**
 * This script deletes a table. 
 * This removes all associated data and formatting.
 */
function main(workbook: ExcelScript.Workbook) {
    // Get the table named "Inventory".
    const table = workbook.getTable("Inventory");

    // Delete the table.
    table.delete();
}

deleteRowsAt(index, count)

Exclua um número especificado de linhas em um determinado índice.

deleteRowsAt(index: number, count?: number): void;

Parâmetros

index

number

O valor do índice da linha a ser excluída. Cuidado: o índice da linha pode ter se movido do momento em que você determinou o valor a ser usado para remoção.

count

number

Número de linhas a serem excluídas. Por padrão, uma única linha será excluída. Observação: excluir mais de 1000 linhas ao mesmo tempo pode resultar em um tempo limite do Power Automate.

Retornos

void

getAutoFilter()

Representa o AutoFilter objeto da tabela.

getAutoFilter(): AutoFilter;

Retornos

getColumn(key)

Obtém um objeto de coluna por nome ou ID. Se a coluna não existir, esse método retornará undefined.

getColumn(key: number | string): TableColumn | undefined;

Parâmetros

key

number | string

Nome da coluna ou ID.

Retornos

Exemplos

/**
 * This script adjusts the indentation of a specific table column.
 */
function main(workbook: ExcelScript.Workbook) {
  // Get the first table in the current worksheet.
  const selectedSheet = workbook.getActiveWorksheet();
  const table = selectedSheet.getTables()[0];

  // Get the data range of the second column.
  const secondColumn = table.getColumn(2);
  const data = secondColumn.getRangeBetweenHeaderAndTotal();

  // Add an indentation of 1 character space to the data range.
  data.getFormat().adjustIndent(1);
}

getColumnById(key)

Obtém um objeto de coluna por ID. Se a coluna não existir, retornará indefinido.

getColumnById(key: number): TableColumn | undefined;

Parâmetros

key

number

ID da coluna.

Retornos

getColumnByName(key)

Obtém um objeto de coluna por Nome. Se a coluna não existir, retornará indefinido.

getColumnByName(key: string): TableColumn | undefined;

Parâmetros

key

string

Nome da coluna.

Retornos

Exemplos

/**
 * This script removes a specific column from a table.
 */
function main(workbook: ExcelScript.Workbook) {
    // Get the table named "Inventory".
    const table = workbook.getTable("Inventory");

    // If it exists, remove the column named "Category".
    let categoryColumn = table.getColumnByName("Category");
    if (categoryColumn) {
        categoryColumn.delete();
    }
}

getColumns()

Representa uma coleção de todas as colunas na tabela.

getColumns(): TableColumn[];

Retornos

Exemplos

/**
 * This script adds a new column to a table.
 * It then sets the formulas in the new column to be the product
 * of the values in the two preceding columns.
 */
function main(workbook: ExcelScript.Workbook) {
  // Get the first table in the workbook.
  const table = workbook.getTables()[0];

  // Append an empty column to the table with the header "Total". 
  const totalColumn = table.addColumn(-1, null, "Total");

  // Get the names of the two preceding columns.
  const productColumnName1 = table.getColumns()[totalColumn.getIndex() - 1].getName();
  const productColumnName2 = table.getColumns()[totalColumn.getIndex() - 2].getName();
  
  // Set the formulas in the "Total" column to be the product of the two preceding columns.
  totalColumn.getRangeBetweenHeaderAndTotal().setFormula(
    `=[@[${productColumnName1}]]*[@[${productColumnName2}]]`
  );
}

getHeaderRowRange()

Obtém o objeto de intervalo associado à linha de cabeçalho da tabela.

getHeaderRowRange(): Range;

Retornos

Exemplos

/**
 * This script centers the text in a table's header row cells.
 */
function main(workbook: ExcelScript.Workbook) {
  // Get the first table on the current worksheet.
  const currentSheet = workbook.getActiveWorksheet();
  const table = currentSheet.getTables()[0];

  // Get the header range.
  const headerRange = table.getHeaderRowRange();

  // Set the horizontal text alignment to `center`.
  headerRange.getFormat().setHorizontalAlignment(ExcelScript.HorizontalAlignment.center);
}

getHighlightFirstColumn()

Especifica se a primeira coluna contém formatação especial.

getHighlightFirstColumn(): boolean;

Retornos

boolean

getHighlightLastColumn()

Especifica se a última coluna contém formatação especial.

getHighlightLastColumn(): boolean;

Retornos

boolean

getId()

Retorna um valor que identifica de forma exclusiva a tabela em uma determinada pasta de trabalho. O valor do identificador permanece o mesmo, ainda que a tabela seja renomeada.

getId(): string;

Retornos

string

getLegacyId()

Retorna uma ID numérica.

getLegacyId(): string;

Retornos

string

getName()

Nome da tabela.

getName(): string;

Retornos

string

getPredefinedTableStyle()

Valor constante que representa o estilo de tabela. Os valores possíveis são: "TableStyleLight1" por meio de "TableStyleLight21", "TableStyleMedium1" por "TableStyleMedium28", "TableStyleDark1" até "TableStyleDark11". Também é possível usar um estilo definido pelo usuário que esteja presente na planilha.

getPredefinedTableStyle(): string;

Retornos

string

getRange()

Obtém o objeto de intervalo associado a toda a tabela.

getRange(): Range;

Retornos

Exemplos

/**
 * This script removes any extra formatting that's been applied to a table. 
 * This leaves only the base table style effects.
 * Any formatting outside of the table will be left as is.
 */
function main(workbook: ExcelScript.Workbook) {
  // Get the first table on the current worksheet.
  let worksheet = workbook.getActiveWorksheet();
  let table = worksheet.getTables()[0];

  // Get the range used by the table.
  let range = table.getRange();

  // Clear all the formatting that is not applied by the table and the table style.
  range.clear(ExcelScript.ClearApplyTo.formats);
}

getRangeBetweenHeaderAndTotal()

Obtém o objeto de intervalo associado ao corpo de dados da tabela.

getRangeBetweenHeaderAndTotal(): Range;

Retornos

getRowCount()

Obtém a quantidade de linhas na tabela.

getRowCount(): number;

Retornos

number

getShowBandedColumns()

Especifica se as colunas mostram formatação em banda na qual colunas ímpares são realçadas de forma diferente das até mesmo, para facilitar a leitura da tabela.

getShowBandedColumns(): boolean;

Retornos

boolean

getShowBandedRows()

Especifica se as linhas mostram formatação em banda na qual linhas ímpares são realçadas de forma diferente das até mesmo, para facilitar a leitura da tabela.

getShowBandedRows(): boolean;

Retornos

boolean

getShowFilterButton()

Especifica se os botões de filtro estão visíveis na parte superior de cada cabeçalho de coluna. Essa configuração só será permitida se a tabela tiver uma linha de cabeçalho.

getShowFilterButton(): boolean;

Retornos

boolean

getShowHeaders()

Especifica se a linha de cabeçalho está visível. Esse valor pode ser definido para mostrar ou remover a linha do cabeçalho.

getShowHeaders(): boolean;

Retornos

boolean

getShowTotals()

Especifica se a linha total está visível. Esse valor pode ser definido para mostrar ou remover a linha do total.

getShowTotals(): boolean;

Retornos

boolean

getSort()

Representa a classificação da tabela.

getSort(): TableSort;

Retornos

getTotalRowRange()

Obtém o objeto de intervalo associado à linha de totais da tabela.

getTotalRowRange(): Range;

Retornos

getWorksheet()

A planilha que contém a tabela atual.

getWorksheet(): Worksheet;

Retornos

reapplyFilters()

Aplica novamente todos os filtros à tabela.

reapplyFilters(): void;

Retornos

void

Exemplos

/**
 * This script reapplies the filters on every table in the workbook.
 */
function main(workbook: ExcelScript.Workbook) {
  // Get all the tables.
  const tables = workbook.getTables();

  // Iterate over every table.
  tables.forEach((table) => {
    // Reapply the filters to account for new table entries.
    table.reapplyFilters();
  });
}

resize(newRange)

Redimensione a tabela para o novo intervalo. O novo intervalo deve se sobrepor ao intervalo de tabela original e os cabeçalhos (ou a parte superior da tabela) devem estar na mesma linha.

resize(newRange: Range | string): void;

Parâmetros

newRange

ExcelScript.Range | string

O objeto de intervalo ou o endereço de intervalo que será usado para determinar o novo tamanho da tabela.

Retornos

void

setHighlightFirstColumn(highlightFirstColumn)

Especifica se a primeira coluna contém formatação especial.

setHighlightFirstColumn(highlightFirstColumn: boolean): void;

Parâmetros

highlightFirstColumn

boolean

Retornos

void

setHighlightLastColumn(highlightLastColumn)

Especifica se a última coluna contém formatação especial.

setHighlightLastColumn(highlightLastColumn: boolean): void;

Parâmetros

highlightLastColumn

boolean

Retornos

void

setName(name)

Nome da tabela.

setName(name: string): void;

Parâmetros

name

string

Retornos

void

setPredefinedTableStyle(predefinedTableStyle)

Valor constante que representa o estilo de tabela. Os valores possíveis são: "TableStyleLight1" por meio de "TableStyleLight21", "TableStyleMedium1" por "TableStyleMedium28", "TableStyleDark1" até "TableStyleDark11". Também é possível usar um estilo definido pelo usuário que esteja presente na planilha.

setPredefinedTableStyle(predefinedTableStyle: string): void;

Parâmetros

predefinedTableStyle

string

Retornos

void

setShowBandedColumns(showBandedColumns)

Especifica se as colunas mostram formatação em banda na qual colunas ímpares são realçadas de forma diferente das até mesmo, para facilitar a leitura da tabela.

setShowBandedColumns(showBandedColumns: boolean): void;

Parâmetros

showBandedColumns

boolean

Retornos

void

setShowBandedRows(showBandedRows)

Especifica se as linhas mostram formatação em banda na qual linhas ímpares são realçadas de forma diferente das até mesmo, para facilitar a leitura da tabela.

setShowBandedRows(showBandedRows: boolean): void;

Parâmetros

showBandedRows

boolean

Retornos

void

setShowFilterButton(showFilterButton)

Especifica se os botões de filtro estão visíveis na parte superior de cada cabeçalho de coluna. Essa configuração só será permitida se a tabela tiver uma linha de cabeçalho.

setShowFilterButton(showFilterButton: boolean): void;

Parâmetros

showFilterButton

boolean

Retornos

void

setShowHeaders(showHeaders)

Especifica se a linha de cabeçalho está visível. Esse valor pode ser definido para mostrar ou remover a linha do cabeçalho.

setShowHeaders(showHeaders: boolean): void;

Parâmetros

showHeaders

boolean

Retornos

void

Exemplos

/**
 * This script makes a table's headers not visible in the grid.
 */
function main(workbook: ExcelScript.Workbook) {
    // Get the table named "CoverageTable".
    const coverageTable = workbook.getTable("CoverageTable");

    // Make the header row not visible.
    coverageTable.setShowHeaders(false);
}

setShowTotals(showTotals)

Especifica se a linha total está visível. Esse valor pode ser definido para mostrar ou remover a linha do total.

setShowTotals(showTotals: boolean): void;

Parâmetros

showTotals

boolean

Retornos

void

Exemplos

/**
 * This script adds the Total Row to an existing table.
 */
function main(workbook: ExcelScript.Workbook) {
    // Get the first table in the current worksheet.
    const selectedSheet = workbook.getActiveWorksheet();
    const table = selectedSheet.getTables()[0];

    // Set the Total Row to show.
    table.setShowTotals(true);
}