|
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/25/2024 |
| 4 | +ms.date: 01/29/2025 |
5 | 5 | ms.localizationpriority: medium
|
6 | 6 | ---
|
7 | 7 |
|
@@ -83,6 +83,36 @@ function columnToSet(column: ExcelScript.TableColumn): string[] {
|
83 | 83 | }
|
84 | 84 | ```
|
85 | 85 |
|
| 86 | +### Copy filtered contents to a new worksheet |
| 87 | + |
| 88 | +This sample filters the data in a table and then copies the filtered data to a new worksheet. It uses [`SpecialCellType`](/javascript/api/office-scripts/excelscript/excelscript.specialcelltype) to get the filtered cells in the original table and then uses `Range.copyFrom` to copy the data to the new worksheet. |
| 89 | + |
| 90 | +```TypeScript |
| 91 | +function main(workbook: ExcelScript.Workbook) { |
| 92 | + // Get the table in the workbook named "StationTable". |
| 93 | + const table = workbook.getTable("StationTable"); |
| 94 | + |
| 95 | + // Get the "Station" table column for the filter. |
| 96 | + const stationColumn = table.getColumnByName("Station"); |
| 97 | + |
| 98 | + // Apply a filter to the table that will only show rows |
| 99 | + // with a value of "Station-1" in the "Station" column. |
| 100 | + stationColumn.getFilter().applyValuesFilter(["Station-1"]); |
| 101 | + |
| 102 | + // Get the filtered table data, as visible cells. |
| 103 | + const filteredTable = worksheet.getUsedRange(); |
| 104 | + const visibleRange = filteredTable.getSpecialCells(ExcelScript.SpecialCellType.visible); |
| 105 | + |
| 106 | + // Create a new worksheet for the filtered data. |
| 107 | + const newWorksheet = workbook.addWorksheet(); |
| 108 | + |
| 109 | + // Loop through the filtered data and copy to new worksheet. |
| 110 | + visibleRange.getAreas().forEach(areaRange => { |
| 111 | + newWorksheet.getRange("A1").copyFrom(areaRange); |
| 112 | + }) |
| 113 | +} |
| 114 | +``` |
| 115 | + |
86 | 116 | ## Remove table column filters
|
87 | 117 |
|
88 | 118 | 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