Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract code snippets from how-to-retrieve-a-list-of-the-hidden-worksheets-in-a-spreadsheet.md #293

Merged
merged 1 commit into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,112 +18,22 @@ ms.localizationpriority: medium

This topic shows how to use the classes in the Open XML SDK for Office to programmatically retrieve a list of hidden worksheets in a Microsoft Excel 2010 or Microsoft Excel 2010 workbook, without loading the document into Excel. It contains an example **GetHiddenSheets** method to illustrate this task.



## GetHiddenSheets method

You can use the **GetHiddenSheets** method, which is shown in the following code, to retrieve a list of the hidden worksheets in a workbook. The **GetHiddenSheets** method accepts a single parameter, a string that indicates the path of the file that you want to examine.

### [C#](#tab/cs-0)
```csharp
public static List<Sheet> GetHiddenSheets(string fileName)
```

### [Visual Basic](#tab/vb-0)
```vb
Public Function GetHiddenSheets(ByVal fileName As String) As List(Of Sheet)
```
***


The method works with the workbook you specify, filling a **[List\<T\>](https://msdn2.microsoft.com/library/6sh2ey19)** instance with a reference to each hidden **Sheet** object.

## Calling the GetHiddenSheets method

The method returns a generic list that contains information about the individual hidden **Sheet** objects. To call the **GetHiddenWorksheets** method, pass the required parameter value, as shown in the following code.

### [C#](#tab/cs-1)
```csharp
// Revise this path to the location of a file that contains hidden worksheets.
const string DEMOPATH =
@"C:\Users\Public\Documents\HiddenSheets.xlsx";
List<Sheet> sheets = GetHiddenSheets(DEMOPATH);
foreach (var sheet in sheets)
{
Console.WriteLine(sheet.Name);
}
```

### [Visual Basic](#tab/vb-1)
```vb
' Revise this path to the location of a file that contains hidden worksheets.
Const DEMOPATH As String =
"C:\Users\Public\Documents\HiddenSheets.xlsx"
Dim sheets As List(Of Sheet) = GetHiddenSheets(DEMOPATH)
For Each sheet In sheets
Console.WriteLine(sheet.Name)
Next
```
***


## How the code works

The following code starts by creating a generic list that will contain information about the hidden worksheets.

### [C#](#tab/cs-2)
```csharp
List<Sheet> returnVal = new List<Sheet>();
```

### [Visual Basic](#tab/vb-2)
```vb
Dim returnVal As New List(Of Sheet)
```
***


Next, the following code opens the specified workbook by using the **SpreadsheetDocument.Open** method and indicating that the document should be open for read-only access (the final **false** parameter value). Given the open workbook, the code uses the **WorkbookPart** property to navigate to the main workbook part, storing the reference in a variable named **wbPart**.

### [C#](#tab/cs-3)
```csharp
using (SpreadsheetDocument document =
SpreadsheetDocument.Open(fileName, false))
{
WorkbookPart wbPart = document.WorkbookPart;
// Code removed here…
}
return returnVal;
```

### [Visual Basic](#tab/vb-3)
```vb
Using document As SpreadsheetDocument = SpreadsheetDocument.Open(fileName, False)
Dim wbPart As WorkbookPart = document.WorkbookPart
' Code removed here…
End Using
Return returnVal
```
***

You can use the **GetHiddenSheets** method, to retrieve a list of the hidden worksheets in a workbook. The **GetHiddenSheets** method accepts a single parameter, a string that indicates the path of the file that you want to examine. The method works with the workbook you specify, filling a **[List\<T\>](https://msdn2.microsoft.com/library/6sh2ey19)** instance with a reference to each hidden **Sheet** object.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
You can use the **GetHiddenSheets** method, to retrieve a list of the hidden worksheets in a workbook. The **GetHiddenSheets** method accepts a single parameter, a string that indicates the path of the file that you want to examine. The method works with the workbook you specify, filling a **[List\<T\>](https://msdn2.microsoft.com/library/6sh2ey19)** instance with a reference to each hidden **Sheet** object.
You can use the **GetHiddenSheets** method, to retrieve a list of the hidden worksheets in a workbook. The **GetHiddenSheets** method accepts a single parameter, a string that indicates the path of the file that you want to examine. The method works with the workbook you specify, filling a **[List\<T\>](/dotnet/api/system.collections.generic.list-1)** instance with a reference to each hidden **Sheet** object.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can do a pass to convert all these to more modern links (and then to xrefs if we can get that enabled) later


## Retrieve the collection of worksheets

The **WorkbookPart** class provides a **Workbook** property, which in turn contains the XML content of the workbook. Although the Open XML SDK provides the **Sheets** property, which returns a collection of the **Sheet** parts, all the information that you need is provided by the **Sheet** elements within the **Workbook** XML content.
The following code uses the **Descendants** generic method of the **Workbook** object to retrieve a collection of **Sheet** objects that contain information about all the sheet child elements of the workbook's XML content.

### [C#](#tab/cs-4)
```csharp
var sheets = wbPart.Workbook.Descendants<Sheet>();
```
[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs#snippet1)]

### [Visual Basic](#tab/vb-4)
```vb
Dim sheets = wbPart.Workbook.Descendants(Of Sheet)()
```
[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/vb/Program.vb#snippet1)]
***


## Retrieve hidden sheets

It's important to be aware that Excel supports two levels of worksheets. You can hide a worksheet by using the Excel user interface by right-clicking the worksheets tab and opting to hide the worksheet.
Expand All @@ -132,46 +42,21 @@ For these worksheets, the **State** property of the **Sheet** object contains an
Given the collection that contains information about all the sheets, the following code uses the **[Where](https://msdn2.microsoft.com/library/bb301979)** function to filter the collection so that it contains only the sheets in which the **State** property is not null. If the **State** property is not null, the code looks for the **Sheet** objects in which the **State** property as a value, and where the value is either **SheetStateValues.Hidden** or **SheetStateValues.VeryHidden**.

### [C#](#tab/cs-5)
```csharp
var hiddenSheets = sheets.Where((item) => item.State != null &&
item.State.HasValue &&
(item.State.Value == SheetStateValues.Hidden ||
item.State.Value == SheetStateValues.VeryHidden));
```
[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs#snippet2)]

### [Visual Basic](#tab/vb-5)
```vb
Dim hiddenSheets = sheets.Where(Function(item) item.State IsNot
Nothing AndAlso item.State.HasValue _
AndAlso (item.State.Value = SheetStateValues.Hidden Or _
item.State.Value = SheetStateValues.VeryHidden))
```
[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/vb/Program.vb#snippet2)]
***


Finally, the following code calls the **[ToList\<TSource\>](https://msdn2.microsoft.com/library/bb342261)** method to execute the LINQ query that retrieves the list of hidden sheets, placing the result into the return value for the function.

### [C#](#tab/cs-6)
```csharp
returnVal = hiddenSheets.ToList();
```

### [Visual Basic](#tab/vb-6)
```vb
returnVal = hiddenSheets.ToList()
```
***


## Sample code

The following is the complete **GetHiddenSheets** code sample in C\# and Visual Basic.

### [C#](#tab/cs)
[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs)]
[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs#snippet0)]

### [Visual Basic](#tab/vb)
[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/vb/Program.vb)]
[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/vb/Program.vb#snippet0)]

## See also

Expand Down
7 changes: 7 additions & 0 deletions samples/samples.sln
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "copy_the_contents_of_an_ope
EndProject
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif_vb", "word\copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif\vb\copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif_vb.vbproj", "{BE95ECDD-B751-410E-B138-44B77DA0DE14}"
EndProject
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "retrieve_a_list_of_the_hidden_worksheets_vb", "spreadsheet\retrieve_a_list_of_the_hidden_worksheets\vb\retrieve_a_list_of_the_hidden_worksheets_vb.vbproj", "{72BE6D64-0AEB-4090-A6F9-B255D291BF14}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -966,6 +968,10 @@ Global
{BE95ECDD-B751-410E-B138-44B77DA0DE14}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BE95ECDD-B751-410E-B138-44B77DA0DE14}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BE95ECDD-B751-410E-B138-44B77DA0DE14}.Release|Any CPU.Build.0 = Release|Any CPU
{72BE6D64-0AEB-4090-A6F9-B255D291BF14}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{72BE6D64-0AEB-4090-A6F9-B255D291BF14}.Debug|Any CPU.Build.0 = Debug|Any CPU
{72BE6D64-0AEB-4090-A6F9-B255D291BF14}.Release|Any CPU.ActiveCfg = Release|Any CPU
{72BE6D64-0AEB-4090-A6F9-B255D291BF14}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -1127,6 +1133,7 @@ Global
{F0CF5756-9899-4DEA-A884-95E06DE2E960} = {7ACDC26B-C774-4004-8553-87E862D1E71F}
{6A9A6136-3F51-4FCA-B2CA-82AB69160895} = {D207D3D7-FD4D-4FD4-A7D0-79A82086FB6F}
{BE95ECDD-B751-410E-B138-44B77DA0DE14} = {D207D3D7-FD4D-4FD4-A7D0-79A82086FB6F}
{72BE6D64-0AEB-4090-A6F9-B255D291BF14} = {7ACDC26B-C774-4004-8553-87E862D1E71F}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {721B3030-08D7-4412-9087-D1CFBB3F5046}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,25 @@
using System.Collections.Generic;
using System.Linq;

List<uint>? items = null;

if (args is [{ } fileName, { } sheetName, { } detectRows])
{
GetHiddenRowsOrCols(fileName, sheetName, detectRows);
items = GetHiddenRowsOrCols(fileName, sheetName, detectRows);
}
else if (args is [{ } fileName2, { } sheetName2])
{
GetHiddenRowsOrCols(fileName2, sheetName2);
items = GetHiddenRowsOrCols(fileName2, sheetName2);
}

if (items is null)
{
throw new ArgumentException("Invalid arguments.");
}

foreach (uint item in items)
{
Console.WriteLine(item);
}

static List<uint> GetHiddenRowsOrCols(string fileName, string sheetName, string detectRows = "false")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,33 +1,46 @@
// <Snippet0>
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.Linq;

GetHiddenSheets(args[0]);

static List<Sheet> GetHiddenSheets(string fileName)
{
List<Sheet> returnVal = new List<Sheet>();

using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
{
// <Snippet1>
WorkbookPart? wbPart = document.WorkbookPart;

if (wbPart is not null)
{
var sheets = wbPart.Workbook.Descendants<Sheet>();
// </Snippet1>

// Look for sheets where there is a State attribute defined,
// where the State has a value,
// and where the value is either Hidden or VeryHidden.

// <Snippet2>
var hiddenSheets = sheets.Where((item) => item.State is not null &&
item.State.HasValue &&
(item.State.Value == SheetStateValues.Hidden ||
item.State.Value == SheetStateValues.VeryHidden));
// </Snippet2>

returnVal = hiddenSheets.ToList();
}
}

return returnVal;
}
// </Snippet0>

var sheets = GetHiddenSheets(args[0]);

foreach (var sheet in sheets)
{
Console.WriteLine(sheet.Name);
}
Original file line number Diff line number Diff line change
@@ -1,31 +1,44 @@
' <Snippet0>
Imports DocumentFormat.OpenXml.Spreadsheet
Imports DocumentFormat.OpenXml.Packaging

Module Program `
Sub Main(args As String())`
End Sub`
Module Program
Sub Main(args As String())
Dim fileName As String = args(0)
Dim hiddenSheets As List(Of Sheet) = GetHiddenSheets(fileName)

For Each sheet As Sheet In hiddenSheets
Console.WriteLine("Sheet ID: {0} Name: {1}", sheet.Id, sheet.Name)
Next
End Sub





Public Function GetHiddenSheets(ByVal fileName As String) As List(Of Sheet)
Dim returnVal As New List(Of Sheet)

Using document As SpreadsheetDocument =
SpreadsheetDocument.Open(fileName, False)

' <Snippet1>
Dim wbPart As WorkbookPart = document.WorkbookPart
Dim sheets = wbPart.Workbook.Descendants(Of Sheet)()
' </Snippet1>

' Look for sheets where there is a State attribute defined,
' where the State has a value,
' and where the value is either Hidden or VeryHidden:

' <Snippet2>
Dim hiddenSheets = sheets.Where(Function(item) item.State IsNot
Nothing AndAlso item.State.HasValue _
AndAlso (item.State.Value = SheetStateValues.Hidden Or _
AndAlso (item.State.Value = SheetStateValues.Hidden Or
item.State.Value = SheetStateValues.VeryHidden))
' </Snippet2>

returnVal = hiddenSheets.ToList()
End Using
Return returnVal
End Function
End Module
End Module
' </Snippet0>