Skip to content

Commit 8ebb0a8

Browse files
authored
Extract code snippets from how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md (#294)
1 parent 80dda58 commit 8ebb0a8

File tree

3 files changed

+72
-218
lines changed

3 files changed

+72
-218
lines changed

docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md

Lines changed: 17 additions & 188 deletions
Original file line numberDiff line numberDiff line change
@@ -17,247 +17,76 @@ ms.localizationpriority: high
1717
---
1818
# Retrieve a list of the hidden rows or columns in a spreadsheet document
1919

20-
This topic shows how to use the classes in the Open XML SDK for Office to programmatically retrieve a list of hidden rows or columns in a Microsoft Excel 2010 or Microsoft Excel 2013 worksheet, without
21-
loading the document into Excel. It contains an example **GetHiddenRowsOrCols** method to illustrate this task.
20+
This topic shows how to use the classes in the Open XML SDK for Office to programmatically retrieve a list of hidden rows or columns in a Microsoft Excel worksheet. It contains an example **GetHiddenRowsOrCols** method to illustrate this task.
2221

2322

2423

2524
---------------------------------------------------------------------------------
2625

2726
## GetHiddenRowsOrCols Method
2827

29-
You can use the **GetHiddenRowsOrCols** method
30-
to retrieve a list of the hidden rows or columns in a worksheet. The
31-
**GetHiddenRowsOrCols** method accepts three
32-
parameters, indicating the following:
28+
You can use the **GetHiddenRowsOrCols** method to retrieve a list of the hidden rows or columns in a worksheet. The method returns a list of unsigned integers that contain each index for the hidden rows or columns, if the specified worksheet contains any hidden rows or columns (rows and columns are numbered starting at 1, rather than 0). The **GetHiddenRowsOrCols** method accepts three parameters:
3329

3430
- The name of the document to examine (string).
3531

3632
- The name of the sheet to examine (string).
3733

3834
- Whether to detect rows (true) or columns (false) (Boolean).
3935

40-
### [C#](#tab/cs-0)
41-
```csharp
42-
public static List<uint> GetHiddenRowsOrCols(
43-
string fileName, string sheetName, bool detectRows)
44-
```
45-
46-
### [Visual Basic](#tab/vb-0)
47-
```vb
48-
Public Function GetHiddenRowsOrCols(
49-
ByVal fileName As String, ByVal sheetName As String,
50-
ByVal detectRows As Boolean) As List(Of UInteger)
51-
```
52-
***
53-
54-
55-
---------------------------------------------------------------------------------
56-
57-
## Calling the GetHiddenRowsOrCols Method
58-
59-
The method returns a list of unsigned integers that contain each index for the hidden rows or columns, if the specified worksheet contains any hidden rows or columns (rows and columns are numbered starting at 1, rather than 0.) To call the method, pass all the parameter values, as shown in the following example code.
60-
61-
### [C#](#tab/cs-1)
62-
```csharp
63-
const string fileName = @"C:\users\public\documents\RetrieveHiddenRowsCols.xlsx";
64-
List<uint> items = GetHiddenRowsOrCols(fileName, "Sheet1", true);
65-
var sw = new StringWriter();
66-
foreach (var item in items)
67-
sw.WriteLine(item);
68-
Console.WriteLine(sw.ToString());
69-
```
70-
71-
### [Visual Basic](#tab/vb-1)
72-
```vb
73-
Const fileName As String = "C:\Users\Public\Documents\RetrieveHiddenRowsCols.xlsx"
74-
Dim items As List(Of UInteger) =
75-
GetHiddenRowsOrCols(fileName, "Sheet1", True)
76-
Dim sw As New StringWriter
77-
For Each item In items
78-
sw.WriteLine(item)
79-
Next
80-
Console.WriteLine(sw.ToString())
81-
```
82-
***
83-
84-
8536
---------------------------------------------------------------------------------
8637

8738
## How the Code Works
8839

89-
The code starts by creating a variable, **itemList**, that will contain the return value.
90-
91-
### [C#](#tab/cs-2)
92-
```csharp
93-
List<uint> itemList = new List<uint>();
94-
```
95-
96-
### [Visual Basic](#tab/vb-2)
97-
```vb
98-
Dim itemList As New List(Of UInteger)
99-
```
100-
***
101-
102-
103-
Next, the code opens the document, by using the [SpreadsheetDocument.Open](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.open.aspx) method and indicating that the document should be open for read-only access (the final **false** parameter value). Next the code retrieves a reference to the workbook part, by using the [WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.workbookpart.aspx) property of the document.
40+
The code opens the document, by using the [SpreadsheetDocument.Open](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.open.aspx) method and indicating that the document should be open for read-only access (the final **false** parameter value). Next the code retrieves a reference to the workbook part, by using the [WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.workbookpart.aspx) property of the document.
10441

10542
### [C#](#tab/cs-3)
106-
```csharp
107-
using (SpreadsheetDocument document =
108-
SpreadsheetDocument.Open(fileName, false))
109-
{
110-
WorkbookPart wbPart = document.WorkbookPart;
111-
// Code removed here...
112-
}
113-
```
43+
[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet1)]
11444

11545
### [Visual Basic](#tab/vb-3)
116-
```vb
117-
Using document As SpreadsheetDocument =
118-
SpreadsheetDocument.Open(fileName, False)
119-
120-
Dim wbPart As WorkbookPart = document.WorkbookPart
121-
' Code removed here...
122-
End Using
123-
```
46+
[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet1)]
12447
***
12548

12649

12750
To find the hidden rows or columns, the code must first retrieve a reference to the specified sheet, given its name. This is not as easy as you might think. The code must look through all the sheet-type descendants of the workbook part's [Workbook](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.workbookpart.workbook.aspx) property, examining the [Name](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.name.aspx) property of each sheet that it finds.
12851
Note that this search simply looks through the relations of the workbook, and does not actually find a worksheet part. It simply finds a reference to a [Sheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.aspx) object, which contains information such as the name and [Id](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.id.aspx) property of the sheet. The simplest way to accomplish this is to use a LINQ query.
12952

13053
### [C#](#tab/cs-4)
131-
```csharp
132-
Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().
133-
Where((s) => s.Name == sheetName).FirstOrDefault();
134-
if (theSheet == null)
135-
{
136-
throw new ArgumentException("sheetName");
137-
}
138-
```
54+
[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet2)]
13955

14056
### [Visual Basic](#tab/vb-4)
141-
```vb
142-
Dim theSheet As Sheet = wbPart.Workbook.Descendants(Of Sheet)().
143-
Where(Function(s) s.Name = sheetName).FirstOrDefault()
144-
If theSheet Is Nothing Then
145-
Throw New ArgumentException("sheetName")
146-
```
57+
[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet2)]
14758
***
14859

149-
150-
The [FirstOrDefault](https://msdn2.microsoft.com/library/bb358452) method returns either the first matching reference (a sheet, in this case) or a null reference if no match was found. The code checks for the
151-
null reference, and throws an exception if you passed in an invalid sheet name. Now that you have information about the sheet, the code must retrieve a reference to the corresponding worksheet part. The sheet
152-
information you already retrieved provides an **Id** property, and given that **Id** property, the code can retrieve a reference to the corresponding [WorksheetPart](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.worksheet.worksheetpart.aspx) property by calling the [GetPartById](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.openxmlpartcontainer.getpartbyid.aspx) method of the [WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.workbookpart.aspx) object.
60+
The sheet information you already retrieved provides an **Id** property, and given that **Id** property, the code can retrieve a reference to the corresponding [WorksheetPart](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.worksheet.worksheetpart.aspx) property by calling the [GetPartById](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.openxmlpartcontainer.getpartbyid.aspx) method of the [WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.workbookpart.aspx) object.
15361

15462
### [C#](#tab/cs-5)
155-
```csharp
156-
else
157-
{
158-
// The sheet does exist.
159-
WorksheetPart wsPart =
160-
(WorksheetPart)(wbPart.GetPartById(theSheet.Id));
161-
Worksheet ws = wsPart.Worksheet;
162-
// Code removed here...
163-
}
164-
```
63+
[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet3)]
16564

16665
### [Visual Basic](#tab/vb-5)
167-
```vb
168-
Else
169-
' The sheet does exist.
170-
Dim wsPart As WorksheetPart =
171-
CType(wbPart.GetPartById(theSheet.Id), WorksheetPart)
172-
Dim ws As Worksheet = wsPart.Worksheet
173-
' Code removed here...
174-
End If
175-
```
66+
[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet3)]
17667
***
17768

17869

17970
---------------------------------------------------------------------------------
18071

18172
## Retrieving the List of Hidden Row or Column Index Values
18273

183-
The code uses the **detectRows** parameter that
184-
you specified when you called the method to determine whether to
185-
retrieve information about rows or columns.
186-
187-
### [C#](#tab/cs-6)
188-
```csharp
189-
if (detectRows)
190-
{
191-
// Retrieve hidden rows.
192-
// Code removed here...
193-
}
194-
else
195-
{
196-
// Retrieve hidden columns.
197-
// Code removed here...
198-
}
199-
```
200-
201-
### [Visual Basic](#tab/vb-6)
202-
```vb
203-
If detectRows Then
204-
' Retrieve hidden rows.
205-
' Code removed here...
206-
Else
207-
' Retrieve hidden columns.
208-
' Code removed here...
209-
End If
210-
```
211-
***
212-
213-
214-
The code that actually retrieves the list of hidden rows requires only a single line of code.
74+
The code uses the **detectRows** parameter that you specified when you called the method to determine whether to retrieve information about rows or columns.The code that actually retrieves the list of hidden rows requires only a single line of code.
21575

21676
### [C#](#tab/cs-7)
217-
```csharp
218-
itemList = ws.Descendants<Row>().
219-
Where((r) => r.Hidden != null && r.Hidden.Value).
220-
Select(r => r.RowIndex.Value).ToList<uint>();
221-
```
77+
[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet4)]
22278

22379
### [Visual Basic](#tab/vb-7)
224-
```vb
225-
itemList = ws.Descendants(Of Row).
226-
Where(Function(r) r.Hidden IsNot Nothing AndAlso
227-
r.Hidden.Value).
228-
Select(Function(r) r.RowIndex.Value).ToList()
229-
```
80+
[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet4)]
23081
***
23182

232-
233-
This single line accomplishes a lot, however. It starts by calling the [Descendants](https://msdn.microsoft.com/library/office/documentformat.openxml.openxmlelement.descendants.aspx) method of the worksheet, retrieving a list of all the rows. The [Where](https://msdn2.microsoft.com/library/bb301979) method limits the results to only those rows where the [Hidden](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.row.hidden.aspx) property of the item is not null and the value of the **Hidden** property is **True**. The [Select](https://msdn2.microsoft.com/library/bb357126) method projects the return value for each row, returning the value of the [RowIndex](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.row.rowindex.aspx) property. Finally, the [ToList\<TSource\>](https://msdn2.microsoft.com/library/bb342261) method converts the resulting [IEnumerable\<T\>](https://msdn2.microsoft.com/library/9eekhta0) interface into a [List\<T\>](https://msdn2.microsoft.com/library/6sh2ey19) object of unsigned integers. If there are no hidden rows, the returned list is empty.
234-
23583
Retrieving the list of hidden columns is a bit trickier, because Excel collapses groups of hidden columns into a single element, and provides [Min](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.column.min.aspx) and [Max](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.column.max.aspx) properties that describe the first and last columns in the group. Therefore, the code that retrieves the list of hidden columns starts the same as the code that retrieves hidden rows. However, it must iterate through the index values (looping each item in the collection of hidden columns, adding each index from the **Min** to the **Max** value, inclusively).
23684

23785
### [C#](#tab/cs-8)
238-
```csharp
239-
var cols = ws.Descendants<Column>().
240-
Where((c) => c.Hidden != null && c.Hidden.Value);
241-
foreach (Column item in cols)
242-
{
243-
for (uint i = item.Min.Value; i <= item.Max.Value; i++)
244-
{
245-
itemList.Add(i);
246-
}
247-
}
248-
```
86+
[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet5)]
24987

25088
### [Visual Basic](#tab/vb-8)
251-
```vb
252-
Dim cols = ws.Descendants(Of Column).
253-
Where(Function(c) c.Hidden IsNot Nothing AndAlso
254-
c.Hidden.Value)
255-
For Each item As Column In cols
256-
For i As UInteger = item.Min.Value To item.Max.Value
257-
itemList.Add(i)
258-
Next
259-
Next
260-
```
89+
[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet5)]
26190
***
26291

26392

@@ -268,10 +97,10 @@ Retrieving the list of hidden columns is a bit trickier, because Excel collapses
26897
The following is the complete **GetHiddenRowsOrCols** code sample in C\# and Visual Basic.
26998

27099
### [C#](#tab/cs)
271-
[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs)]
100+
[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet0)]
272101

273102
### [Visual Basic](#tab/vb)
274-
[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb)]
103+
[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet0)]
275104

276105
---------------------------------------------------------------------------------
277106

Lines changed: 37 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,73 +1,61 @@
1+
// <Snippet0>
12
using DocumentFormat.OpenXml.Packaging;
23
using DocumentFormat.OpenXml.Spreadsheet;
34
using System;
45
using System.Collections.Generic;
56
using System.Linq;
67

7-
List<uint>? items = null;
8-
9-
if (args is [{ } fileName, { } sheetName, { } detectRows])
10-
{
11-
items = GetHiddenRowsOrCols(fileName, sheetName, detectRows);
12-
}
13-
else if (args is [{ } fileName2, { } sheetName2])
14-
{
15-
items = GetHiddenRowsOrCols(fileName2, sheetName2);
16-
}
17-
18-
if (items is null)
19-
{
20-
throw new ArgumentException("Invalid arguments.");
21-
}
22-
23-
foreach (uint item in items)
24-
{
25-
Console.WriteLine(item);
26-
}
27-
288
static List<uint> GetHiddenRowsOrCols(string fileName, string sheetName, string detectRows = "false")
299
{
3010
// Given a workbook and a worksheet name, return
3111
// either a list of hidden row numbers, or a list
3212
// of hidden column numbers. If detectRows is true, return
3313
// hidden rows. If detectRows is false, return hidden columns.
3414
// Rows and columns are numbered starting with 1.
35-
15+
// <Snippet1>
3616
List<uint> itemList = new List<uint>();
3717

3818
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
3919
{
4020
if (document is not null)
4121
{
4222
WorkbookPart wbPart = document.WorkbookPart ?? document.AddWorkbookPart();
23+
// </Snippet1>
4324

25+
// <Snippet2>
4426
Sheet? theSheet = wbPart.Workbook.Descendants<Sheet>().FirstOrDefault((s) => s.Name == sheetName);
4527

46-
if (theSheet is null)
28+
if (theSheet is null || theSheet.Id is null)
4729
{
4830
throw new ArgumentException("sheetName");
4931
}
32+
// </Snippet2>
5033
else
5134
{
52-
string id = theSheet.Id?.ToString() ?? string.Empty;
35+
// <Snippet3>
36+
5337
// The sheet does exist.
54-
WorksheetPart? wsPart = wbPart.GetPartById(id) as WorksheetPart;
38+
WorksheetPart? wsPart = wbPart.GetPartById(theSheet.Id!) as WorksheetPart;
5539
Worksheet? ws = wsPart?.Worksheet;
40+
// </Snippet3>
5641

5742
if (ws is not null)
5843
{
5944
if (detectRows.ToLower() == "true")
6045
{
46+
// <Snippet4>
6147
// Retrieve hidden rows.
6248
itemList = ws.Descendants<Row>()
6349
.Where((r) => r?.Hidden is not null && r.Hidden.Value)
6450
.Select(r => r.RowIndex?.Value)
6551
.Cast<uint>()
6652
.ToList();
53+
// </Snippet4>
6754
}
6855
else
6956
{
7057
// Retrieve hidden columns.
58+
// <Snippet5>
7159
var cols = ws.Descendants<Column>().Where((c) => c?.Hidden is not null && c.Hidden.Value);
7260

7361
foreach (Column item in cols)
@@ -80,11 +68,34 @@ static List<uint> GetHiddenRowsOrCols(string fileName, string sheetName, string
8068
}
8169
}
8270
}
71+
// </Snippet5>
8372
}
8473
}
8574
}
8675
}
8776
}
8877

8978
return itemList;
90-
}
79+
}
80+
// </Snippet0>
81+
82+
List<uint>? items = null;
83+
84+
if (args is [{ } fileName, { } sheetName, { } detectRows])
85+
{
86+
items = GetHiddenRowsOrCols(fileName, sheetName, detectRows);
87+
}
88+
else if (args is [{ } fileName2, { } sheetName2])
89+
{
90+
items = GetHiddenRowsOrCols(fileName2, sheetName2);
91+
}
92+
93+
if (items is null)
94+
{
95+
throw new ArgumentException("Invalid arguments.");
96+
}
97+
98+
foreach (uint item in items)
99+
{
100+
Console.WriteLine(item);
101+
}

0 commit comments

Comments
 (0)