Skip to content

Commit 64a1ad9

Browse files
authored
[excel] (Table) Add sample for copying filtered table to new worksheet (#776)
* [excel] (Table) Add sample for copying filtered table to new worksheet * Add missing code ticks * Get table header * Remove unnecessary header lines * Address build suggestion * Remove unnecessary line, change let to const * Change from let to const
1 parent df038ed commit 64a1ad9

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

docs/resources/samples/table-samples.md

+31-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Table samples
33
description: A collection of samples showing how to interact with Excel tables.
4-
ms.date: 09/25/2024
4+
ms.date: 01/29/2025
55
ms.localizationpriority: medium
66
---
77

@@ -83,6 +83,36 @@ function columnToSet(column: ExcelScript.TableColumn): string[] {
8383
}
8484
```
8585

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+
86116
## Remove table column filters
87117

88118
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

Comments
 (0)