|
1 | 1 | ---
|
2 | 2 | title: Table samples
|
3 | 3 | description: A collection of samples showing how to interact with Excel tables.
|
4 |
| -ms.date: 09/08/2023 |
| 4 | +ms.date: 10/30/2023 |
5 | 5 | ms.localizationpriority: medium
|
6 | 6 | ---
|
7 | 7 |
|
@@ -52,6 +52,44 @@ function main(workbook: ExcelScript.Workbook) {
|
52 | 52 | > workbook.addWorksheet().getRange("A1").copyFrom(table.getRange());
|
53 | 53 | > ```
|
54 | 54 |
|
| 55 | +### Filter out one value |
| 56 | +
|
| 57 | +The previous sample filters a table based on a list of included values. To exclude a particular value from the table, you need to provide the list of every other value in the column. This sample uses a function `columnToSet` to convert a column into a set of unique values. That set then has the excluded value ("Station-1") removed. |
| 58 | +
|
| 59 | +```TypeScript |
| 60 | +function main(workbook: ExcelScript.Workbook) { |
| 61 | + // Get the table in the workbook named "StationTable". |
| 62 | + const table = workbook.getTable("StationTable"); |
| 63 | +
|
| 64 | + // Get the "Station" table column for the filter. |
| 65 | + const stationColumn = table.getColumnByName("Station"); |
| 66 | +
|
| 67 | + // Get a list of unique values in the station column. |
| 68 | + const stationSet = columnToSet(stationColumn); |
| 69 | +
|
| 70 | + // Apply a filter to the table that will only show rows |
| 71 | + // that don't have a value of "Station-1" in the "Station" column. |
| 72 | + stationColumn.getFilter().applyValuesFilter(stationSet.filter((value) => { |
| 73 | + return value !== "Station-1"; |
| 74 | + })); |
| 75 | +} |
| 76 | +
|
| 77 | +/** |
| 78 | + * Convert a column into a set so it only contains unique values. |
| 79 | + */ |
| 80 | +function columnToSet(column: ExcelScript.TableColumn): string[] { |
| 81 | + const range = column.getRangeBetweenHeaderAndTotal().getValues() as string[][]; |
| 82 | + const columnSet: string[] = []; |
| 83 | + range.forEach((value) => { |
| 84 | + if (!columnSet.includes(value[0])) { |
| 85 | + columnSet.push(value[0]); |
| 86 | + } |
| 87 | + }); |
| 88 | +
|
| 89 | + return columnSet; |
| 90 | +} |
| 91 | +``` |
| 92 | +
|
55 | 93 | ## Remove table column filters
|
56 | 94 |
|
57 | 95 | This sample removes the filters from a table column, based on the active cell location. The script detects if the cell is part of a table, determines the table column, and clears any filters that are applied on it.
|
|
0 commit comments