From 021771f62210e156941e1d01b14ce540dc3087ed Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Mon, 27 Nov 2023 15:56:00 -0800 Subject: [PATCH 001/139] Replace inline code samples with snippets (#292) --- .../how-to-apply-a-theme-to-a-presentation.md | 244 ++---------------- ...list-of-the-worksheets-in-a-spreadsheet.md | 76 +----- ...ve-the-values-of-cells-in-a-spreadsheet.md | 242 ++--------------- .../apply_a_theme_to/cs/Program.cs | 27 +- .../apply_a_theme_to/vb/Program.vb | 25 +- .../cs/Program.cs | 25 +- .../vb/Program.vb | 21 +- .../cs/Program.cs | 54 ++-- .../vb/Program.vb | 50 ++-- 9 files changed, 196 insertions(+), 568 deletions(-) diff --git a/docs/presentation/how-to-apply-a-theme-to-a-presentation.md b/docs/presentation/how-to-apply-a-theme-to-a-presentation.md index 809babf2..78aad9de 100644 --- a/docs/presentation/how-to-apply-a-theme-to-a-presentation.md +++ b/docs/presentation/how-to-apply-a-theme-to-a-presentation.md @@ -44,22 +44,10 @@ that represents the path for the source presentation document, and the represents the path for the target presentation document. ### [C#](#tab/cs-0) -```csharp - using (PresentationDocument themeDocument = PresentationDocument.Open(themePresentation, false)) - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true)) - { - // Insert other code here. - } -``` +[!code-csharp[](../../samples/presentation/apply_a_theme_to/cs/Program.cs?name=snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Using themeDocument As PresentationDocument = PresentationDocument.Open(themePresentation, False) - Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, True) - ' Insert other code here. - End Using - End Using -``` +[!code-vb[](../../samples/presentation/apply_a_theme_to/vb/Program.vb?name=snippet1)] *** @@ -141,29 +129,10 @@ files, **themePresentation** and **presentationFile**, are opened and passed to second overloaded method as parameters. ### [C#](#tab/cs-1) -```csharp - // Apply a new theme to the presentation. - public static void ApplyThemeToPresentation(string presentationFile, string themePresentation) - { - using (PresentationDocument themeDocument = PresentationDocument.Open(themePresentation, false)) - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true)) - { - ApplyThemeToPresentation(presentationDocument, themeDocument); - } - } -``` +[!code-csharp[](../../samples/presentation/apply_a_theme_to/cs/Program.cs?name=snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - ' Apply a new theme to the presentation. - Public Shared Sub ApplyThemeToPresentation(ByVal presentationFile As String, ByVal themePresentation As String) - Using themeDocument As PresentationDocument = PresentationDocument.Open(themePresentation, False) - Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, True) - ApplyThemeToPresentation(presentationDocument, themeDocument) - End Using - End Using - End Sub -``` +[!code-vb[](../../samples/presentation/apply_a_theme_to/vb/Program.vb?name=snippet2)] *** @@ -177,52 +146,10 @@ passed in, and gets the relationship ID of the slide master part of the target presentation. ### [C#](#tab/cs-2) -```csharp - // Apply a new theme to the presentation. - public static void ApplyThemeToPresentation(PresentationDocument presentationDocument, PresentationDocument themeDocument) - { - if (presentationDocument == null) - { - throw new ArgumentNullException("presentationDocument"); - } - if (themeDocument == null) - { - throw new ArgumentNullException("themeDocument"); - } - - // Get the presentation part of the presentation document. - PresentationPart presentationPart = presentationDocument.PresentationPart; - - // Get the existing slide master part. - SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.ElementAt(0); - string relationshipId = presentationPart.GetIdOfPart(slideMasterPart); - - // Get the new slide master part. - SlideMasterPart newSlideMasterPart = themeDocument.PresentationPart.SlideMasterParts.ElementAt(0); - } -``` +[!code-csharp[](../../samples/presentation/apply_a_theme_to/cs/Program.cs?name=snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - Apply a new theme to the presentation. - Public Shared Sub ApplyThemeToPresentation(ByVal presentationDocument As PresentationDocument, ByVal themeDocument As PresentationDocument) - If presentationDocument Is Nothing Then - Throw New ArgumentNullException("presentationDocument") - End If - If themeDocument Is Nothing Then - Throw New ArgumentNullException("themeDocument") - End If - - ' Get the presentation part of the presentation document. - Dim presentationPart As PresentationPart = presentationDocument.PresentationPart - - ' Get the existing slide master part. - Dim slideMasterPart As SlideMasterPart = presentationPart.SlideMasterParts.ElementAt(0) - Dim relationshipId As String = presentationPart.GetIdOfPart(slideMasterPart) - - ' Get the new slide master part. - Dim newSlideMasterPart As SlideMasterPart = themeDocument.PresentationPart.SlideMasterParts.ElementAt(0) -``` +[!code-vb[](../../samples/presentation/apply_a_theme_to/vb/Program.vb?name=snippet3)] *** @@ -233,34 +160,10 @@ target presentation. It also adds the theme part to the target presentation. ### [C#](#tab/cs-3) -```csharp - // Remove the existing theme part. - presentationPart.DeletePart(presentationPart.ThemePart); - - // Remove the old slide master part. - presentationPart.DeletePart(slideMasterPart); - - // Import the new slide master part, and reuse the old relationship ID. - newSlideMasterPart = presentationPart.AddPart(newSlideMasterPart, relationshipId); - - // Change to the new theme part. - presentationPart.AddPart(newSlideMasterPart.ThemePart); -``` +[!code-csharp[](../../samples/presentation/apply_a_theme_to/cs/Program.cs?name=snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - ' Remove the existing theme part. - presentationPart.DeletePart(presentationPart.ThemePart) - - ' Remove the old slide master part. - presentationPart.DeletePart(slideMasterPart) - - ' Import the new slide master part, and reuse the old relationship ID. - newSlideMasterPart = presentationPart.AddPart(newSlideMasterPart, relationshipId) - - ' Change to the new theme part. - presentationPart.AddPart(newSlideMasterPart.ThemePart) -``` +[!code-vb[](../../samples/presentation/apply_a_theme_to/vb/Program.vb?name=snippet4)] *** @@ -270,35 +173,10 @@ default layout type. For this example, the code for the default layout type is "Title and Content". ### [C#](#tab/cs-4) -```csharp - Dictionary newSlideLayouts = new Dictionary(); - - foreach (var slideLayoutPart in newSlideMasterPart.SlideLayoutParts) - { - newSlideLayouts.Add(GetSlideLayoutType(slideLayoutPart), slideLayoutPart); - } - - string layoutType = null; - SlideLayoutPart newLayoutPart = null; - - // Insert the code for the layout for this example. - string defaultLayoutType = "Title and Content"; -``` +[!code-csharp[](../../samples/presentation/apply_a_theme_to/cs/Program.cs?name=snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - Dim newSlideLayouts As New Dictionary(Of String, SlideLayoutPart)() - - For Each slideLayoutPart In newSlideMasterPart.SlideLayoutParts - newSlideLayouts.Add(GetSlideLayoutType(slideLayoutPart), slideLayoutPart) - Next slideLayoutPart - - Dim layoutType As String = Nothing - Dim newLayoutPart As SlideLayoutPart = Nothing - - ' Insert the code for the layout for this example. - Dim defaultLayoutType As String = "Title and Content" -``` +[!code-vb[](../../samples/presentation/apply_a_theme_to/vb/Program.vb?name=snippet5)] *** @@ -311,90 +189,22 @@ had previously. For any slide without an existing slide layout part, it adds a new slide layout part of the default type. ### [C#](#tab/cs-5) -```csharp - // Remove the slide layout relationship on all slides. - foreach (var slidePart in presentationPart.SlideParts) - { - layoutType = null; - - if (slidePart.SlideLayoutPart != null) - { - // Determine the slide layout type for each slide. - layoutType = GetSlideLayoutType(slidePart.SlideLayoutPart); - - // Delete the old layout part. - slidePart.DeletePart(slidePart.SlideLayoutPart); - } - - if (layoutType != null && newSlideLayouts.TryGetValue(layoutType, out newLayoutPart)) - { - // Apply the new layout part. - slidePart.AddPart(newLayoutPart); - } - else - { - newLayoutPart = newSlideLayouts[defaultLayoutType]; - - // Apply the new default layout part. - slidePart.AddPart(newLayoutPart); - } - } -``` +[!code-csharp[](../../samples/presentation/apply_a_theme_to/cs/Program.cs?name=snippet6)] ### [Visual Basic](#tab/vb-5) -```vb - ' Remove the slide layout relationship on all slides. - For Each slidePart In presentationPart.SlideParts - layoutType = Nothing - - If slidePart.SlideLayoutPart IsNot Nothing Then - ' Determine the slide layout type for each slide. - layoutType = GetSlideLayoutType(slidePart.SlideLayoutPart) - - ' Delete the old layout part. - slidePart.DeletePart(slidePart.SlideLayoutPart) - End If - - If layoutType IsNot Nothing AndAlso newSlideLayouts.TryGetValue(layoutType, newLayoutPart) Then - ' Apply the new layout part. - slidePart.AddPart(newLayoutPart) - Else - newLayoutPart = newSlideLayouts(defaultLayoutType) - - ' Apply the new default layout part. - slidePart.AddPart(newLayoutPart) - End If - Next slidePart -`` +[!code-vb[](../../samples/presentation/apply_a_theme_to/vb/Program.vb?name=snippet6)] +*** To get the type of the slide layout, the code uses the **GetSlideLayoutType** method that takes the slide layout part as a parameter, and returns to the second overloaded **ApplyThemeToPresentation** method a string that represents the name of the slide layout type -``csharp - // Get the slide layout type. - public static string GetSlideLayoutType(SlideLayoutPart slideLayoutPart) - { - CommonSlideData slideData = slideLayoutPart.SlideLayout.CommonSlideData; - - // Remarks: If this is used in production code, check for a null reference. +### [C#](#tab/cs-6) +[!code-csharp[](../../samples/presentation/apply_a_theme_to/cs/Program.cs?name=snippet7)] - return slideData.Name;} -``` +### [Visual Basic](#tab/vb-6) +[!code-vb[](../../samples/presentation/apply_a_theme_to/vb/Program.vb?name=snippet7)] *** - - -```vb - ' Get the slide layout type. - Public Shared Function GetSlideLayoutType(ByVal slideLayoutPart As SlideLayoutPart) As String - Dim slideData As CommonSlideData = slideLayoutPart.SlideLayout.CommonSlideData - - ' Remarks: If this is used in production code, check for a null reference. - - Return slideData.Name - End Function -``` - ----------------------------------------------------------------------------- ## Sample Code The following is the complete sample code to copy a theme from one @@ -404,19 +214,11 @@ copy, for example, Myppt9-theme.pptx, and the other one is the target presentation, for example, Myppt9.pptx. You can use the following call in your program to perform the copying. -### [C#](#tab/cs-6) -```csharp - string presentationFile=@"C:\Users\Public\Documents\myppt2.pptx"; - string themePresentation = @"C:\Users\Public\Documents\myppt2-theme.pptx"; - ApplyThemeToPresentation(presentationFile, themePresentation); -``` +### [C#](#tab/cs-7) +[!code-csharp[](../../samples/presentation/apply_a_theme_to/cs/Program.cs?name=snippet8)] -### [Visual Basic](#tab/vb-6) -```vb - Dim presentationFile As String = "C:\Users\Public\Documents\myppt2.pptx" - Dim themePresentation As String = "C:\Users\Public\Documents\myppt2-theme.pptx" - ApplyThemeToPresentation(presentationFile, themePresentation) -``` +### [Visual Basic](#tab/vb-7) +[!code-vb[](../../samples/presentation/apply_a_theme_to/vb/Program.vb?name=snippet8)] *** @@ -424,10 +226,10 @@ After performing that call you can inspect the file Myppt2.pptx, and you would see the same theme of the file Myppt9-theme.pptx. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/apply_a_theme_to/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/apply_a_theme_to/cs/Program.cs?name=snippet9)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/apply_a_theme_to/vb/Program.vb)] +[!code-vb[](../../samples/presentation/apply_a_theme_to/vb/Program.vb?name=snippet9)] ----------------------------------------------------------------------------- ## See also diff --git a/docs/spreadsheet/how-to-retrieve-a-list-of-the-worksheets-in-a-spreadsheet.md b/docs/spreadsheet/how-to-retrieve-a-list-of-the-worksheets-in-a-spreadsheet.md index 2a5f76e1..67330c29 100644 --- a/docs/spreadsheet/how-to-retrieve-a-list-of-the-worksheets-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-retrieve-a-list-of-the-worksheets-in-a-spreadsheet.md @@ -35,14 +35,10 @@ parameter, a string that indicates the path of the file that you want to examine. ### [C#](#tab/cs-0) -```csharp - public static Sheets GetAllWorksheets(string fileName) -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Function GetAllWorksheets(ByVal fileName As String) As Sheets -``` +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb#snippet2)] *** @@ -58,33 +54,10 @@ To call the **GetAllWorksheets** method, pass the required value, as shown in the following code. ### [C#](#tab/cs-1) -```csharp - const string DEMOFILE = @"C:\Users\Public\Documents\SampleWorkbook.xlsx"; - - static void Main(string[] args) - { - var results = GetAllWorksheets(DEMOFILE); - foreach (Sheet item in results) - { - Console.WriteLine(item.Name); - } - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Const DEMOFILE As String = - "C:\Samples\SampleWorkbook.xlsx" - - Sub Main() - Dim results = GetAllWorksheets(DEMOFILE) - ' Because Sheet inherits from OpenXmlElement, you can cast - ' each item in the collection to be a Sheet instance. - For Each item As Sheet In results - Console.WriteLine(item.Name) - Next - End Sub -``` +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb#snippet2)] *** @@ -100,18 +73,10 @@ null/Nothing if there were no sheets (this cannot occur in a well-formed workbook). ### [C#](#tab/cs-2) -```csharp - Sheets theSheets = null; - // Code removed here… - return theSheets; -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - Dim theSheets As Sheets - ' Code removed here… - Return theSheets -``` +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb#snippet3)] *** @@ -119,37 +84,20 @@ The code then continues by opening the document in read-only mode, and retrieving a reference to the **[WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.workbookpart.aspx)**. ### [C#](#tab/cs-3) -```csharp - using (SpreadsheetDocument document = - SpreadsheetDocument.Open(fileName, false)) - { - WorkbookPart wbPart = document.WorkbookPart; - // Code removed here. - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs#snippet4)] ### [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 -``` +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb#snippet4)] *** To get access to the **[Workbook](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.workbook.aspx)** object, the code retrieves the value of the **[Workbook](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.workbookpart.workbook.aspx)** property from the **WorkbookPart**, and then retrieves a reference to the **Sheets** object from the **[Sheets](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.workbook.sheets.aspx)** property of the **Workbook**. The **Sheets** object contains the collection of **[Sheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.aspx)** objects that provide the method's return value. ### [C#](#tab/cs-4) -```csharp - theSheets = wbPart.Workbook.Sheets; -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - theSheets = wbPart.Workbook.Sheets -``` +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb#snippet5)] *** @@ -161,10 +109,10 @@ The following is the complete **GetAllWorksheets** code sample in C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- diff --git a/docs/spreadsheet/how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md b/docs/spreadsheet/how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md index 0cac0d0d..6816f8d9 100644 --- a/docs/spreadsheet/how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md @@ -40,72 +40,22 @@ The method returns the value of the specified cell, if it could be found. The following code example shows the method signature. ### [C#](#tab/cs-0) -```csharp - public static string GetCellValue(string fileName, - string sheetName, - string addressName) -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs?name=snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Function GetCellValue(ByVal fileName As String, - ByVal sheetName As String, - ByVal addressName As String) As String -``` +[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb?name=snippet1)] *** - -## Calling the GetCellValue Sample Method - -To call the **GetCellValue** method, pass the -file name, sheet name, and cell address, as shown in the following code -example. - -### [C#](#tab/cs-1) -```csharp - const string fileName = - @"C:\users\public\documents\RetrieveCellValue.xlsx"; - - // Retrieve the value in cell A1. - string value = GetCellValue(fileName, "Sheet1", "A1"); - Console.WriteLine(value); - // Retrieve the date value in cell A2. - value = GetCellValue(fileName, "Sheet1", "A2"); - Console.WriteLine( - DateTime.FromOADate(double.Parse(value)).ToShortDateString()); -``` - -### [Visual Basic](#tab/vb-1) -```vb - Const fileName As String = - "C:\Users\Public\Documents\RetrieveCellValue.xlsx" - - ' Retrieve the value in cell A1. - Dim value As String = - GetCellValue(fileName, "Sheet1", "A1") - Console.WriteLine(value) - ' Retrieve the date value in cell A2. - value = GetCellValue(fileName, "Sheet1", "A2") - Console.WriteLine( - DateTime.FromOADate(Double.Parse(value)).ToShortDateString()) -``` -*** - - ## How the Code Works The code starts by creating a variable to hold the return value, and initializes it to null. ### [C#](#tab/cs-2) -```csharp - string value = null; -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-2) -```vb - Dim value as String = Nothing -``` +[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb#snippet2)] *** @@ -116,24 +66,10 @@ should be open for read-only access (the final **false** parameter). Next, the c 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. ### [C#](#tab/cs-3) -```csharp - // Open the spreadsheet document for read-only access. - using (SpreadsheetDocument document = - SpreadsheetDocument.Open(fileName, false)) - { - // Retrieve a reference to the workbook part. - WorkbookPart wbPart = document.WorkbookPart; -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs?name=snippet3)] ### [Visual Basic](#tab/vb-3) -```vb - ' Open the spreadsheet document for read-only access. - Using document As SpreadsheetDocument = - SpreadsheetDocument.Open(fileName, False) - - ' Retrieve a reference to the workbook part. - Dim wbPart As WorkbookPart = document.WorkbookPart -``` +[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb?name=snippet3)] *** @@ -147,31 +83,10 @@ the name and **[Id](https://msdn.microsoft.com/library/office/documentformat.ope this is to use a LINQ query, as shown in the following code example. ### [C#](#tab/cs-4) -```csharp - // Find the sheet with the supplied name, and then use that - // Sheet object to retrieve a reference to the first worksheet. - Sheet theSheet = wbPart.Workbook.Descendants(). - Where(s => s.Name == sheetName).FirstOrDefault(); - - // Throw an exception if there is no sheet. - if (theSheet == null) - { - throw new ArgumentException("sheetName"); - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs?name=snippet4)] ### [Visual Basic](#tab/vb-4) -```vb - ' Find the sheet with the supplied name, and then use that Sheet object - ' to retrieve a reference to the appropriate worksheet. - Dim theSheet As Sheet = wbPart.Workbook.Descendants(Of Sheet)(). - Where(Function(s) s.Name = sheetName).FirstOrDefault() - - ' Throw an exception if there is no sheet. - If theSheet Is Nothing Then - Throw New ArgumentException("sheetName") - End If -``` +[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb?name=snippet4)] *** @@ -186,18 +101,10 @@ the corresponding **[WorksheetPart](https://msdn.microsoft.com/library/office/do **[GetPartById](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.openxmlpartcontainer.getpartbyid.aspx)** method. ### [C#](#tab/cs-5) -```csharp - // Retrieve a reference to the worksheet part. - WorksheetPart wsPart = - (WorksheetPart)(wbPart.GetPartById(theSheet.Id)); -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs?name=snippet5)] ### [Visual Basic](#tab/vb-5) -```vb - ' Retrieve a reference to the worksheet part. - Dim wsPart As WorksheetPart = - CType(wbPart.GetPartById(theSheet.Id), WorksheetPart) -``` +[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb?name=snippet5)] *** @@ -209,20 +116,10 @@ parameter. After this method call, the variable named **theCell** will either co or will contain a null reference. ### [C#](#tab/cs-6) -```csharp - // Use its Worksheet property to get a reference to the cell - // whose address matches the address you supplied. - Cell theCell = wsPart.Worksheet.Descendants(). - Where(c => c.CellReference == addressName).FirstOrDefault(); -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs?name=snippet6)] ### [Visual Basic](#tab/vb-6) -```vb - ' Use its Worksheet property to get a reference to the cell - ' whose address matches the address you supplied. - Dim theCell As Cell = wsPart.Worksheet.Descendants(Of Cell). - Where(Function(c) c.CellReference = addressName).FirstOrDefault -``` +[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb?name=snippet6)] *** @@ -243,23 +140,10 @@ The **[InnerText](https://msdn.microsoft.com/library/office/documentformat.openx the cell, and so the next block of code retrieves this value. ### [C#](#tab/cs-7) -```csharp - // If the cell does not exist, return an empty string. - if (theCell != null) - { - value = theCell.InnerText; - // Code removed here… - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs?name=snippet7)] ### [Visual Basic](#tab/vb-7) -```vb - ' If the cell does not exist, return an empty string. - If theCell IsNot Nothing Then - value = theCell.InnerText - ' Code removed here… - End If -``` +[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb#snippet7)] *** @@ -273,38 +157,10 @@ the value of the cell (it is a numeric value). Otherwise, the code continues by branching based on the data type. ### [C#](#tab/cs-8) -```csharp - // If the cell represents an integer number, you are done. - // For dates, this code returns the serialized value that - // represents the date. The code handles strings and - // Booleans individually. For shared strings, the code - // looks up the corresponding value in the shared string - // table. For Booleans, the code converts the value into - // the words TRUE or FALSE. - if (theCell.DataType != null) - { - switch (theCell.DataType.Value) - { - // Code removed here… - } - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs#snippet8)] ### [Visual Basic](#tab/vb-8) -```vb - ' If the cell represents an numeric value, you are done. - ' For dates, this code returns the serialized value that - ' represents the date. The code handles strings and - ' Booleans individually. For shared strings, the code - ' looks up the corresponding value in the shared string - ' table. For Booleans, the code converts the value into - ' the words TRUE or FALSE. - If theCell.DataType IsNot Nothing Then - Select Case theCell.DataType.Value - ' Code removed here… - End Select - End If -``` +[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb?#snippet8)] *** @@ -312,21 +168,10 @@ If the **DataType** property contains **CellValues.SharedString**, the code must reference to the single **[SharedStringTablePart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.workbookpart.sharedstringtablepart.aspx)**. ### [C#](#tab/cs-9) -```csharp - // For shared strings, look up the value in the - // shared strings table. - var stringTable = - wbPart.GetPartsOfType() - .FirstOrDefault(); -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs#snippet9)] ### [Visual Basic](#tab/vb-9) -```vb - ' For shared strings, look up the value in the - ' shared strings table. - Dim stringTable = wbPart. - GetPartsOfType(Of SharedStringTablePart).FirstOrDefault() -``` +[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb?#snippet9)] *** @@ -336,30 +181,10 @@ instead of the string itself) the code returns the **InnerText** property of the specified index (first converting the value property to an integer). ### [C#](#tab/cs-10) -```csharp - // If the shared string table is missing, something - // is wrong. Return the index that is in - // the cell. Otherwise, look up the correct text in - // the table. - if (stringTable != null) - { - value = - stringTable.SharedStringTable - .ElementAt(int.Parse(value)).InnerText; - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs#snippet10)] ### [Visual Basic](#tab/vb-10) -```vb - ' If the shared string table is missing, something - ' is wrong. Return the index that is in - ' the cell. Otherwise, look up the correct text in - ' the table. - If stringTable IsNot Nothing Then - value = stringTable.SharedStringTable. - ElementAt(Integer.Parse(value)).InnerText - End If -``` +[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb?#snippet10)] *** @@ -367,29 +192,10 @@ If the **DataType** property contains **CellValues.Boolean**, the code converts it finds in the cell value into the appropriate text string. ### [C#](#tab/cs-11) -```csharp - case CellValues.Boolean: - switch (value) - { - case "0": - value = "FALSE"; - break; - default: - value = "TRUE"; - break; - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs#snippet11)] ### [Visual Basic](#tab/vb-11) -```vb - Case CellValues.Boolean - Select Case value - Case "0" - value = "FALSE" - Case Else - value = "TRUE" - End Select -``` +[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb#snippet11)] *** @@ -400,10 +206,10 @@ Finally, the procedure returns the variable **value**, which contains the reques The following is the complete **GetCellValue** code sample in C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb#snippet0)] ## See also diff --git a/samples/presentation/apply_a_theme_to/cs/Program.cs b/samples/presentation/apply_a_theme_to/cs/Program.cs index e310f47b..0c56c348 100644 --- a/samples/presentation/apply_a_theme_to/cs/Program.cs +++ b/samples/presentation/apply_a_theme_to/cs/Program.cs @@ -1,20 +1,25 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Presentation; using System.Collections.Generic; using System.Linq; - +// ApplyThemeToPresentation(args[0], args[1]); - +// +// // Apply a new theme to the presentation. static void ApplyThemeToPresentation(string presentationFile, string themePresentation) { + // using (PresentationDocument themeDocument = PresentationDocument.Open(themePresentation, false)) using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true)) { + // ApplyThemeToPresentationDocument(presentationDocument, themeDocument); } } - +// +// // Apply a new theme to the presentation. static void ApplyThemeToPresentationDocument(PresentationDocument presentationDocument, PresentationDocument themeDocument) { @@ -30,7 +35,8 @@ static void ApplyThemeToPresentationDocument(PresentationDocument presentationDo // Get the new slide master part. PresentationPart themeDocPresentationPart = themeDocument.PresentationPart ?? themeDocument.AddPresentationPart(); SlideMasterPart newSlideMasterPart = themeDocPresentationPart.SlideMasterParts.ElementAt(0); - + // + // if (presentationPart.ThemePart is not null) { // Remove the existing theme part. @@ -48,7 +54,8 @@ static void ApplyThemeToPresentationDocument(PresentationDocument presentationDo // Change to the new theme part. presentationPart.AddPart(newSlideMasterPart.ThemePart); } - + // + // Dictionary newSlideLayouts = new Dictionary(); foreach (var slideLayoutPart in newSlideMasterPart.SlideLayoutParts) @@ -66,7 +73,8 @@ static void ApplyThemeToPresentationDocument(PresentationDocument presentationDo // Insert the code for the layout for this example. string defaultLayoutType = "Title and Content"; - + // + // // Remove the slide layout relationship on all slides. foreach (var slidePart in presentationPart.SlideParts) { @@ -94,14 +102,15 @@ static void ApplyThemeToPresentationDocument(PresentationDocument presentationDo slidePart.AddPart(newLayoutPart); } } + // } - +// // Get the slide layout type. static string? GetSlideLayoutType(SlideLayoutPart slideLayoutPart) { CommonSlideData? slideData = slideLayoutPart.SlideLayout?.CommonSlideData; - // Remarks: If this is used in production code, check for a null reference. - return slideData?.Name; } +// +// diff --git a/samples/presentation/apply_a_theme_to/vb/Program.vb b/samples/presentation/apply_a_theme_to/vb/Program.vb index c2eb1fc8..7732a27d 100644 --- a/samples/presentation/apply_a_theme_to/vb/Program.vb +++ b/samples/presentation/apply_a_theme_to/vb/Program.vb @@ -1,23 +1,30 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Presentation Module MyModule - + ' Sub Main(args As String()) + ApplyThemeToPresentation(args(0), args(1)) End Sub - + ' + ' ' Apply a new theme to the presentation. Public Sub ApplyThemeToPresentation(ByVal presentationFile As String, ByVal themePresentation As String) + ' Dim themeDocument As PresentationDocument = PresentationDocument.Open(themePresentation, False) Dim presentationDoc As PresentationDocument = PresentationDocument.Open(presentationFile, True) Using (themeDocument) Using (presentationDoc) + ' ApplyThemeToPresentation(presentationDoc, themeDocument) End Using End Using End Sub + ' + ' ' Apply a new theme to the presentation. Public Sub ApplyThemeToPresentation(ByVal presentationDocument As PresentationDocument, ByVal themeDocument As PresentationDocument) If (presentationDocument Is Nothing) Then @@ -37,7 +44,8 @@ Module MyModule ' Get the new slide master part. Dim newSlideMasterPart As SlideMasterPart = themeDocument.PresentationPart.SlideMasterParts.ElementAt(0) - + ' + ' ' Remove the theme part. presentationPart.DeletePart(presentationPart.ThemePart) @@ -49,6 +57,9 @@ Module MyModule ' Change to the new theme part. presentationPart.AddPart(newSlideMasterPart.ThemePart) + ' + ' + ' Dim newSlideLayouts As Dictionary(Of String, SlideLayoutPart) = New Dictionary(Of String, SlideLayoutPart)() For Each slideLayoutPart As Object In newSlideMasterPart.SlideLayoutParts newSlideLayouts.Add(GetSlideLayoutType(slideLayoutPart), slideLayoutPart) @@ -58,7 +69,7 @@ Module MyModule ' Insert the code for the layout for this example. Dim defaultLayoutType As String = "Title and Content" - + ' ' Remove the slide layout relationship on all slides. For Each slidePart As Object In presentationPart.SlideParts layoutType = Nothing @@ -81,8 +92,10 @@ Module MyModule ' Apply the new default layout part. slidePart.AddPart(newLayoutPart) End If + ' Next End Sub + ' ' Get the type of the slide layout. Public Function GetSlideLayoutType(ByVal slideLayoutPart As SlideLayoutPart) As String Dim slideData As CommonSlideData = slideLayoutPart.SlideLayout.CommonSlideData @@ -90,4 +103,6 @@ Module MyModule ' Remarks: If this is used in production code, check for a null reference. Return slideData.Name End Function -End Module \ No newline at end of file + ' +End Module +' \ No newline at end of file diff --git a/samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs b/samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs index a72be727..8aecfb1b 100644 --- a/samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs +++ b/samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs @@ -1,7 +1,21 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; +using System; +// -GetAllWorksheets(args[0]); +// +Sheets? sheets = GetAllWorksheets(args[0]); +// + +if (sheets is not null) +{ + foreach (Sheet sheet in sheets) + { + Console.WriteLine(sheet.Name); + } +} +// // Retrieve a List of all the sheets in a workbook. // The Sheets class contains a collection of @@ -9,12 +23,19 @@ // the sheets. static Sheets? GetAllWorksheets(string fileName) { + // Sheets? theSheets = null; + // + // using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false)) { + // theSheets = document?.WorkbookPart?.Workbook.Sheets; + // + // } return theSheets; -} \ No newline at end of file +} +// diff --git a/samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb b/samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb index e438b481..ee967dae 100644 --- a/samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb +++ b/samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb @@ -1,31 +1,38 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Spreadsheet Module Module1 - - Const DEMOFILE As String = - "C:\Users\Public\Documents\SampleWorkbook.xlsx" - - Sub Main() - Dim results = GetAllWorksheets(DEMOFILE) + ' + Sub Main(args As String()) + ' + Dim results = GetAllWorksheets(args(0)) + ' ' Because Sheet inherits from OpenXmlElement, you can cast ' each item in the collection to be a Sheet instance. For Each item As Sheet In results Console.WriteLine(item.Name) Next End Sub - + ' ' Retrieve a list of all the sheets in a Workbook. ' The Sheets class contains a collection of ' OpenXmlElement objects, each representing ' one of the sheets. Public Function GetAllWorksheets(ByVal fileName As String) As Sheets + ' Dim theSheets As Sheets + ' + ' Using document As SpreadsheetDocument = SpreadsheetDocument.Open(fileName, False) Dim wbPart As WorkbookPart = document.WorkbookPart + ' + ' theSheets = wbPart.Workbook.Sheets() + ' End Using Return theSheets End Function End Module +' diff --git a/samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs b/samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs index 299bc02c..cd708c7f 100644 --- a/samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs +++ b/samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs @@ -1,47 +1,55 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; using System.Linq; -GetCellValue(args[0], args[1], args[2]); +Console.WriteLine(GetCellValue(args[0], args[1], args[2])); // Retrieve the value of a cell, given a file name, sheet name, // and address name. +// static string GetCellValue(string fileName, string sheetName, string addressName) +// { + // string? value = null; - + // + // // Open the spreadsheet document for read-only access. - using (SpreadsheetDocument document = - SpreadsheetDocument.Open(fileName, false)) + using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false)) { // Retrieve a reference to the workbook part. - WorkbookPart wbPart = document.WorkbookPart ?? document.AddWorkbookPart(); - + WorkbookPart? wbPart = document.WorkbookPart; + // + // // Find the sheet with the supplied name, and then use that // Sheet object to retrieve a reference to the first worksheet. - Sheet? theSheet = wbPart.Workbook.Descendants().Where(s => s.Name == sheetName).FirstOrDefault(); + Sheet? theSheet = wbPart?.Workbook.Descendants().Where(s => s.Name == sheetName).FirstOrDefault(); // Throw an exception if there is no sheet. if (theSheet is null || theSheet.Id is null) { throw new ArgumentException("sheetName"); } - + // + // // Retrieve a reference to the worksheet part. - WorksheetPart wsPart = (WorksheetPart)wbPart.GetPartById(theSheet.Id!); - + WorksheetPart wsPart = (WorksheetPart)wbPart!.GetPartById(theSheet.Id!); + // + // // Use its Worksheet property to get a reference to the cell // whose address matches the address you supplied. Cell? theCell = wsPart.Worksheet?.Descendants()?.Where(c => c.CellReference == addressName).FirstOrDefault(); - + // + // // If the cell does not exist, return an empty string. - if (theCell is null || theCell.InnerText.Length > 0) + if (theCell is null || theCell.InnerText.Length < 0) { return string.Empty; } - value = theCell.InnerText; - + // + // // If the cell represents an integer number, you are done. // For dates, this code returns the serialized value that // represents the date. The code handles strings and @@ -53,24 +61,26 @@ static string GetCellValue(string fileName, string sheetName, string addressName { if (theCell.DataType.Value == CellValues.SharedString) { - + // + // // For shared strings, look up the value in the // shared strings table. - var stringTable = - wbPart.GetPartsOfType().FirstOrDefault(); - + var stringTable = wbPart.GetPartsOfType().FirstOrDefault(); + // + // // If the shared string table is missing, something // is wrong. Return the index that is in // the cell. Otherwise, look up the correct text in // the table. if (stringTable is not null) { - value = - stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText; + value = stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText; } + // } else if (theCell.DataType.Value == CellValues.Boolean) { + // switch (value) { case "0": @@ -78,6 +88,7 @@ static string GetCellValue(string fileName, string sheetName, string addressName break; default: value = "TRUE"; + // break; } } @@ -85,4 +96,5 @@ static string GetCellValue(string fileName, string sheetName, string addressName } return value; -} \ No newline at end of file +} +// diff --git a/samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb b/samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb index 533dfb86..7b9ccdda 100644 --- a/samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb +++ b/samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb @@ -1,3 +1,4 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Spreadsheet @@ -6,20 +7,20 @@ Module Program End Sub - - Public Function GetCellValue(ByVal fileName As String, - ByVal sheetName As String, - ByVal addressName As String) As String - + ' + Public Function GetCellValue(ByVal fileName As String, ByVal sheetName As String, ByVal addressName As String) As String + ' + ' Dim value As String = Nothing - + ' + ' ' Open the spreadsheet document for read-only access. - Using document As SpreadsheetDocument = - SpreadsheetDocument.Open(fileName, False) + Using document As SpreadsheetDocument = SpreadsheetDocument.Open(fileName, False) ' Retrieve a reference to the workbook part. Dim wbPart As WorkbookPart = document.WorkbookPart - + ' + ' ' Find the sheet with the supplied name, and then use that Sheet object ' to retrieve a reference to the appropriate worksheet. Dim theSheet As Sheet = wbPart.Workbook.Descendants(Of Sheet)(). @@ -29,20 +30,23 @@ Module Program If theSheet Is Nothing Then Throw New ArgumentException("sheetName") End If - + ' ' Retrieve a reference to the worksheet part. - Dim wsPart As WorksheetPart = - CType(wbPart.GetPartById(theSheet.Id), WorksheetPart) - + ' + Dim wsPart As WorksheetPart = CType(wbPart.GetPartById(theSheet.Id), WorksheetPart) + ' + ' ' Use its Worksheet property to get a reference to the cell ' whose address matches the address you supplied. Dim theCell As Cell = wsPart.Worksheet.Descendants(Of Cell). Where(Function(c) c.CellReference = addressName).FirstOrDefault - + ' + ' ' If the cell does not exist, return an empty string. If theCell IsNot Nothing Then value = theCell.InnerText - + ' + ' ' If the cell represents an numeric value, you are done. ' For dates, this code returns the serialized value that ' represents the date. The code handles strings and @@ -52,13 +56,14 @@ Module Program ' the words TRUE or FALSE. If theCell.DataType IsNot Nothing Then Select Case theCell.DataType.Value + ' Case CellValues.SharedString - + ' ' For shared strings, look up the value in the ' shared strings table. - Dim stringTable = wbPart. - GetPartsOfType(Of SharedStringTablePart).FirstOrDefault() - + Dim stringTable = wbPart.GetPartsOfType(Of SharedStringTablePart).FirstOrDefault() + ' + ' ' If the shared string table is missing, something ' is wrong. Return the index that is in ' the cell. Otherwise, look up the correct text in @@ -67,7 +72,8 @@ Module Program value = stringTable.SharedStringTable. ElementAt(Integer.Parse(value)).InnerText End If - + ' + ' Case CellValues.Boolean Select Case value Case "0" @@ -75,10 +81,12 @@ Module Program Case Else value = "TRUE" End Select + ' End Select End If End If End Using Return value End Function -End Module \ No newline at end of file +End Module +' \ No newline at end of file From 80dda5853158d7a2f0b1e361fe1f2933cef82f29 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Wed, 29 Nov 2023 09:18:11 -0800 Subject: [PATCH 002/139] Extract code snippets from how-to-retrieve-a-list-of-the-hidden-worksheets-in-a-spreadsheet.md and add missing project (#293) --- ...-the-hidden-worksheets-in-a-spreadsheet.md | 129 +----------------- samples/samples.sln | 7 + .../cs/Program.cs | 16 ++- .../cs/Program.cs | 17 ++- .../vb/Program.vb | 27 +++- 5 files changed, 63 insertions(+), 133 deletions(-) diff --git a/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-worksheets-in-a-spreadsheet.md b/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-worksheets-in-a-spreadsheet.md index 90371c6a..baa59eae 100644 --- a/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-worksheets-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-worksheets-in-a-spreadsheet.md @@ -18,94 +18,9 @@ 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 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\](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 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 returnVal = new List(); -``` - -### [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\](https://msdn2.microsoft.com/library/6sh2ey19)** instance with a reference to each hidden **Sheet** object. ## Retrieve the collection of worksheets @@ -113,17 +28,12 @@ The **WorkbookPart** class provides a **Workbook** property, which in turn conta 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(); -``` +[!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. @@ -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\](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 diff --git a/samples/samples.sln b/samples/samples.sln index 77e03ed3..42fbbf65 100644 --- a/samples/samples.sln +++ b/samples/samples.sln @@ -328,6 +328,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "copy_the_contents_of_an_ope EndProject Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "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 @@ -962,6 +964,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 @@ -1123,6 +1129,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} diff --git a/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs b/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs index f51fdaba..876cc5a0 100644 --- a/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs +++ b/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs @@ -4,13 +4,25 @@ using System.Collections.Generic; using System.Linq; +List? 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 GetHiddenRowsOrCols(string fileName, string sheetName, string detectRows = "false") diff --git a/samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs b/samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs index e377843d..59cf208d 100644 --- a/samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs +++ b/samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs @@ -1,33 +1,46 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; +using System; using System.Collections.Generic; using System.Linq; -GetHiddenSheets(args[0]); - static List GetHiddenSheets(string fileName) { List returnVal = new List(); using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false)) { + // WorkbookPart? wbPart = document.WorkbookPart; if (wbPart is not null) { var sheets = wbPart.Workbook.Descendants(); + // // 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. + + // var hiddenSheets = sheets.Where((item) => item.State is not null && item.State.HasValue && (item.State.Value == SheetStateValues.Hidden || item.State.Value == SheetStateValues.VeryHidden)); + // returnVal = hiddenSheets.ToList(); } } return returnVal; +} +// + +var sheets = GetHiddenSheets(args[0]); + +foreach (var sheet in sheets) +{ + Console.WriteLine(sheet.Name); } \ No newline at end of file diff --git a/samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/vb/Program.vb b/samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/vb/Program.vb index c510cf05..af9b16ba 100644 --- a/samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/vb/Program.vb +++ b/samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/vb/Program.vb @@ -1,31 +1,44 @@ +' 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) + ' Dim wbPart As WorkbookPart = document.WorkbookPart Dim sheets = wbPart.Workbook.Descendants(Of Sheet)() + ' ' 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: + + ' 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)) + ' returnVal = hiddenSheets.ToList() End Using Return returnVal End Function -End Module \ No newline at end of file +End Module +' From 8ebb0a8fee65e0ad87ead007a0df0592f6bbfedb Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Tue, 5 Dec 2023 10:39:43 -0800 Subject: [PATCH 003/139] Extract code snippets from how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md (#294) --- ...hidden-rows-or-columns-in-a-spreadsheet.md | 205 ++---------------- .../cs/Program.cs | 63 +++--- .../vb/Program.vb | 22 +- 3 files changed, 72 insertions(+), 218 deletions(-) diff --git a/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md b/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md index d3805008..a8b0d587 100644 --- a/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md @@ -17,8 +17,7 @@ ms.localizationpriority: high --- # Retrieve a list of the hidden rows or columns in a spreadsheet document -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 -loading the document into Excel. It contains an example **GetHiddenRowsOrCols** method to illustrate this task. +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. @@ -26,10 +25,7 @@ loading the document into Excel. It contains an example **GetHiddenRowsOrCols** ## GetHiddenRowsOrCols Method -You can use the **GetHiddenRowsOrCols** method -to retrieve a list of the hidden rows or columns in a worksheet. The -**GetHiddenRowsOrCols** method accepts three -parameters, indicating the following: +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: - The name of the document to examine (string). @@ -37,90 +33,17 @@ parameters, indicating the following: - Whether to detect rows (true) or columns (false) (Boolean). -### [C#](#tab/cs-0) -```csharp - public static List GetHiddenRowsOrCols( - string fileName, string sheetName, bool detectRows) -``` - -### [Visual Basic](#tab/vb-0) -```vb - Public Function GetHiddenRowsOrCols( - ByVal fileName As String, ByVal sheetName As String, - ByVal detectRows As Boolean) As List(Of UInteger) -``` -*** - - ---------------------------------------------------------------------------------- - -## Calling the GetHiddenRowsOrCols Method - -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. - -### [C#](#tab/cs-1) -```csharp - const string fileName = @"C:\users\public\documents\RetrieveHiddenRowsCols.xlsx"; - List items = GetHiddenRowsOrCols(fileName, "Sheet1", true); - var sw = new StringWriter(); - foreach (var item in items) - sw.WriteLine(item); - Console.WriteLine(sw.ToString()); -``` - -### [Visual Basic](#tab/vb-1) -```vb - Const fileName As String = "C:\Users\Public\Documents\RetrieveHiddenRowsCols.xlsx" - Dim items As List(Of UInteger) = - GetHiddenRowsOrCols(fileName, "Sheet1", True) - Dim sw As New StringWriter - For Each item In items - sw.WriteLine(item) - Next - Console.WriteLine(sw.ToString()) -``` -*** - - --------------------------------------------------------------------------------- ## How the Code Works -The code starts by creating a variable, **itemList**, that will contain the return value. - -### [C#](#tab/cs-2) -```csharp - List itemList = new List(); -``` - -### [Visual Basic](#tab/vb-2) -```vb - Dim itemList As New List(Of UInteger) -``` -*** - - -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. +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. ### [C#](#tab/cs-3) -```csharp - using (SpreadsheetDocument document = - SpreadsheetDocument.Open(fileName, false)) - { - WorkbookPart wbPart = document.WorkbookPart; - // Code removed here... - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet1)] ### [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 -``` +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet1)] *** @@ -128,51 +51,19 @@ To find the hidden rows or columns, the code must first retrieve a reference to 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. ### [C#](#tab/cs-4) -```csharp - Sheet theSheet = wbPart.Workbook.Descendants(). - Where((s) => s.Name == sheetName).FirstOrDefault(); - if (theSheet == null) - { - throw new ArgumentException("sheetName"); - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-4) -```vb - Dim theSheet As Sheet = wbPart.Workbook.Descendants(Of Sheet)(). - Where(Function(s) s.Name = sheetName).FirstOrDefault() - If theSheet Is Nothing Then - Throw New ArgumentException("sheetName") -``` +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet2)] *** - -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 -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 -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. +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. ### [C#](#tab/cs-5) -```csharp - else - { - // The sheet does exist. - WorksheetPart wsPart = - (WorksheetPart)(wbPart.GetPartById(theSheet.Id)); - Worksheet ws = wsPart.Worksheet; - // Code removed here... - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-5) -```vb - Else - ' The sheet does exist. - Dim wsPart As WorksheetPart = - CType(wbPart.GetPartById(theSheet.Id), WorksheetPart) - Dim ws As Worksheet = wsPart.Worksheet - ' Code removed here... - End If -``` +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet3)] *** @@ -180,84 +71,22 @@ information you already retrieved provides an **Id** property, and given that ** ## Retrieving the List of Hidden Row or Column Index Values -The code uses the **detectRows** parameter that -you specified when you called the method to determine whether to -retrieve information about rows or columns. - -### [C#](#tab/cs-6) -```csharp - if (detectRows) - { - // Retrieve hidden rows. - // Code removed here... - } - else - { - // Retrieve hidden columns. - // Code removed here... - } -``` - -### [Visual Basic](#tab/vb-6) -```vb - If detectRows Then - ' Retrieve hidden rows. - ' Code removed here... - Else - ' Retrieve hidden columns. - ' Code removed here... - End If -``` -*** - - -The code that actually retrieves the list of hidden rows requires only a single line of code. +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. ### [C#](#tab/cs-7) -```csharp - itemList = ws.Descendants(). - Where((r) => r.Hidden != null && r.Hidden.Value). - Select(r => r.RowIndex.Value).ToList(); -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-7) -```vb - itemList = ws.Descendants(Of Row). - Where(Function(r) r.Hidden IsNot Nothing AndAlso - r.Hidden.Value). - Select(Function(r) r.RowIndex.Value).ToList() -``` +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet4)] *** - -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\](https://msdn2.microsoft.com/library/bb342261) method converts the resulting [IEnumerable\](https://msdn2.microsoft.com/library/9eekhta0) interface into a [List\](https://msdn2.microsoft.com/library/6sh2ey19) object of unsigned integers. If there are no hidden rows, the returned list is empty. - 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). ### [C#](#tab/cs-8) -```csharp - var cols = ws.Descendants(). - Where((c) => c.Hidden != null && c.Hidden.Value); - foreach (Column item in cols) - { - for (uint i = item.Min.Value; i <= item.Max.Value; i++) - { - itemList.Add(i); - } - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-8) -```vb - Dim cols = ws.Descendants(Of Column). - Where(Function(c) c.Hidden IsNot Nothing AndAlso - c.Hidden.Value) - For Each item As Column In cols - For i As UInteger = item.Min.Value To item.Max.Value - itemList.Add(i) - Next - Next -``` +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet5)] *** @@ -268,10 +97,10 @@ Retrieving the list of hidden columns is a bit trickier, because Excel collapses The following is the complete **GetHiddenRowsOrCols** code sample in C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet0)] --------------------------------------------------------------------------------- diff --git a/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs b/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs index 876cc5a0..4739e1ad 100644 --- a/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs +++ b/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs @@ -1,30 +1,10 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; using System.Collections.Generic; using System.Linq; -List? items = null; - -if (args is [{ } fileName, { } sheetName, { } detectRows]) -{ - items = GetHiddenRowsOrCols(fileName, sheetName, detectRows); -} -else if (args is [{ } 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 GetHiddenRowsOrCols(string fileName, string sheetName, string detectRows = "false") { // Given a workbook and a worksheet name, return @@ -32,7 +12,7 @@ static List GetHiddenRowsOrCols(string fileName, string sheetName, string // of hidden column numbers. If detectRows is true, return // hidden rows. If detectRows is false, return hidden columns. // Rows and columns are numbered starting with 1. - + // List itemList = new List(); using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false)) @@ -40,34 +20,42 @@ static List GetHiddenRowsOrCols(string fileName, string sheetName, string if (document is not null) { WorkbookPart wbPart = document.WorkbookPart ?? document.AddWorkbookPart(); + // + // Sheet? theSheet = wbPart.Workbook.Descendants().FirstOrDefault((s) => s.Name == sheetName); - if (theSheet is null) + if (theSheet is null || theSheet.Id is null) { throw new ArgumentException("sheetName"); } + // else { - string id = theSheet.Id?.ToString() ?? string.Empty; + // + // The sheet does exist. - WorksheetPart? wsPart = wbPart.GetPartById(id) as WorksheetPart; + WorksheetPart? wsPart = wbPart.GetPartById(theSheet.Id!) as WorksheetPart; Worksheet? ws = wsPart?.Worksheet; + // if (ws is not null) { if (detectRows.ToLower() == "true") { + // // Retrieve hidden rows. itemList = ws.Descendants() .Where((r) => r?.Hidden is not null && r.Hidden.Value) .Select(r => r.RowIndex?.Value) .Cast() .ToList(); + // } else { // Retrieve hidden columns. + // var cols = ws.Descendants().Where((c) => c?.Hidden is not null && c.Hidden.Value); foreach (Column item in cols) @@ -80,6 +68,7 @@ static List GetHiddenRowsOrCols(string fileName, string sheetName, string } } } + // } } } @@ -87,4 +76,26 @@ static List GetHiddenRowsOrCols(string fileName, string sheetName, string } return itemList; -} \ No newline at end of file +} +// + +List? items = null; + +if (args is [{ } fileName, { } sheetName, { } detectRows]) +{ + items = GetHiddenRowsOrCols(fileName, sheetName, detectRows); +} +else if (args is [{ } fileName2, { } sheetName2]) +{ + items = GetHiddenRowsOrCols(fileName2, sheetName2); +} + +if (items is null) +{ + throw new ArgumentException("Invalid arguments."); +} + +foreach (uint item in items) +{ + Console.WriteLine(item); +} diff --git a/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb b/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb index 47207836..f6621a23 100644 --- a/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb +++ b/samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb @@ -1,3 +1,4 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Spreadsheet @@ -6,7 +7,6 @@ Module Program End Sub - Public Function GetHiddenRowsOrCols( ByVal fileName As String, ByVal sheetName As String, ByVal detectRows As Boolean) As List(Of UInteger) @@ -17,31 +17,40 @@ Module Program ' hidden rows. If detectRows is False, return hidden columns. ' Rows and columns are numbered starting with 1. + ' Dim itemList As New List(Of UInteger) Using document As SpreadsheetDocument = SpreadsheetDocument.Open(fileName, False) Dim wbPart As WorkbookPart = document.WorkbookPart + ' + ' Dim theSheet As Sheet = wbPart.Workbook.Descendants(Of Sheet)(). Where(Function(s) s.Name = sheetName).FirstOrDefault() If theSheet Is Nothing Then Throw New ArgumentException("sheetName") + ' + + ' Else ' The sheet does exist. - Dim wsPart As WorksheetPart = - CType(wbPart.GetPartById(theSheet.Id), WorksheetPart) + Dim wsPart As WorksheetPart = CType(wbPart.GetPartById(theSheet.Id), WorksheetPart) Dim ws As Worksheet = wsPart.Worksheet + ' If detectRows Then ' Retrieve hidden rows. + ' itemList = ws.Descendants(Of Row). Where(Function(r) r.Hidden IsNot Nothing AndAlso r.Hidden.Value). Select(Function(r) r.RowIndex.Value).ToList() + ' Else ' Retrieve hidden columns. + ' Dim cols = ws.Descendants(Of Column). Where(Function(c) c.Hidden IsNot Nothing AndAlso c.Hidden.Value) @@ -50,9 +59,14 @@ Module Program itemList.Add(i) Next Next + ' + End If + End If End Using Return itemList End Function -End Module \ No newline at end of file +End Module + +' From 04deec72951b437357abd6c3fe412a73ac18d73a Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Mon, 8 Jan 2024 11:28:43 -0800 Subject: [PATCH 004/139] Extract code snippets from markdown files (#296) --- ...receives-a-relationship-id-to-a-package.md | 13 +- ...to-add-a-new-document-part-to-a-package.md | 6 +- ...ackage-part-to-a-document-part-in-a-dif.md | 13 +- docs/general/how-to-create-a-package.md | 16 +- ...tents-of-a-document-part-from-a-package.md | 13 +- ...o-remove-a-document-part-from-a-package.md | 13 +- ...heme-part-in-a-word-processing-document.md | 16 +- ...rch-and-replace-text-in-a-document-part.md | 13 +- .../word/packages-and-document-parts.md | 13 + .../how-to-apply-a-theme-to-a-presentation.md | 2 +- ...elete-text-from-a-cell-in-a-spreadsheet.md | 3 - ...ow-to-insert-a-chart-into-a-spreadsheet.md | 364 +----------------- ...sert-a-new-worksheet-into-a-spreadsheet.md | 134 +------ ...nsert-text-into-a-cell-in-a-spreadsheet.md | 364 +----------------- ...rge-two-adjacent-cells-in-a-spreadsheet.md | 145 +------ ...readsheet-document-for-read-only-access.md | 80 +--- ...en-a-spreadsheet-document-from-a-stream.md | 93 +---- ...w-to-parse-and-read-a-large-spreadsheet.md | 140 +------ ...ry-of-all-named-ranges-in-a-spreadsheet.md | 129 +------ ...hidden-rows-or-columns-in-a-spreadsheet.md | 2 +- ...-the-hidden-worksheets-in-a-spreadsheet.md | 2 +- ...list-of-the-worksheets-in-a-spreadsheet.md | 2 +- ...ve-the-values-of-cells-in-a-spreadsheet.md | 2 +- .../how-to-set-the-font-for-a-text-run.md | 13 +- .../insert_a_chartto/cs/Program.cs | 17 +- .../insert_a_chartto/vb/Program.vb | 22 +- .../insert_a_new_worksheet/cs/Program.cs | 6 +- .../insert_textto_a_cell/cs/Program.cs | 17 +- .../insert_textto_a_cell/vb/Program.vb | 14 +- .../merge_two_adjacent_cells/cs/Program.cs | 7 +- .../merge_two_adjacent_cells/vb/Program.vb | 7 +- .../open_for_read_only_access/cs/Program.cs | 49 ++- .../open_for_read_only_access/vb/Program.vb | 44 ++- .../open_from_a_stream/cs/Program.cs | 17 +- .../open_from_a_stream/vb/Program.vb | 15 +- .../cs/Program.cs | 22 +- .../vb/Program.vb | 26 +- .../cs/Program.cs | 29 +- .../vb/Program.vb | 23 +- 39 files changed, 352 insertions(+), 1554 deletions(-) create mode 100644 docs/includes/word/packages-and-document-parts.md diff --git a/docs/general/how-to-add-a-new-document-part-that-receives-a-relationship-id-to-a-package.md b/docs/general/how-to-add-a-new-document-part-that-receives-a-relationship-id-to-a-package.md index 3c742e0a..512f0346 100644 --- a/docs/general/how-to-add-a-new-document-part-that-receives-a-relationship-id-to-a-package.md +++ b/docs/general/how-to-add-a-new-document-part-that-receives-a-relationship-id-to-a-package.md @@ -24,18 +24,7 @@ processing document. ----------------------------------------------------------------------------- -## Packages and Document Parts -An Open XML document is stored as a package, whose format is defined by -[ISO/IEC 29500-2](https://www.iso.org/standard/71691.html). The -package can have multiple parts with relationships between them. The -relationship between parts controls the category of the document. A -document can be defined as a word-processing document if its -package-relationship item contains a relationship to a main document -part. If its package-relationship item contains a relationship to a -presentation part it can be defined as a presentation document. If its -package-relationship item contains a relationship to a workbook part, it -is defined as a spreadsheet document. In this how-to topic, you will use -a word-processing document package. +[!include[Structure](../includes/word/packages-and-document-parts.md)] ----------------------------------------------------------------------------- diff --git a/docs/general/how-to-add-a-new-document-part-to-a-package.md b/docs/general/how-to-add-a-new-document-part-to-a-package.md index eb869c04..40021a8f 100644 --- a/docs/general/how-to-add-a-new-document-part-to-a-package.md +++ b/docs/general/how-to-add-a-new-document-part-to-a-package.md @@ -17,11 +17,7 @@ ms.localizationpriority: medium This topic shows how to use the classes in the Open XML SDK for Office to add a document part (file) to a word processing document programmatically. - - -## Packages and document parts - -An Open XML document is stored as a package, whose format is defined by [ISO/IEC 29500-2](https://www.iso.org/standard/71691.html). The package can have multiple parts with relationships between them. The relationship between parts controls the category of the document. A document can be defined as a word-processing document if its package-relationship item contains a relationship to a main document part. If its package-relationship item contains a relationship to a presentation part it can be defined as a presentation document. If its package-relationship item contains a relationship to a workbook part, it is defined as a spreadsheet document. In this how-to topic, you'll use a word-processing document package. +[!include[Structure](../includes/word/packages-and-document-parts.md)] ## Get a WordprocessingDocument object diff --git a/docs/general/how-to-copy-the-contents-of-an-open-xml-package-part-to-a-document-part-in-a-dif.md b/docs/general/how-to-copy-the-contents-of-an-open-xml-package-part-to-a-document-part-in-a-dif.md index 61ee8e7f..3429e8d8 100644 --- a/docs/general/how-to-copy-the-contents-of-an-open-xml-package-part-to-a-document-part-in-a-dif.md +++ b/docs/general/how-to-copy-the-contents-of-an-open-xml-package-part-to-a-document-part-in-a-dif.md @@ -25,18 +25,7 @@ programmatically. -------------------------------------------------------------------------------- -## Packages and Document Parts -An Open XML document is stored as a package, whose format is defined by -[ISO/IEC 29500-2](https://www.iso.org/standard/71691.html). The -package can have multiple parts with relationships between them. The -relationship between parts controls the category of the document. A -document can be defined as a word-processing document if its -package-relationship item contains a relationship to a main document -part. If its package-relationship item contains a relationship to a -presentation part it can be defined as a presentation document. If its -package-relationship item contains a relationship to a workbook part, it -is defined as a spreadsheet document. In this how-to topic, you will use -a word-processing document package. +[!include[Structure](../includes/word/packages-and-document-parts.md)] -------------------------------------------------------------------------------- diff --git a/docs/general/how-to-create-a-package.md b/docs/general/how-to-create-a-package.md index a4f62cdc..5c28f447 100644 --- a/docs/general/how-to-create-a-package.md +++ b/docs/general/how-to-create-a-package.md @@ -21,21 +21,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to programmatically create a word processing document package from content in the form of **WordprocessingML** XML markup. - - -## Packages and Document Parts - -An Open XML document is stored as a package, whose format is defined by -[ISO/IEC 29500-2](https://www.iso.org/standard/71691.html). The -package can have multiple parts with relationships between them. The -relationship between parts controls the category of the document. A -document can be defined as a word-processing document if its -package-relationship item contains a relationship to a main document -part. If its package-relationship item contains a relationship to a -presentation part it can be defined as a presentation document. If its -package-relationship item contains a relationship to a workbook part, it -is defined as a spreadsheet document. In this how-to topic, you will use -a word-processing document package. +[!include[Structure](../includes/word/packages-and-document-parts.md)] ## Getting a WordprocessingDocument Object diff --git a/docs/general/how-to-get-the-contents-of-a-document-part-from-a-package.md b/docs/general/how-to-get-the-contents-of-a-document-part-from-a-package.md index e022e650..c092e0be 100644 --- a/docs/general/how-to-get-the-contents-of-a-document-part-from-a-package.md +++ b/docs/general/how-to-get-the-contents-of-a-document-part-from-a-package.md @@ -23,18 +23,7 @@ document programmatically. -------------------------------------------------------------------------------- -## Packages and Document Parts -An Open XML document is stored as a package, whose format is defined by -[ISO/IEC 29500-2](https://www.iso.org/standard/71691.html). The -package can have multiple parts with relationships between them. The -relationship between parts controls the category of the document. A -document can be defined as a word-processing document if its -package-relationship item contains a relationship to a main document -part. If its package-relationship item contains a relationship to a -presentation part it can be defined as a presentation document. If its -package-relationship item contains a relationship to a workbook part, it -is defined as a spreadsheet document. In this how-to topic, you will use -a word-processing document package. +[!include[Structure](../includes/word/packages-and-document-parts.md)] --------------------------------------------------------------------------------- diff --git a/docs/general/how-to-remove-a-document-part-from-a-package.md b/docs/general/how-to-remove-a-document-part-from-a-package.md index e2a4c432..77742ba0 100644 --- a/docs/general/how-to-remove-a-document-part-from-a-package.md +++ b/docs/general/how-to-remove-a-document-part-from-a-package.md @@ -23,18 +23,7 @@ programmatically. -------------------------------------------------------------------------------- -## Packages and Document Parts -An Open XML document is stored as a package, whose format is defined by -[ISO/IEC 29500-2](https://www.iso.org/standard/71691.html). The -package can have multiple parts with relationships between them. The -relationship between parts controls the category of the document. A -document can be defined as a word-processing document if its -package-relationship item contains a relationship to a main document -part. If its package-relationship item contains a relationship to a -presentation part it can be defined as a presentation document. If its -package-relationship item contains a relationship to a workbook part, it -is defined as a spreadsheet document. In this how-to topic, you will use -a word-processing document package. +[!include[Structure](../includes/word/packages-and-document-parts.md)] --------------------------------------------------------------------------------- diff --git a/docs/general/how-to-replace-the-theme-part-in-a-word-processing-document.md b/docs/general/how-to-replace-the-theme-part-in-a-word-processing-document.md index 8ed5b408..8e86f9c7 100644 --- a/docs/general/how-to-replace-the-theme-part-in-a-word-processing-document.md +++ b/docs/general/how-to-replace-the-theme-part-in-a-word-processing-document.md @@ -20,21 +20,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to programmatically replace a document part in a word processing document. - - -## Packages and Document Parts - -An Open XML document is stored as a package, whose format is defined by -[ISO/IEC 29500-2](https://www.iso.org/standard/71691.html). The -package can have multiple parts with relationships between them. The -relationship between parts controls the category of the document. A -document can be defined as a word-processing document if its -package-relationship item contains a relationship to a main document -part. If its package-relationship item contains a relationship to a -presentation part it can be defined as a presentation document. If its -package-relationship item contains a relationship to a workbook part, it -is defined as a spreadsheet document. In this how-to topic, you will use -a word-processing document package. +[!include[Structure](../includes/word/packages-and-document-parts.md)] ## Getting a WordprocessingDocument Object diff --git a/docs/general/how-to-search-and-replace-text-in-a-document-part.md b/docs/general/how-to-search-and-replace-text-in-a-document-part.md index cfdfbe19..1cdc9569 100644 --- a/docs/general/how-to-search-and-replace-text-in-a-document-part.md +++ b/docs/general/how-to-search-and-replace-text-in-a-document-part.md @@ -23,18 +23,7 @@ processing document. -------------------------------------------------------------------------------- -## Packages and Document Parts -An Open XML document is stored as a package, whose format is defined by -[ISO/IEC 29500-2](https://www.iso.org/standard/71691.html). The -package can have multiple parts with relationships between them. The -relationship between parts controls the category of the document. A -document can be defined as a word-processing document if its -package-relationship item contains a relationship to a main document -part. If its package-relationship item contains a relationship to a -presentation part it can be defined as a presentation document. If its -package-relationship item contains a relationship to a workbook part, it -is defined as a spreadsheet document. In this how-to topic, you will use -a word-processing document package. +[!include[Structure](../includes/word/packages-and-document-parts.md)] --------------------------------------------------------------------------------- diff --git a/docs/includes/word/packages-and-document-parts.md b/docs/includes/word/packages-and-document-parts.md new file mode 100644 index 00000000..a2a0356b --- /dev/null +++ b/docs/includes/word/packages-and-document-parts.md @@ -0,0 +1,13 @@ +## Packages and Document Parts + +An Open XML document is stored as a package, whose format is defined by +[ISO/IEC 29500-2](https://www.iso.org/standard/71691.html). The +package can have multiple parts with relationships between them. The +relationship between parts controls the category of the document. A +document can be defined as a word-processing document if its +package-relationship item contains a relationship to a main document +part. If its package-relationship item contains a relationship to a +presentation part it can be defined as a presentation document. If its +package-relationship item contains a relationship to a workbook part, it +is defined as a spreadsheet document. In this how-to topic, you will use +a word-processing document package. \ No newline at end of file diff --git a/docs/presentation/how-to-apply-a-theme-to-a-presentation.md b/docs/presentation/how-to-apply-a-theme-to-a-presentation.md index 78aad9de..b5b6e2a2 100644 --- a/docs/presentation/how-to-apply-a-theme-to-a-presentation.md +++ b/docs/presentation/how-to-apply-a-theme-to-a-presentation.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 12/05/2023 ms.localizationpriority: medium --- diff --git a/docs/spreadsheet/how-to-delete-text-from-a-cell-in-a-spreadsheet.md b/docs/spreadsheet/how-to-delete-text-from-a-cell-in-a-spreadsheet.md index f8ec9c93..1eb293ca 100644 --- a/docs/spreadsheet/how-to-delete-text-from-a-cell-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-delete-text-from-a-cell-in-a-spreadsheet.md @@ -19,9 +19,6 @@ This topic shows how to use the classes in the Open XML SDK for Office to delete text from a cell in a spreadsheet document programmatically. - - - ## Get a SpreadsheetDocument object In the Open XML SDK, the [SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx) class represents an Excel document package. To open and work with an Excel document, create an instance of the **SpreadsheetDocument** class from the document. After you create the instance from the document, obtain access to the main workbook part that contains the worksheets. The text in the document is represented in the package as XML using **SpreadsheetML** markup. diff --git a/docs/spreadsheet/how-to-insert-a-chart-into-a-spreadsheet.md b/docs/spreadsheet/how-to-insert-a-chart-into-a-spreadsheet.md index 7dc9b486..18197bbd 100644 --- a/docs/spreadsheet/how-to-insert-a-chart-into-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-insert-a-chart-into-a-spreadsheet.md @@ -9,7 +9,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 12/12/2023 ms.localizationpriority: high --- @@ -17,51 +17,6 @@ ms.localizationpriority: high This topic shows how to use the classes in the Open XML SDK for Office to insert a chart into a spreadsheet document programmatically. - - -## Get a SpreadsheetDocument object - -In the Open XML SDK, the [SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx) class represents an -Excel document package. To open and work with an Excel document, you -create an instance of the **SpreadsheetDocument** class from the document. -After you create the instance from the document, you can then obtain -access to the main workbook part that contains the worksheets. The -content in the document is represented in the package as XML using **SpreadsheetML** markup. - -To create the class instance from the document, you call one of the -[Open()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.open.aspx) methods. Several are provided, each -with a different signature. The sample code in this topic uses the [Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562356.aspx) method with a -signature that requires two parameters. The first parameter takes a full -path string that represents the document that you want to open. The -second parameter is either **true** or **false** and represents whether you want the file to -be opened for editing. Any changes to the document will not be saved if -this parameter is **false**. - -The code that calls the **Open** method is shown in the following **using** statement. - -### [C#](#tab/cs-0) -```csharp - // Open the document for editing. - using (SpreadsheetDocument document = SpreadsheetDocument.Open(docName, true)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - ' Open the document for editing. - Using document As SpreadsheetDocument = SpreadsheetDocument.Open(docName, True) - ' Insert other code here. - End Using -``` -*** - - -The **using** statement provides a recommended alternative to the typical .Open, .Save, .Close sequence. It ensures that the **Dispose** method (internal method used by the Open XML SDK to clean up resources) is automatically called when the closing brace is reached. The block that follows the **using** statement establishes a scope for the object that is created or named in the **using** statement, in this case *document*. - -[!include[Structure](../includes/spreadsheet/structure.md)] - ## Row element In this how-to, you are going to deal with the row, cell, and cell value @@ -191,58 +146,10 @@ In the following example cell B4 contains the number 360. After opening the spreadsheet file for read/write access, the code verifies if the specified worksheet exists. It then adds a new [DrawingsPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.drawingspart.aspx) object using the [AddNewPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.openxmlpartcontainer.addnewpart.aspx) method, appends it to the worksheet, and saves the worksheet part. The code then adds a new [ChartPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.chartpart.aspx) object, appends a new [ChartSpace](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.chartpart.chartspace.aspx) object to the **ChartPart** object, and then appends a new [EditingLanguage](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.chartspace.editinglanguage.aspx) object to the **ChartSpace*** object that specifies the language for the chart is English-US. ### [C#](#tab/cs-1) -```csharp - IEnumerable sheets = document.WorkbookPart.Workbook.Descendants().Where - (s => s.Name == worksheetName); - if (sheets.Count() == 0) - { - // The specified worksheet does not exist. - return; - } - WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id); - - // Add a new drawing to the worksheet. - DrawingsPart drawingsPart = worksheetPart.AddNewPart(); - worksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing() - { Id = worksheetPart.GetIdOfPart(drawingsPart) }); - worksheetPart.Worksheet.Save(); - - // Add a new chart and set the chart language to English-US. - ChartPart chartPart = drawingsPart.AddNewPart(); - chartPart.ChartSpace = new ChartSpace(); - chartPart.ChartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") }); - DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartPart.ChartSpace.AppendChild - - (new DocumentFormat.OpenXml.Drawing.Charts.Chart()); -``` +[!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-1) -```vb - Dim sheets As IEnumerable(Of Sheet) = _ - document.WorkbookPart.Workbook.Descendants(Of Sheet)() _ - .Where(Function(s) s.Name = worksheetName) - If sheets.Count() = 0 Then - ' The specified worksheet does not exist. - Return - End If - Dim worksheetPart As WorksheetPart = _ - CType(document.WorkbookPart.GetPartById(sheets.First().Id), WorksheetPart) - - ' Add a new drawing to the worksheet. - Dim drawingsPart As DrawingsPart = worksheetPart.AddNewPart(Of DrawingsPart)() - worksheetPart.Worksheet.Append(New DocumentFormat.OpenXml.Spreadsheet.Drawing() With {.Id = _ - worksheetPart.GetIdOfPart(drawingsPart)}) - worksheetPart.Worksheet.Save() - - ' Add a new chart and set the chart language to English-US. - Dim chartPart As ChartPart = drawingsPart.AddNewPart(Of ChartPart)() - chartPart.ChartSpace = New ChartSpace() - chartPart.ChartSpace.Append(New EditingLanguage() With {.Val = _ - New StringValue("en-US")}) - Dim chart As DocumentFormat.OpenXml.Drawing.Charts.Chart = _ - chartPart.ChartSpace.AppendChild(Of DocumentFormat.OpenXml.Drawing.Charts _ - .Chart)(New DocumentFormat.OpenXml.Drawing.Charts.Chart()) -``` +[!code-vb[](../../samples/spreadsheet/insert_a_chartto/vb/Program.vb#snippet1)] *** @@ -252,293 +159,46 @@ The code then iterates through each key in the **Dictionary** class. For each ke [BarChartSeries](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.barchartseries.aspx) object to the **BarChart** object and sets the [SeriesText](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.seriestext.aspx) object of the **BarChartSeries** object to equal the key. For each key, it appends a [NumberLiteral](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.numberliteral.aspx) object to the **Values** collection of the **BarChartSeries** object and sets the **NumberLiteral** object to equal the **Dictionary** class value corresponding to the key. ### [C#](#tab/cs-2) -```csharp - // Create a new clustered column chart. - PlotArea plotArea = chart.AppendChild(new PlotArea()); - Layout layout = plotArea.AppendChild(new Layout()); - BarChart barChart = plotArea.AppendChild(new BarChart(new BarDirection() - { Val = new EnumValue(BarDirectionValues.Column) }, - new BarGrouping() { Val = new EnumValue (BarGroupingValues.Clustered) })); - - uint i = 0; - - // Iterate through each key in the Dictionary collection and add the key to the chart Series - // and add the corresponding value to the chart Values. - foreach (string key in data.Keys) - { - BarChartSeries barChartSeries = barChart.AppendChild - (new BarChartSeries(new Index() { Val = new UInt32Value(i) }, - new Order() { Val = new UInt32Value(i) }, - new SeriesText(new NumericValue() { Text = key }))); - - StringLiteral strLit = barChartSeries.AppendChild - (new CategoryAxisData()).AppendChild(new StringLiteral()); - strLit.Append(new PointCount() { Val = new UInt32Value(1U) }); - strLit.AppendChild(new StringPoint() { Index = new UInt32Value(0U) }) - .Append(new NumericValue(title)); - - NumberLiteral numLit = barChartSeries.AppendChild(new DocumentFormat.OpenXml.Drawing.Charts.Values()).AppendChild - (new NumberLiteral()); - numLit.Append(new FormatCode("General")); - numLit.Append(new PointCount() { Val = new UInt32Value(1U) }); - numLit.AppendChild(new NumericPoint() { Index = new UInt32Value(0u)}) - .Append(new NumericValue(data[key].ToString())); - - i++; - } -``` +[!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-2) -```vb - ' Create a new clustered column chart. - Dim plotArea As PlotArea = chart.AppendChild(Of PlotArea)(New PlotArea()) - Dim layout As Layout = plotArea.AppendChild(Of Layout)(New Layout()) - Dim barChart As BarChart = plotArea.AppendChild(Of BarChart)(New BarChart _ - (New BarDirection() With {.Val = New EnumValue(Of BarDirectionValues) _ - (BarDirectionValues.Column)}, New BarGrouping() With {.Val = New EnumValue _ - (Of BarGroupingValues)(BarGroupingValues.Clustered)})) - - Dim i As UInteger = 0 - - ' Iterate through each key in the Dictionary collection and add the key to the chart Series - ' and add the corresponding value to the chart Values. - For Each key As String In data.Keys - Dim barChartSeries As BarChartSeries = barChart.AppendChild(Of BarChartSeries) _ - (New BarChartSeries(New Index() With {.Val = New UInt32Value(i)}, New Order() _ - With {.Val = New UInt32Value(i)}, New SeriesText(New NumericValue() With {.Text = key}))) - - Dim strLit As StringLiteral = barChartSeries.AppendChild(Of CategoryAxisData) _ - (New CategoryAxisData()).AppendChild(Of StringLiteral)(New StringLiteral()) - strLit.Append(New PointCount() With {.Val = New UInt32Value(1UI)}) - strLit.AppendChild(Of StringPoint)(New StringPoint() With {.Index = _ - New UInt32Value(0UI)}).Append(New NumericValue(title)) - - Dim numLit As NumberLiteral = barChartSeries.AppendChild _ - (Of DocumentFormat.OpenXml.Drawing.Charts.Values)(New DocumentFormat _ - .OpenXml.Drawing.Charts.Values()).AppendChild(Of NumberLiteral)(New NumberLiteral()) - numLit.Append(New FormatCode("General")) - numLit.Append(New PointCount() With {.Val = New UInt32Value(1UI)}) - numLit.AppendChild(Of NumericPoint)(New NumericPoint() With {.Index = _ - New UInt32Value(0UI)}).Append(New NumericValue(data(key).ToString())) - - i += 1 - Next key -``` +[!code-vb[](../../samples/spreadsheet/insert_a_chartto/vb/Program.vb#snippet2)] *** The code adds the [CategoryAxis](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.categoryaxis.aspx) object and [ValueAxis](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.valueaxis.aspx) object to the chart and sets the value of the following properties: [Scaling](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.scaling.aspx), [AxisPosition](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.axisposition.aspx), [TickLabelPosition](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.ticklabelposition.aspx), [CrossingAxis](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.crossingaxis.aspx), [Crosses](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.crosses.aspx), [AutoLabeled](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.autolabeled.aspx), [LabelAlignment](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.labelalignment.aspx), and [LabelOffset](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.labeloffset.aspx). It also adds the [Legend](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.charts.chart.legend.aspx) object to the chart and saves the chart part. ### [C#](#tab/cs-3) -```csharp - barChart.Append(new AxisId() { Val = new UInt32Value(48650112u) }); - barChart.Append(new AxisId() { Val = new UInt32Value(48672768u) }); - - // Add the Category Axis. - CategoryAxis catAx = plotArea.AppendChild(new CategoryAxis(new AxisId() - { Val = new UInt32Value(48650112u) }, new Scaling(new Orientation() - { - Val = new EnumValue( - DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax) - }), - new AxisPosition() { Val = new EnumValue(AxisPositionValues.Bottom) }, - new TickLabelPosition() { Val = new EnumValue(TickLabelPositionValues.NextTo) }, - new CrossingAxis() { Val = new UInt32Value(48672768U) }, - new Crosses() { Val = new EnumValue(CrossesValues.AutoZero) }, - new AutoLabeled() { Val = new BooleanValue(true) }, - new LabelAlignment() { Val = new EnumValue(LabelAlignmentValues.Center) }, - new LabelOffset() { Val = new UInt16Value((ushort)100) })); - - // Add the Value Axis. - ValueAxis valAx = plotArea.AppendChild(new ValueAxis(new AxisId() { Val = new UInt32Value(48672768u) }, - new Scaling(new Orientation() - { - Val = new EnumValue( - DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax) - }), - new AxisPosition() { Val = new EnumValue(AxisPositionValues.Left) }, - new MajorGridlines(), - new DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat() { FormatCode = new StringValue("General"), - SourceLinked = new BooleanValue(true) }, new TickLabelPosition() { Val = - new EnumValue(TickLabelPositionValues.NextTo) }, - new CrossingAxis() { Val = new UInt32Value(48650112U) }, new Crosses() { - Val = new EnumValue(CrossesValues.AutoZero) }, new CrossBetween() - { Val = new EnumValue(CrossBetweenValues.Between) })); - // Add the chart Legend. - Legend legend = chart.AppendChild(new Legend(new LegendPosition() - { Val = new EnumValue(LegendPositionValues.Right) }, - new Layout())); - - chart.Append(new PlotVisibleOnly() { Val = new BooleanValue(true) }); - - // Save the chart part. - chartPart.ChartSpace.Save(); -``` +[!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-3) -```vb - barChart.Append(New AxisId() With {.Val = New UInt32Value(48650112UI)}) - barChart.Append(New AxisId() With {.Val = New UInt32Value(48672768UI)}) - - ' Add the Category Axis. - Dim catAx As CategoryAxis = plotArea.AppendChild(Of CategoryAxis) _ - (New CategoryAxis(New AxisId() With {.Val = New UInt32Value(48650112UI)}, _ - New Scaling(New Orientation() With {.Val = New EnumValue(Of _ - DocumentFormat.OpenXml.Drawing.Charts.OrientationValues) _ - (DocumentFormat.Open Xml.Drawing.Charts.OrientationValues.MinMax)}), New AxisPosition() With _ - {.Val = New EnumValue(Of AxisPositionValues)(AxisPositionValues.Bottom)}, _ - New TickLabelPosition() With {.Val = New EnumValue(Of TickLabelPositionValues) _ - (TickLabelPositionValues.NextTo)}, New CrossingAxis() With {.Val = New UInt32Value(48672768UI)}, _ - New Crosses() With {.Val = New EnumValue(Of CrossesValues)(CrossesValues.AutoZero)} _ - , New AutoLabeled() With {.Val = New BooleanValue(True)}, New LabelAlignment()_ - With {.Val = New EnumValue(Of LabelAlignmentValues)(LabelAlignmentValues.Center)} _ - , New LabelOffset() With {.Val = New UInt16Value(CUShort(100))})) - - ' Add the Value Axis. - Dim valAx As ValueAxis = plotArea.AppendChild(Of ValueAxis)(New ValueAxis _ - (New AxisId() With {.Val = New UInt32Value(48672768UI)}, New Scaling(New _ - Orientation() With {.Val = New EnumValue(Of DocumentFormat.OpenXml.Drawing _ - .Charts.OrientationValues)(DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)}), _ - New AxisPosition() With {.Val = New EnumValue(Of AxisPositionValues)(AxisPositionValues.Left)}, _ - New MajorGridlines(), New DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat() With {.FormatCode = _ - New StringValue("General"), .SourceLinked = New BooleanValue(True)}, New TickLabelPosition() With _ - {.Val = New EnumValue(Of TickLabelPositionValues)(TickLabelPositionValues.NextTo)}, New CrossingAxis() _ - With {.Val = New UInt32Value(48650112UI)}, New Crosses() With {.Val = New EnumValue(Of CrossesValues) _ - (CrossesValues.AutoZero)}, New CrossBetween() With {.Val = New EnumValue(Of CrossBetweenValues) _ - (CrossBetweenValues.Between)})) - - ' Add the chart Legend. - Dim legend As Legend = chart.AppendChild(Of Legend)(New Legend(New LegendPosition() _ - With {.Val = New EnumValue(Of LegendPositionValues)(LegendPositionValues.Right)}, New Layout())) - - chart.Append(New PlotVisibleOnly() With {.Val = New BooleanValue(True)}) - - ' Save the chart part. - chartPart.ChartSpace.Save() -``` +[!code-vb[](../../samples/spreadsheet/insert_a_chartto/vb/Program.vb#snippet3)] *** The code positions the chart on the worksheet by creating a [WorksheetDrawing](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.drawingspart.worksheetdrawing.aspx) object and appending a **TwoCellAnchor** object. The **TwoCellAnchor** object specifies how to move or resize the chart if you move the rows and columns between the [FromMarker](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.spreadsheet.frommarker.aspx) and [ToMarker](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.spreadsheet.tomarker.aspx) anchors. The code then creates a [GraphicFrame](https://msdn.microsoft.com/library/office/documentformat.openxml.drawing.spreadsheet.graphicframe.aspx) object to contain the chart and names the chart "Chart 1," and saves the worksheet drawing. ### [C#](#tab/cs-4) -```csharp - // Position the chart on the worksheet using a TwoCellAnchor object. - drawingsPart.WorksheetDrawing = new WorksheetDrawing(); - TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild(new TwoCellAnchor()); - twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId("9"), - new ColumnOffset("581025"), - new RowId("17"), - new RowOffset("114300"))); - twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId("17"), - new ColumnOffset("276225"), - new RowId("32"), - new RowOffset("0"))); - - // Append a GraphicFrame to the TwoCellAnchor object. - DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame graphicFrame = - twoCellAnchor.AppendChild( - new DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame()); - graphicFrame.Macro = ""; - - graphicFrame.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameProperties( - new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties() { Id = new UInt32Value(2u), - Name = "Chart 1" }, new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties())); - - graphicFrame.Append(new Transform(new Offset() { X = 0L, Y = 0L }, - new Extents() { Cx = 0L, Cy = 0L })); - - graphicFrame.Append(new Graphic(new GraphicData(new ChartReference() { Id = drawingsPart.GetIdOfPart(chartPart)}) - { Uri = "https://schemas.openxmlformats.org/drawingml/2006/chart" })); - - twoCellAnchor.Append(new ClientData()); - - // Save the WorksheetDrawing object. - drawingsPart.WorksheetDrawing.Save(); -``` +[!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-4) -```vb - ' Position the chart on the worksheet using a TwoCellAnchor object. - drawingsPart.WorksheetDrawing = New WorksheetDrawing() - Dim twoCellAnchor As TwoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild(Of _ - TwoCellAnchor)(New TwoCellAnchor()) - twoCellAnchor.Append(New DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(New _ - ColumnId("9"), New ColumnOffset("581025"), New RowId("17"), New RowOffset("114300"))) - twoCellAnchor.Append(New DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(New _ - ColumnId("17"), New ColumnOffset("276225"), New RowId("32"), New RowOffset("0"))) - - ' Append a GraphicFrame to the TwoCellAnchor object. - Dim graphicFrame As DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame = _ - twoCellAnchor.AppendChild(Of DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame) _ - (New DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame()) - graphicFrame.Macro = "" - - graphicFrame.Append(New DocumentFormat.OpenXml.Drawing.Spreadsheet _ - .NonVisualGraphicFrameProperties(New DocumentFormat.OpenXml.Drawing.Spreadsheet. _ - NonVisualDrawingProperties() With {.Id = New UInt32Value(2UI), .Name = "Chart 1"}, _ - New DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties())) - - graphicFrame.Append(New Transform(New Offset() With {.X = 0L, .Y = 0L}, _ - New Extents() With {.Cx = 0L, .Cy = 0L})) - - graphicFrame.Append(New Graphic(New GraphicData(New ChartReference() With _ - {.Id = drawingsPart.GetIdOfPart(chartPart)}) With {.Uri = _ - "https://schemas.openxmlformats.org/drawingml/2006/chart"})) - - twoCellAnchor.Append(New ClientData()) - - ' Save the WorksheetDrawing object. - drawingsPart.WorksheetDrawing.Save() -``` +[!code-vb[](../../samples/spreadsheet/insert_a_chartto/vb/Program.vb#snippet4)] *** ## Sample Code -In the following code, you add a clustered column chart to a [SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx) document package using -the data from a [Dictionary\](https://msdn2.microsoft.com/library/xfhwa508) -class. For instance, you can call the method **InsertChartInSpreadsheet** by using this code segment. - -### [C#](#tab/cs-5) -```csharp - string docName = @"C:\Users\Public\Documents\Sheet6.xlsx"; - string worksheetName = "Joe"; - string title = "New Chart"; - Dictionary data = new Dictionary(); - data.Add("abc", 1); - InsertChartInSpreadsheet(docName, worksheetName, title, data); -``` - -### [Visual Basic](#tab/vb-5) -```vb - Dim docName As String = "C:\Users\Public\Documents\Sheet6.xlsx" - Dim worksheetName As String = "Joe" - Dim title As String = "New Chart" - Dim data As New Dictionary(Of String, Integer)() - data.Add("abc", 1) - InsertChartInSpreadsheet(docName, worksheetName, title, data) -``` -*** - - -After you have run the program, take a look the file named "Sheet6.xlsx" to see the inserted chart. - > [!NOTE] > This code can be run only once. You cannot create more than one instance of the chart. The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/insert_a_chartto/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/insert_a_chartto/vb/Program.vb#snippet0)] ## See also -- [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) -[Language-Integrated Query (LINQ)](https://msdn.microsoft.com/library/bb397926.aspx) -[Lambda Expressions](https://msdn.microsoft.com/library/bb531253.aspx) -[Lambda Expressions (C\# Programming Guide)](https://msdn.microsoft.com/library/bb397687.aspx) +[Open XML SDK class library reference](/office/open-xml/open-xml-sdk) diff --git a/docs/spreadsheet/how-to-insert-a-new-worksheet-into-a-spreadsheet.md b/docs/spreadsheet/how-to-insert-a-new-worksheet-into-a-spreadsheet.md index c04087a6..3bb56571 100644 --- a/docs/spreadsheet/how-to-insert-a-new-worksheet-into-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-insert-a-new-worksheet-into-a-spreadsheet.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 12/12/2023 ms.localizationpriority: high --- # Insert a new worksheet into a spreadsheet document @@ -23,133 +23,11 @@ programmatically. -------------------------------------------------------------------------------- -## Getting a SpreadsheetDocument Object -In the Open XML SDK, the [SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx) class represents an -Excel document package. To open and work with an Excel document, you -create an instance of the **SpreadsheetDocument** class from the document. -After you create the instance from the document, you can then obtain -access to the main workbook part that contains the worksheets. The text -in the document is represented in the package as XML using **SpreadsheetML** markup. - -To create the class instance from the document that you call one of the -[Open()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.open.aspx) methods. Several are provided, each -with a different signature. The sample code in this topic uses the [Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562356.aspx) method with a -signature that requires two parameters. The first parameter takes a full -path string that represents the document that you want to open. The -second parameter is either **true** or **false** and represents whether you want the file to -be opened for editing. Any changes that you make to the document will -not be saved if this parameter is **false**. - -The code that calls the **Open** method is -shown in the following **using** statement. - -### [C#](#tab/cs-0) -```csharp - // Open the document for editing. - using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - ' Open the document for editing. - Dim spreadSheet As SpreadsheetDocument = SpreadsheetDocument.Open(docName, True) - Using (spreadSheet) - ' Insert other code here. - End Using -``` -*** - - -The **using** statement provides a recommended -alternative to the typical .Open, .Save, .Close sequence. It ensures -that the **Dispose** method (internal method -used by the Open XML SDK to clean up resources) is automatically called -when the closing brace is reached. The block that follows the **using** statement establishes a scope for the -object that is created or named in the **using** statement, in this case **spreadSheet**. - - --------------------------------------------------------------------------------- -## Basic Structure of a SpreadsheetML Document -The basic document structure of a **SpreadsheetML** document consists of the [Sheets](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheets.aspx) and [Sheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.aspx) elements, which reference the -worksheets in the [Workbook](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.workbook.aspx). A separate XML file is created -for each [Worksheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.worksheet.aspx). For example, the **SpreadsheetML** for a workbook that has two -worksheets name MySheet1 and MySheet2 is located in the Workbook.xml -file and is shown in the following code example. - -```xml - - - - - - - -``` - -The worksheet XML files contain one or more block level elements such as -[SheetData](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheetdata.aspx). **sheetData** represents the cell table and contains -one or more [Row](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.row.aspx) elements. A **row** contains one or more [Cell](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cell.aspx) elements. Each cell contains a [CellValue](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cellvalue.aspx) element that represents the value -of the cell. For example, the **SpreadsheetML** -for the first worksheet in a workbook, that only has the value 100 in -cell A1, is located in the Sheet1.xml file and is shown in the following -code example. - -```xml - - - - - - 100 - - - - -``` - -Using the Open XML SDK, you can create document structure and -content that uses strongly-typed classes that correspond to **SpreadsheetML** elements. You can find these -classes in the **DocumentFormat.OpenXML.Spreadsheet** namespace. The -following table lists the class names of the classes that correspond to -the **workbook**, **sheets**, **sheet**, **worksheet**, and **sheetData** elements. - -| SpreadsheetML Element | Open XML SDK Class | Description | -|---|---|---| -| workbook | DocumentFormat.OpenXml.Spreadsheet.Workbook | The root element for the main document part. | -| sheets | DocumentFormat.OpenXml.Spreadsheet.Sheets | The container for the block level structures such as sheet, fileVersion, and others specified in the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification. | -| sheet | DocumentFormat.OpenXml.Spreadsheet.Sheet | A sheet that points to a sheet definition file. | -| worksheet | DocumentFormat.OpenXml.Spreadsheet.Worksheet | A sheet definition file that contains the sheet data. | -| sheetData | DocumentFormat.OpenXml.Spreadsheet.SheetData | The cell table, grouped together by rows. | -| row | DocumentFormat.OpenXml.Spreadsheet.Row | A row in the cell table. | -| c | DocumentFormat.OpenXml.Spreadsheet.Cell | A cell in a row. | -| v | DocumentFormat.OpenXml.Spreadsheet.CellValue | The value of a cell. | +[!include[Structure](../includes/spreadsheet/structure.md)] -------------------------------------------------------------------------------- ## Sample Code -In the following code, insert a blank [Worksheet](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.worksheetpart.worksheet.aspx) object by adding a blank [WorksheetPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.worksheetpart.aspx) object, generating a unique -ID for the **WorksheetPart** object, and -registering the **WorksheetPart** object in the -[WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.workbookpart.aspx) object contained in a [SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx) document package. To -call the method InsertWorksheet, you can use the following code, which -inserts a worksheet in a file names "Sheet7.xslx," as an example. - -### [C#](#tab/cs-1) -```csharp - string docName = @"C:\Users\Public\Documents\Sheet7.xlsx"; - InsertWorksheet(docName); -``` - -### [Visual Basic](#tab/vb-1) -```vb - Dim docName As String = "C:\Users\Public\Documents\Sheet7.xlsx" - InsertWorksheet(docName) -``` -*** - Following is the complete sample code in both C\# and Visual Basic. @@ -163,10 +41,4 @@ Following is the complete sample code in both C\# and Visual Basic. ## See also -- [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) - -[Language-Integrated Query (LINQ)](https://msdn.microsoft.com/library/bb397926.aspx) - -[Lambda Expressions](https://msdn.microsoft.com/library/bb531253.aspx) - -[Lambda Expressions (C\# Programming Guide)](https://msdn.microsoft.com/library/bb397687.aspx) +[Open XML SDK class library reference](/office/open-xml/open-xml-sdk) diff --git a/docs/spreadsheet/how-to-insert-text-into-a-cell-in-a-spreadsheet.md b/docs/spreadsheet/how-to-insert-text-into-a-cell-in-a-spreadsheet.md index bc18c31a..c86e7e9e 100644 --- a/docs/spreadsheet/how-to-insert-text-into-a-cell-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-insert-text-into-a-cell-in-a-spreadsheet.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 12/12/2023 ms.localizationpriority: high --- # Insert text into a cell in a spreadsheet document @@ -20,55 +20,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to insert text into a cell in a new worksheet in a spreadsheet document programmatically. - - -------------------------------------------------------------------------------- -## Getting a SpreadsheetDocument Object -In the Open XML SDK, the [SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx) class represents an -Excel document package. To open and work with an Excel document, you -create an instance of the **SpreadsheetDocument** class from the document. -After you create the instance from the document, you can then obtain -access to the main workbook part that contains the worksheets. The text -in the document is represented in the package as XML using **SpreadsheetML** markup. - -To create the class instance from the document that you call one of the -[Open()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.open.aspx) overload methods. Several are -provided, each with a different signature. The sample code in this topic -uses the [Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562356.aspx) method with a -signature that requires two parameters. The first parameter takes a full -path string that represents the document that you want to open. The -second parameter is either **true** or **false** and represents whether you want the file to -be opened for editing. Any changes that you make to the document will -not be saved if this parameter is **false**. - -The code that calls the **Open** method is -shown in the following **using** statement. - -### [C#](#tab/cs-0) -```csharp - // Open the document for editing. - using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - ' Open the document for editing. - Using spreadSheet As SpreadsheetDocument = SpreadsheetDocument.Open(docName, True) - ' Insert other code here. - End Using -``` -*** - - -The **using** statement provides a recommended -alternative to the typical .Open, .Save, .Close sequence. It ensures -that the **Dispose** method (internal method -used by the Open XML SDK to clean up resources) is automatically called -when the closing brace is reached. The block that follows the **using** statement establishes a scope for the -object that is created or named in the **using** statement, in this case *spreadSheet*. [!include[Structure](../includes/spreadsheet/structure.md)] @@ -79,82 +31,10 @@ inserts a new [Cell](https://msdn.microsoft.com/library/office/documentformat.op inserts the specified text into that cell. ### [C#](#tab/cs-1) -```csharp - // Given a document name and text, - // inserts a new worksheet and writes the text to cell "A1" of the new worksheet. - public static void InsertText(string docName, string text) - { - // Open the document for editing. - using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true)) - { - // Get the SharedStringTablePart. If it does not exist, create a new one. - SharedStringTablePart shareStringPart; - if (spreadSheet.WorkbookPart.GetPartsOfType().Count() > 0) - { - shareStringPart = spreadSheet.WorkbookPart.GetPartsOfType().First(); - } - else - { - shareStringPart = spreadSheet.WorkbookPart.AddNewPart(); - } - - // Insert the text into the SharedStringTablePart. - int index = InsertSharedStringItem(text, shareStringPart); - - // Insert a new worksheet. - WorksheetPart worksheetPart = InsertWorksheet(spreadSheet.WorkbookPart); - - // Insert cell A1 into the new worksheet. - Cell cell = InsertCellInWorksheet("A", 1, worksheetPart); - - // Set the value of cell A1. - cell.CellValue = new CellValue(index.ToString()); - cell.DataType = new EnumValue(CellValues.SharedString); - - // Save the new worksheet. - worksheetPart.Worksheet.Save(); - } - } -``` +[!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-1) -```vb - ' Given a document name and text, - ' inserts a new worksheet and writes the text to cell "A1" of the new worksheet. - Public Function InsertText(ByVal docName As String, ByVal text As String) - ' Open the document for editing. - Dim spreadSheet As SpreadsheetDocument = SpreadsheetDocument.Open(docName, True) - - Imports (spreadSheet) - ' Get the SharedStringTablePart. If it does not exist, create a new one. - Dim shareStringPart As SharedStringTablePart - - If (spreadSheet.WorkbookPart.GetPartsOfType(Of SharedStringTablePart).Count() > 0) Then - shareStringPart = spreadSheet.WorkbookPart.GetPartsOfType(Of SharedStringTablePart).First() - Else - shareStringPart = spreadSheet.WorkbookPart.AddNewPart(Of SharedStringTablePart)() - End If - - ' Insert the text into the SharedStringTablePart. - Dim index As Integer = InsertSharedStringItem(text, shareStringPart) - - ' Insert a new worksheet. - Dim worksheetPart As WorksheetPart = InsertWorksheet(spreadSheet.WorkbookPart) - - ' Insert cell A1 into the new worksheet. - Dim cell As Cell = InsertCellInWorksheet("A", 1, worksheetPart) - - ' Set the value of cell A1. - cell.CellValue = New CellValue(index.ToString) - cell.DataType = New EnumValue(Of CellValues)(CellValues.SharedString) - - ' Save the new worksheet. - worksheetPart.Worksheet.Save() - - Return 0 - End Imports - End Function -``` +[!code-vb[](../../samples/spreadsheet/insert_textto_a_cell/vb/Program.vb#snippet1)] *** @@ -170,65 +50,10 @@ The following code verifies if the specified text exists in the **SharedStringTa it does not exist. ### [C#](#tab/cs-2) -```csharp - // Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text - // and inserts it into the SharedStringTablePart. If the item already exists, returns its index. - private static int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart) - { - // If the part does not contain a SharedStringTable, create one. - if (shareStringPart.SharedStringTable == null) - { - shareStringPart.SharedStringTable = new SharedStringTable(); - } - - int i = 0; - - // Iterate through all the items in the SharedStringTable. If the text already exists, return its index. - foreach (SharedStringItem item in shareStringPart.SharedStringTable.Elements()) - { - if (item.InnerText == text) - { - return i; - } - - i++; - } - - // The text does not exist in the part. Create the SharedStringItem and return its index. - shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new DocumentFormat.OpenXml.Spreadsheet.Text(text))); - shareStringPart.SharedStringTable.Save(); - - return i; - } -``` +[!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-2) -```vb - ' Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text - ' and inserts it into the SharedStringTablePart. If the item already exists, returns its index. - Private Function InsertSharedStringItem(ByVal text As String, ByVal shareStringPart As SharedStringTablePart) As Integer - ' If the part does not contain a SharedStringTable, create one. - If (shareStringPart.SharedStringTable Is Nothing) Then - shareStringPart.SharedStringTable = New SharedStringTable - End If - - Dim i As Integer = 0 - - ' Iterate through all the items in the SharedStringTable. If the text already exists, return its index. - For Each item As SharedStringItem In shareStringPart.SharedStringTable.Elements(Of SharedStringItem)() - If (item.InnerText = text) Then - Return i - End If - i = (i + 1) - Next - - ' The text does not exist in the part. Create the SharedStringItem and return its index. - shareStringPart.SharedStringTable.AppendChild(New SharedStringItem(New DocumentFormat.OpenXml.Spreadsheet.Text(text))) - shareStringPart.SharedStringTable.Save() - - Return i - End Function -``` +[!code-vb[](../../samples/spreadsheet/insert_textto_a_cell/vb/Program.vb#snippet2)] *** @@ -245,66 +70,10 @@ object by adding a new **WorksheetPart** object to the [WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.workbookpart.aspx) object. ### [C#](#tab/cs-3) -```csharp - // Given a WorkbookPart, inserts a new worksheet. - private static WorksheetPart InsertWorksheet(WorkbookPart workbookPart) - { - // Add a new worksheet part to the workbook. - WorksheetPart newWorksheetPart = workbookPart.AddNewPart(); - newWorksheetPart.Worksheet = new Worksheet(new SheetData()); - newWorksheetPart.Worksheet.Save(); - - Sheets sheets = workbookPart.Workbook.GetFirstChild(); - string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart); - - // Get a unique ID for the new sheet. - uint sheetId = 1; - if (sheets.Elements().Count() > 0) - { - sheetId = sheets.Elements().Select(s => s.SheetId.Value).Max() + 1; - } - - string sheetName = "Sheet" + sheetId; - - // Append the new worksheet and associate it with the workbook. - Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName }; - sheets.Append(sheet); - workbookPart.Workbook.Save(); - - return newWorksheetPart; - } -``` +[!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-3) -```vb - ' Given a WorkbookPart, inserts a new worksheet. - Private Function InsertWorksheet(ByVal workbookPart As WorkbookPart) As WorksheetPart - ' Add a new worksheet part to the workbook. - Dim newWorksheetPart As WorksheetPart = workbookPart.AddNewPart(Of WorksheetPart)() - newWorksheetPart.Worksheet = New Worksheet(New SheetData) - newWorksheetPart.Worksheet.Save() - Dim sheets As Sheets = workbookPart.Workbook.GetFirstChild(Of Sheets)() - Dim relationshipId As String = workbookPart.GetIdOfPart(newWorksheetPart) - - ' Get a unique ID for the new sheet. - Dim sheetId As UInteger = 1 - If (sheets.Elements(Of Sheet).Count() > 0) Then - sheetId = sheets.Elements(Of Sheet).Select(Function(s) s.SheetId.Value).Max() + 1 - End If - - Dim sheetName As String = ("Sheet" + sheetId.ToString()) - - ' Add the new worksheet and associate it with the workbook. - Dim sheet As Sheet = New Sheet - sheet.Id = relationshipId - sheet.SheetId = sheetId - sheet.Name = sheetName - sheets.Append(sheet) - workbookPart.Workbook.Save() - - Return newWorksheetPart - End Function -``` +[!code-vb[](../../samples/spreadsheet/insert_textto_a_cell/vb/Program.vb#snippet3)] *** @@ -319,137 +88,26 @@ In the following code, insert a new **Cell** object into a **Worksheet** object. ### [C#](#tab/cs-4) -```csharp - // Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet. - // If the cell already exists, returns it. - private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart) - { - Worksheet worksheet = worksheetPart.Worksheet; - SheetData sheetData = worksheet.GetFirstChild(); - string cellReference = columnName + rowIndex; - - // If the worksheet does not contain a row with the specified row index, insert one. - Row row; - if (sheetData.Elements().Where(r => r.RowIndex == rowIndex).Count() != 0) - { - row = sheetData.Elements().Where(r => r.RowIndex == rowIndex).First(); - } - else - { - row = new Row() { RowIndex = rowIndex }; - sheetData.Append(row); - } - - // If there is not a cell with the specified column name, insert one. - if (row.Elements().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0) - { - return row.Elements().Where(c => c.CellReference.Value == cellReference).First(); - } - else - { - // Cells must be in sequential order according to CellReference. Determine where to insert the new cell. - Cell refCell = null; - foreach (Cell cell in row.Elements()) - { - if (cell.CellReference.Value.Length == cellReference.Length) - { - if (string.Compare(cell.CellReference.Value, cellReference, true) > 0) - { - refCell = cell; - break; - } - } - } - - Cell newCell = new Cell() { CellReference = cellReference }; - row.InsertBefore(newCell, refCell); - - worksheet.Save(); - return newCell; - } - } -``` +[!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-4) -```vb - ' Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet. - ' If the cell already exists, return it. - Private Function InsertCellInWorksheet(ByVal columnName As String, ByVal rowIndex As UInteger, ByVal worksheetPart As WorksheetPart) As Cell - Dim worksheet As Worksheet = worksheetPart.Worksheet - Dim sheetData As SheetData = worksheet.GetFirstChild(Of SheetData)() - Dim cellReference As String = (columnName + rowIndex.ToString()) - - ' If the worksheet does not contain a row with the specified row index, insert one. - Dim row As Row - If (sheetData.Elements(Of Row).Where(Function(r) r.RowIndex.Value = rowIndex).Count() <> 0) Then - row = sheetData.Elements(Of Row).Where(Function(r) r.RowIndex.Value = rowIndex).First() - Else - row = New Row() - row.RowIndex = rowIndex - sheetData.Append(row) - End If - - ' If there is not a cell with the specified column name, insert one. - If (row.Elements(Of Cell).Where(Function(c) c.CellReference.Value = columnName + rowIndex.ToString()).Count() > 0) Then - Return row.Elements(Of Cell).Where(Function(c) c.CellReference.Value = cellReference).First() - Else - ' Cells must be in sequential order according to CellReference. Determine where to insert the new cell. - Dim refCell As Cell = Nothing - For Each cell As Cell In row.Elements(Of Cell)() - If (String.Compare(cell.CellReference.Value, cellReference, True) > 0) Then - refCell = cell - Exit For - End If - Next - - Dim newCell As Cell = New Cell - newCell.CellReference = cellReference - - row.InsertBefore(newCell, refCell) - worksheet.Save() - - Return newCell - End If - End Function -``` +[!code-vb[](../../samples/spreadsheet/insert_textto_a_cell/vb/Program.vb#snippet4)] *** -------------------------------------------------------------------------------- ## Sample Code -The following code sample is used to insert a new worksheet and write -the text to the cell "A1" of the new worksheet for a specific -spreadsheet document named "Sheet8.xlsx." To call the **InsertText** method you can use the following code -as an example. - -### [C#](#tab/cs-5) -```csharp - InsertText(@"C:\Users\Public\Documents\Sheet8.xlsx", "Inserted Text"); -``` - -### [Visual Basic](#tab/vb-5) -```vb - InsertText("C:\Users\Public\Documents\Sheet8.xlsx", "Inserted Text") -``` -*** - The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/insert_textto_a_cell/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/insert_textto_a_cell/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- ## See also [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) - -[Language-Integrated Query (LINQ)](https://msdn.microsoft.com/library/bb397926.aspx) - -[Lambda Expressions](https://msdn.microsoft.com/library/bb531253.aspx) - -[Lambda Expressions (C\# Programming Guide)](https://msdn.microsoft.com/library/bb397687.aspx) diff --git a/docs/spreadsheet/how-to-merge-two-adjacent-cells-in-a-spreadsheet.md b/docs/spreadsheet/how-to-merge-two-adjacent-cells-in-a-spreadsheet.md index 3e2725c0..64d8c38c 100644 --- a/docs/spreadsheet/how-to-merge-two-adjacent-cells-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-merge-two-adjacent-cells-in-a-spreadsheet.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 12/12/2023 ms.localizationpriority: high --- # Merge two adjacent cells in a spreadsheet document @@ -20,114 +20,9 @@ This topic shows how to use the classes in the Open XML SDK for Office to merge two adjacent cells in a spreadsheet document programmatically. - - -------------------------------------------------------------------------------- -## Getting a SpreadsheetDocument Object - -In the Open XML SDK, the **[SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx)** class represents an -Excel document package. To open and work with an Excel document, you -create an instance of the **SpreadsheetDocument** class from the document. -After you create the instance from the document, you can then obtain -access to the main workbook part that contains the worksheets. The text -in the document is represented in the package as XML using **SpreadsheetML** markup. - -To create the class instance from the document that you call one of the -**[Open()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.open.aspx)** overload methods. Several are -provided, each with a different signature. The sample code in this topic -uses the **[Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562356.aspx)** method with a -signature that requires two parameters. The first parameter takes a full -path string that represents the document that you want to open. The -second parameter is either **true** or **false** and represents whether you want the file to -be opened for editing. Any changes that you make to the document will -not be saved if this parameter is **false**. - -The code that calls the **Open** method is -shown in the following **using** statement. - -### [C#](#tab/cs-0) -```csharp - // Open the document for editing. - using (SpreadsheetDocument document = SpreadsheetDocument.Open(docName, true)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - ' Open the document for editing. - Using document As SpreadsheetDocument = SpreadsheetDocument.Open(docName, True) - ' Insert other code here. - End Using -``` -*** - -The **using** statement provides a recommended -alternative to the typical .Open, .Save, .Close sequence. It ensures -that the **Dispose** method (internal method -used by the Open XML SDK to clean up resources) is automatically called -when the closing brace is reached. The block that follows the **using** statement establishes a scope for the -object that is created or named in the **using** statement, in this case **document**. - - --------------------------------------------------------------------------------- -## Basic Structure of a SpreadsheetML Document - -The basic document structure of a **SpreadsheetML** document consists of the **[Sheets](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheets.aspx)** and **[Sheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.aspx)** elements, which reference the -worksheets in the **Workbook**. -A separate XML file is created for each **Worksheet**. -For example, the **SpreadsheetML** for a -workbook that has two worksheets name MySheet1 and MySheet2 is located -in the Workbook.xml file and is shown in the following code example. - -```xml - - - - - - - -``` - -The worksheet XML files contain one or more block level elements such as -**[SheetData](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheetdata.aspx)**. **sheetData** represents the cell table and contains -one or more **[Row](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.row.aspx)** elements. A **row** contains one or more **[Cell](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cell.aspx)** elements. Each cell contains a **[CellValue](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.cellvalue.aspx)** element that represents the value -of the cell. For example, the SpreadsheetML for the first worksheet in a -workbook, that only has the value 100 in cell A1, is located in the -Sheet1.xml file and is shown in the following code example. - -```xml - - - - - - 100 - - - - -``` - -Using the Open XML SDK, you can create document structure and -content that uses strongly-typed classes that correspond to **SpreadsheetML** elements. You can find these -classes in the **DocumentFormat.OpenXML.Spreadsheet** namespace. The -following table lists the class names of the classes that correspond to -the **workbook**, **sheets**, **sheet**, **worksheet**, and **sheetData** elements. - -| SpreadsheetML Element | Open XML SDK Class | Description | -|---|---|---| -| workbook | DocumentFormat.OpenXML.Spreadsheet.Workbook | The root element for the main document part. | -| sheets | DocumentFormat. OpenXML.Spreadsheet.Sheets | The container for the block level structures such as sheet, fileVersion, and others specified in the [ISO/IEC 29500](https://www.iso.org/standard/71691.html) specification. | -| sheet | DocumentFormat.OpenXML.Spreadsheet.Sheet | A sheet that points to a sheet definition file. | -| worksheet | DocumentFormat.OpenXML.Spreadsheet.Worksheet | A sheet definition file that contains the sheet data. | -| sheetData | DocumentFormat.OpenXML.Spreadsheet.SheetData | The cell table, grouped together by rows. | -| row | DocumentFormat.OpenXml.Spreadsheet.Row | A row in the cell table. | -| c | DocumentFormat.OpenXml.Spreadsheet.Cell | A cell in a row. | -| v | DocumentFormat.OpenXml.Spreadsheet.CellValue | The value of a cell. | +[!include[Structure](../includes/spreadsheet/structure.md)] -------------------------------------------------------------------------------- @@ -137,47 +32,17 @@ The following code merges two adjacent cells in a **[SpreadsheetDocument](https: merging two cells, only the content from one of the cells is preserved. In left-to-right languages, the content in the upper-left cell is preserved. In right-to-left languages, the content in the upper-right -cell is preserved. You can call the **MergeTwoCells** method in your program by using the -following code example, which merges the two cells B2 and C2 in a sheet -named "Jane," in a file named "Sheet9.xlsx." - -### [C#](#tab/cs-1) -```csharp - string docName = @"C:\Users\Public\Documents\Sheet9.xlsx"; - string sheetName = "Jane"; - string cell1Name = "B2"; - string cell2Name = "C2"; - MergeTwoCells(docName, sheetName, cell1Name, cell2Name); -``` - -### [Visual Basic](#tab/vb-1) -```vb - Dim docName As String = "C:\Users\Public\Documents\Sheet9.xlsx" - Dim sheetName As String = "Jane" - Dim cell1Name As String = "B2" - Dim cell2Name As String = "C2" - MergeTwoCells(docName, sheetName, cell1Name, cell2Name) -``` -*** - +cell is preserved. The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- ## See also - - - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) - -[Language-Integrated Query (LINQ)](https://msdn.microsoft.com/library/bb397926.aspx) - -[Lambda Expressions](https://msdn.microsoft.com/library/bb531253.aspx) - -[Lambda Expressions (C\# Programming Guide)](https://msdn.microsoft.com/library/bb397687.aspx) diff --git a/docs/spreadsheet/how-to-open-a-spreadsheet-document-for-read-only-access.md b/docs/spreadsheet/how-to-open-a-spreadsheet-document-for-read-only-access.md index 323e0539..fca64e09 100644 --- a/docs/spreadsheet/how-to-open-a-spreadsheet-document-for-read-only-access.md +++ b/docs/spreadsheet/how-to-open-a-spreadsheet-document-for-read-only-access.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 12/12/2023 ms.localizationpriority: high --- # Open a spreadsheet document for read-only access @@ -71,16 +71,10 @@ The following code example calls the **Open** Method. ### [C#](#tab/cs-0) -```csharp - // Open a SpreadsheetDocument for read-only access based on a filepath. - using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filepath, false)) -``` +[!code-csharp[](../../samples/spreadsheet/open_for_read_only_access/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - ' Open a SpreadsheetDocument for read-only access based on a filepath. - Using spreadsheetDocument As SpreadsheetDocument = SpreadsheetDocument.Open(filepath, False) -``` +[!code-vb[](../../samples/spreadsheet/open_for_read_only_access/vb/Program.vb#snippet1)] *** @@ -94,19 +88,10 @@ document. The following code example opens a document based on a stream. ### [C#](#tab/cs-1) -```csharp - Stream stream = File.Open(strDoc, FileMode.Open); - // Open a SpreadsheetDocument for read-only access based on a stream. - using (SpreadsheetDocument spreadsheetDocument = - SpreadsheetDocument.Open(stream, false)) -``` +[!code-csharp[](../../samples/spreadsheet/open_for_read_only_access/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Dim stream As Stream = File.Open(strDoc, FileMode.Open) - ' Open a SpreadsheetDocument for read-only access based on a stream. - Using spreadsheetDocument As SpreadsheetDocument = SpreadsheetDocument.Open(stream, False) -``` +[!code-vb[](../../samples/spreadsheet/open_for_read_only_access/vb/Program.vb#snippet2)] *** @@ -124,43 +109,10 @@ example in the sample code. The following code example performs this operation. ### [C#](#tab/cs-2) -```csharp - // Open System.IO.Packaging.Package. - Package spreadsheetPackage = Package.Open(filepath, FileMode.Open, FileAccess.Read); - - // Open a SpreadsheetDocument based on a package. - using (SpreadsheetDocument spreadsheetDocument = - SpreadsheetDocument.Open(spreadsheetPackage)) -``` +[!code-csharp[](../../samples/spreadsheet/open_for_read_only_access/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - ' Open System.IO.Packaging.Package. - Dim spreadsheetPackage As Package = Package.Open(filepath, FileMode.Open, FileAccess.Read) - - ' Open a SpreadsheetDocument based on a package. - Using spreadsheetDocument As SpreadsheetDocument = SpreadsheetDocument.Open(spreadsheetPackage) -``` -*** - - -After you open the spreadsheet document package, you can access the main -workbook part. To access the main workbook part, you assign a reference -to the existing workbook part, as shown in the following code example. - -### [C#](#tab/cs-3) -```csharp - // Assign a reference to the existing workbook part. - WorkbookPart wbPart = document.WorkbookPart; -``` - -### [Visual Basic](#tab/vb-3) -```vb - ' Assign a reference to the existing workbook part. - Dim wbPart As WorkbookPart = document.WorkbookPart -``` -*** - +[!code-vb[](../../samples/spreadsheet/open_for_read_only_access/vb/Program.vb#snippet3)] --------------------------------------------------------------------------------- ## Basic Document Structure @@ -220,28 +172,14 @@ v|DocumentFormat.OpenXml.Spreadsheet.CellValue|The value of a cell. -------------------------------------------------------------------------------- ## Sample Code -The following code sample is used to open a Spreadsheet Document for -Read-only Access. You can call the **OpenSpreadsheetDocumentReadonly** method by using -the following code, which opens the file "Sheet10.xlsx," as an example. - -### [C#](#tab/cs-4) -```csharp - OpenSpreadsheetDocumentReadonly(@"C:\Users\Public\Documents\Sheet10.xlsx"); -``` - -### [Visual Basic](#tab/vb-4) -```vb - OpenSpreadsheetDocumentReadonly("C:\Users\Public\Documents\Sheet10.xlsx") -``` -*** The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/open_for_read_only_access/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/open_for_read_only_access/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/open_for_read_only_access/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/open_for_read_only_access/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- ## See also diff --git a/docs/spreadsheet/how-to-open-a-spreadsheet-document-from-a-stream.md b/docs/spreadsheet/how-to-open-a-spreadsheet-document-from-a-stream.md index 6b9f5b5e..c06478e6 100644 --- a/docs/spreadsheet/how-to-open-a-spreadsheet-document-from-a-stream.md +++ b/docs/spreadsheet/how-to-open-a-spreadsheet-document-from-a-stream.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 12/05/2023 ms.localizationpriority: high --- # Open a spreadsheet document from a stream @@ -36,59 +36,7 @@ Open XML SDK. -------------------------------------------------------------------------------- -## Getting a SpreadsheetDocument Object - -In the Open XML SDK, the [SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx) class represents an -Excel document package. To open and work with an Excel document, you -create an instance of the **SpreadsheetDocument** class from the document. -After you create the instance from the document, you can then obtain -access to the main workbook part that contains the worksheets. The text -in the document is represented in the package as XML using SpreadsheetML -markup. - -To create the class instance from the document, you call one of the -[Open()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.open.aspx) methods. Several are provided, each -with a different signature. The sample code in this topic uses the [Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562356.aspx) method with a -signature that requires two parameters. The first parameter takes a full -path string that represents the document that you want to open. The -second parameter is either **true** or **false** and represents whether you want the file to -be opened for editing. Any changes that you make to the document will -not be saved if this parameter is **false**. - -The code that calls the **Open** method is -shown in the following example. - -### [C#](#tab/cs-0) -```csharp - // Open the document for editing. - using (SpreadsheetDocument document = SpreadsheetDocument.Open(docName, true)) -``` - -### [Visual Basic](#tab/vb-0) -```vb - ' Open the document for editing. - Using document As SpreadsheetDocument = SpreadsheetDocument.Open(docName, True) -``` -*** - - -After you have opened the spreadsheet document package, you can add a -row to a sheet in the workbook. Each workbook has a workbook part and at -least one [Worksheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.worksheet.aspx). To access the [Workbook](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.workbook.aspx) assign a reference to the existing -document body, represented by the [WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.workbook.workbookpart.aspx), as shown in the following -code example. - -### [C#](#tab/cs-1) -```csharp - WorkbookPart wbPart = document.WorkbookPart; -``` - -### [Visual Basic](#tab/vb-1) -```vb - Dim wbPart As WorkbookPart = document.WorkbookPart -``` -*** - +## The SpreadsheetDocument Object The basic document structure of a SpreadsheetML document consists of the [Sheets](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheets.aspx) and [Sheet](https://msdn.microsoft.com/library/office/documentformat.openxml.spreadsheet.sheet.aspx) elements, which reference the @@ -154,20 +102,10 @@ create a new [WorksheetPart](https://msdn.microsoft.com/library/office/documentf adds the new **WorksheetPart**. ### [C#](#tab/cs-2) -```csharp - // Add a new worksheet. - WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart(); - newWorksheetPart.Worksheet = new Worksheet(new SheetData()); - newWorksheetPart.Worksheet.Save(); -``` +[!code-csharp[](../../samples/spreadsheet/open_from_a_stream/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-2) -```vb - ' Add a new worksheet. - Dim newWorksheetPart As WorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart(Of WorksheetPart)() - newWorksheetPart.Worksheet = New Worksheet(New SheetData()) - newWorksheetPart.Worksheet.Save() -``` +[!code-vb[](../../samples/spreadsheet/open_from_a_stream/vb/Program.vb#snippet1)] *** @@ -175,26 +113,13 @@ adds the new **WorksheetPart**. ## Sample Code In this example, the **OpenAndAddToSpreadsheetStream** method can be used to open a spreadsheet document from an already open stream and append -some text to it. In your program, you can use the following example to -call the **OpenAndAddToSpreadsheetStream** -method that uses a file named Sheet11.xslx. +some text to it. The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs-3) -```csharp - string strDoc = @"C:\Users\Public\Documents\Sheet11.xlsx"; - ; - Stream stream = File.Open(strDoc, FileMode.Open); - OpenAndAddToSpreadsheetStream(stream); - stream.Close(); -``` +[!code-csharp[](../../samples/spreadsheet/open_from_a_stream/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-3) -```vb - Dim strDoc As String = "C:\Users\Public\Documents\Sheet11.xlsx" - Dim stream As Stream = File.Open(strDoc, FileMode.Open) - OpenAndAddToSpreadsheetStream(stream) - stream.Close() -``` +[!code-vb[](../../samples/spreadsheet/open_from_a_stream/vb/Program.vb#snippet2)] *** @@ -204,10 +129,10 @@ close the stream passed to it. The calling code must do that. The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/open_from_a_stream/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/open_from_a_stream/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/open_from_a_stream/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/open_from_a_stream/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- ## See also diff --git a/docs/spreadsheet/how-to-parse-and-read-a-large-spreadsheet.md b/docs/spreadsheet/how-to-parse-and-read-a-large-spreadsheet.md index 283b28eb..3c9a503f 100644 --- a/docs/spreadsheet/how-to-parse-and-read-a-large-spreadsheet.md +++ b/docs/spreadsheet/how-to-parse-and-read-a-large-spreadsheet.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 12/05/2023 ms.localizationpriority: high --- # Parse and read a large spreadsheet document @@ -22,68 +22,6 @@ about the basic structure of a **SpreadsheetML** document, see [Structure of a S [!include[Add-ins note](../includes/addinsnote.md)] -You must use the following **using** directives -or **Imports** statements to compile the code -in this topic. - -### [C#](#tab/cs-0) -```csharp - using System; - using System.Linq; - using DocumentFormat.OpenXml; - using DocumentFormat.OpenXml.Packaging; - using DocumentFormat.OpenXml.Spreadsheet; -``` - -### [Visual Basic](#tab/vb-0) -```vb - Imports System - Imports System.Linq - Imports DocumentFormat.OpenXml - Imports DocumentFormat.OpenXml.Packaging - Imports DocumentFormat.OpenXml.Spreadsheet -``` -*** - - --------------------------------------------------------------------------------- -## Getting a SpreadsheetDocument Object -In the Open XML SDK, the [SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx) class represents an -Excel document package. To open and work with an Excel document, you -create an instance of the **SpreadsheetDocument** class from the document. -After you create this instance, you can use it to obtain access to the -main workbook part that contains the worksheets. The content in the -document is represented in the package as XML using **SpreadsheetML** markup. - -To create the class instance, you call one of the overloads of the [Open()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.open.aspx) method. The following code sample -shows how to use the [Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562356.aspx) overload. The first -parameter takes a string that represents the full path to the document -to open. The second parameter takes a value of **true** or **false** and -represents whether or not you want the file to be opened for editing. In -this example, the parameter is **false** -because the document is opened as read-only. - -### [C#](#tab/cs-1) -```csharp - // Open the document as read-only. - using (SpreadsheetDocument spreadsheetDocument = - SpreadsheetDocument.Open(fileName, false)) - { - // Code removed here. - } -``` - -### [Visual Basic](#tab/vb-1) -```vb - ' Open the document as read-only. - Using spreadsheetDocument As SpreadsheetDocument = _ - SpreadsheetDocument.Open(filename, False) - ' Code removed here. - End Using -``` -*** - - -------------------------------------------------------------------------------- ## Approaches to Parsing Open XML Files The Open XML SDK provides two approaches to parsing Open XML files. You @@ -101,34 +39,10 @@ The following code segment is used to read a very large Excel file using the DOM approach. ### [C#](#tab/cs-2) -```csharp - WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; - WorksheetPart worksheetPart = workbookPart.WorksheetParts.First(); - SheetData sheetData = worksheetPart.Worksheet.Elements().First(); - string text; - foreach (Row r in sheetData.Elements()) - { - foreach (Cell c in r.Elements()) - { - text = c.CellValue.Text; - Console.Write(text + " "); - } - } -``` +[!code-csharp[](../../samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-2) -```vb - Dim workbookPart As WorkbookPart = spreadsheetDocument.WorkbookPart - Dim worksheetPart As WorksheetPart = workbookPart.WorksheetParts.First() - Dim sheetData As SheetData = worksheetPart.Worksheet.Elements(Of SheetData)().First() - Dim text As String - For Each r As Row In sheetData.Elements(Of Row)() - For Each c As Cell In r.Elements(Of Cell)() - text = c.CellValue.Text - Console.Write(text & " ") - Next - Next -``` +[!code-vb[](../../samples/spreadsheet/parse_and_read_a_large_spreadsheet/vb/Program.vb#snippet1)] *** @@ -137,36 +51,10 @@ sample (reading a very large Excel file), but uses the SAX approach. This is the recommended approach for reading very large files. ### [C#](#tab/cs-3) -```csharp - WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; - WorksheetPart worksheetPart = workbookPart.WorksheetParts.First(); - - OpenXmlReader reader = OpenXmlReader.Create(worksheetPart); - string text; - while (reader.Read()) - { - if (reader.ElementType == typeof(CellValue)) - { - text = reader.GetText(); - Console.Write(text + " "); - } - } -``` +[!code-csharp[](../../samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-3) -```vb - Dim workbookPart As WorkbookPart = spreadsheetDocument.WorkbookPart - Dim worksheetPart As WorksheetPart = workbookPart.WorksheetParts.First() - - Dim reader As OpenXmlReader = OpenXmlReader.Create(worksheetPart) - Dim text As String - While reader.Read() - If reader.ElementType = GetType(CellValue) Then - text = reader.GetText() - Console.Write(text & " ") - End If - End While -``` +[!code-vb[](../../samples/spreadsheet/parse_and_read_a_large_spreadsheet/vb/Program.vb#snippet2)] *** @@ -184,30 +72,20 @@ method separately by commenting the call to the one you would like to exclude. ### [C#](#tab/cs-4) -```csharp - String fileName = @"C:\Users\Public\Documents\BigFile.xlsx"; - // Comment one of the following lines to test the method separately. - ReadExcelFileDOM(fileName); // DOM - ReadExcelFileSAX(fileName); // SAX -``` +[!code-csharp[](../../samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-4) -```vb - Dim fileName As String = "C:\Users\Public\Documents\BigFile.xlsx" - ' Comment one of the following lines to test each method separately. - ReadExcelFileDOM(fileName) ' DOM - ReadExcelFileSAX(fileName) ' SAX -``` +[!code-vb[](../../samples/spreadsheet/parse_and_read_a_large_spreadsheet/vb/Program.vb#snippet3)] *** The following is the complete code sample in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/parse_and_read_a_large_spreadsheet/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/parse_and_read_a_large_spreadsheet/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- ## See also diff --git a/docs/spreadsheet/how-to-retrieve-a-dictionary-of-all-named-ranges-in-a-spreadsheet.md b/docs/spreadsheet/how-to-retrieve-a-dictionary-of-all-named-ranges-in-a-spreadsheet.md index c16e418a..0c3e347b 100644 --- a/docs/spreadsheet/how-to-retrieve-a-dictionary-of-all-named-ranges-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-retrieve-a-dictionary-of-all-named-ranges-in-a-spreadsheet.md @@ -12,7 +12,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 12/05/2023 ms.localizationpriority: medium --- # Retrieve a dictionary of all named ranges in a spreadsheet document @@ -23,112 +23,25 @@ and ranges of all defined names in an Microsoft Excel 2010 or Microsoft Excel 2013 workbook. It contains an example **GetDefinedNames** method to illustrate this task. - - ## GetDefinedNames Method -The **GetDefinedNames** procedure accepts a +The **GetDefinedNames** method accepts a single parameter that indicates the name of the document from which to -retrieve the defined names. The procedure returns an +retrieve the defined names. The method returns an [Dictionary](https://msdn.microsoft.com/library/xfhwa508.aspx) instance that contains information about the defined names within the specified workbook, which may be empty if there are no defined names. -### [C#](#tab/cs-0) -```csharp - public static Dictionary - GetDefinedNames(String fileName) -``` - -### [Visual Basic](#tab/vb-0) -```vb - Public Function GetDefinedNames( - ByVal fileName As String) As Dictionary(Of String, String) -``` -*** - - -The method examines the workbook that you specify, looking for the part -that contains defined names. If it exists, the code iterates through all -the contents of the part, adding the name and value for each defined -name to the returned dictionary. - -## Calling the Sample Method - -To call the sample method, pass a string that contains the name of the -file from which to retrieve the defined names. The following code -example passes a string that contains the name of the file from which to -retrieve the defined names and iterates through the returned dictionary, -and displays the key and value from each item. - -### [C#](#tab/cs-1) -```csharp - var result = - GetDefinedNames(@"C:\Users\Public\Documents\definednames.xlsx"); - foreach (var dn in result) - Console.WriteLine("{0} {1}", dn.Key, dn.Value); -``` - -### [Visual Basic](#tab/vb-1) -```vb - Dim result = - GetDefinedNames("C:\Users\Public\Documents\definednames.xlsx") - For Each dn In result - Console.WriteLine("{0}: {1}", dn.Key, dn.Value) -``` -*** - - ## How the Code Works -The code starts by creating a variable named **returnValue** that the method will return before it exits. - -### [C#](#tab/cs-2) -```csharp - // Given a workbook name, return a dictionary of defined names. - // The pairs include the range name and a string representing the range. - var returnValue = new Dictionary(); - // Code removed here… - return returnValue; -``` - -### [Visual Basic](#tab/vb-2) -```vb - ' Given a workbook name, return a dictionary of defined names. - ' The pairs include the range name and a string representing the range. - Dim returnValue As New Dictionary(Of String, String) - ' Code removed here… - Return returnValue -``` -*** - - -The code continues by opening the spreadsheet document, using the **Open** method and indicating that the -document should be open for read-only access (the final false parameter). Given the open workbook, the code uses the **WorkbookPart** property to navigate to the main workbook part. The code stores this reference in a variable named **wbPart**. +The code opens the spreadsheet document, using the **Open** method, indicating that the +document should be open for read-only access with the final false parameter. Given the open workbook, the code uses the **WorkbookPart** property to navigate to the main workbook part. The code stores this reference in a variable named **wbPart**. ### [C#](#tab/cs-3) -```csharp - // Open the spreadsheet document for read-only access. - using (SpreadsheetDocument document = - SpreadsheetDocument.Open(fileName, false)) - { - // Retrieve a reference to the workbook part. - var wbPart = document.WorkbookPart; - // Code removed here. - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-3) -```vb - ' Open the spreadsheet document for read-only access. - Using document As SpreadsheetDocument = - SpreadsheetDocument.Open(fileName, False) - - ' Retrieve a reference to the workbook part. - Dim wbPart As WorkbookPart = document.WorkbookPart - ' Code removed here… - End Using -``` +[!code-vb[](../../samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/vb/Program.vb#snippet1)] *** @@ -139,30 +52,10 @@ Given the workbook part, the next step is simple. The code uses the defined names that are contained within the workbook. If the property returns a non-null value, the code then iterates through the collection, retrieving information about each named part and adding the key name) and value (range description) to the dictionary for each defined name. ### [C#](#tab/cs-4) -```csharp - // Retrieve a reference to the defined names collection. - DefinedNames definedNames = wbPart.Workbook.DefinedNames; - - // If there are defined names, add them to the dictionary. - if (definedNames != null) - { - foreach (DefinedName dn in definedNames) - returnValue.Add(dn.Name.Value, dn.Text); - } -``` +[!code-csharp[](../../samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-4) -```vb - ' Retrieve a reference to the defined names collection. - Dim definedNames As DefinedNames = wbPart.Workbook.DefinedNames - - ' If there are defined names, add them to the dictionary. - If definedNames IsNot Nothing Then - For Each dn As DefinedName In definedNames - returnValue.Add(dn.Name.Value, dn.Text) - Next - End If -``` +[!code-vb[](../../samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/vb/Program.vb#snippet2)] *** @@ -171,10 +64,10 @@ defined names that are contained within the workbook. If the property returns a The following is the complete **GetDefinedNames** code sample in C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/vb/Program.vb#snippet0)] ## See also diff --git a/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md b/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md index a8b0d587..4572bd72 100644 --- a/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md @@ -12,7 +12,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 12/05/2023 ms.localizationpriority: high --- # Retrieve a list of the hidden rows or columns in a spreadsheet document diff --git a/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-worksheets-in-a-spreadsheet.md b/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-worksheets-in-a-spreadsheet.md index baa59eae..87f77f01 100644 --- a/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-worksheets-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-retrieve-a-list-of-the-hidden-worksheets-in-a-spreadsheet.md @@ -10,7 +10,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 11/29/2023 ms.localizationpriority: medium --- diff --git a/docs/spreadsheet/how-to-retrieve-a-list-of-the-worksheets-in-a-spreadsheet.md b/docs/spreadsheet/how-to-retrieve-a-list-of-the-worksheets-in-a-spreadsheet.md index 67330c29..ccc65726 100644 --- a/docs/spreadsheet/how-to-retrieve-a-list-of-the-worksheets-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-retrieve-a-list-of-the-worksheets-in-a-spreadsheet.md @@ -12,7 +12,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 11/27/2023 ms.localizationpriority: high --- # Retrieve a list of the worksheets in a spreadsheet document diff --git a/docs/spreadsheet/how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md b/docs/spreadsheet/how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md index 6816f8d9..a3ce0be8 100644 --- a/docs/spreadsheet/how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md @@ -10,7 +10,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 11/20/2023 ms.localizationpriority: high --- diff --git a/docs/word/how-to-set-the-font-for-a-text-run.md b/docs/word/how-to-set-the-font-for-a-text-run.md index 2b14d19a..87065d56 100644 --- a/docs/word/how-to-set-the-font-for-a-text-run.md +++ b/docs/word/how-to-set-the-font-for-a-text-run.md @@ -23,18 +23,7 @@ document programmatically. -------------------------------------------------------------------------------- -## Packages and Document Parts -An Open XML document is stored as a package, whose format is defined by -[ISO/IEC 29500-2](https://www.iso.org/standard/71691.html). The -package can have multiple parts with relationships between them. The -relationship between parts controls the category of the document. A -document can be defined as a word-processing document if its -package-relationship item contains a relationship to a main document -part. If its package-relationship item contains a relationship to a -presentation part it can be defined as a presentation document. If its -package-relationship item contains a relationship to a workbook part, it -is defined as a spreadsheet document. In this how-to topic, you will use -a word-processing document package. +[!include[Structure](../includes/word/packages-and-document-parts.md)] -------------------------------------------------------------------------------- diff --git a/samples/spreadsheet/insert_a_chartto/cs/Program.cs b/samples/spreadsheet/insert_a_chartto/cs/Program.cs index 07ad189a..ecd759df 100644 --- a/samples/spreadsheet/insert_a_chartto/cs/Program.cs +++ b/samples/spreadsheet/insert_a_chartto/cs/Program.cs @@ -1,4 +1,4 @@ - +// using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Drawing; using DocumentFormat.OpenXml.Drawing.Charts; @@ -8,16 +8,15 @@ using System.Collections.Generic; using System.Linq; -InsertChartInSpreadsheet(args[0], args[1], args[2], new Dictionary() { { "First", 1 }, { "Second", 2 }, { "Third", 3 } }); // Given a document name, a worksheet name, a chart title, and a Dictionary collection of text keys // and corresponding integer data, creates a column chart with the text as the series and the integers as the values. -static void InsertChartInSpreadsheet(string docName, string worksheetName, string title, -Dictionary data) +static void InsertChartInSpreadsheet(string docName, string worksheetName, string title, Dictionary data) { // Open the document for editing. using (SpreadsheetDocument document = SpreadsheetDocument.Open(docName, true)) { + // IEnumerable? sheets = document.WorkbookPart?.Workbook.Descendants().Where(s => s.Name == worksheetName); if (sheets is null || sheets.Count() == 0) @@ -48,7 +47,9 @@ static void InsertChartInSpreadsheet(string docName, string worksheetName, strin chartPart.ChartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") }); DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartPart.ChartSpace.AppendChild( new DocumentFormat.OpenXml.Drawing.Charts.Chart()); + // + // // Create a new clustered column chart. PlotArea plotArea = chart.AppendChild(new PlotArea()); Layout layout = plotArea.AppendChild(new Layout()); @@ -82,7 +83,9 @@ static void InsertChartInSpreadsheet(string docName, string worksheetName, strin i++; } + // + // barChart.Append(new AxisId() { Val = new UInt32Value(48650112u) }); barChart.Append(new AxisId() { Val = new UInt32Value(48672768u) }); @@ -129,7 +132,9 @@ static void InsertChartInSpreadsheet(string docName, string worksheetName, strin // Save the chart part. chartPart.ChartSpace.Save(); + // + // // Position the chart on the worksheet using a TwoCellAnchor object. drawingsPart.WorksheetDrawing = new WorksheetDrawing(); TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild(new TwoCellAnchor()); @@ -163,6 +168,10 @@ static void InsertChartInSpreadsheet(string docName, string worksheetName, strin // Save the WorksheetDrawing object. drawingsPart.WorksheetDrawing.Save(); + // } } +// + +InsertChartInSpreadsheet(args[0], args[1], args[2], new Dictionary() { { "First", 1 }, { "Second", 2 }, { "Third", 3 } }); diff --git a/samples/spreadsheet/insert_a_chartto/vb/Program.vb b/samples/spreadsheet/insert_a_chartto/vb/Program.vb index d4c9eac8..3befa45a 100644 --- a/samples/spreadsheet/insert_a_chartto/vb/Program.vb +++ b/samples/spreadsheet/insert_a_chartto/vb/Program.vb @@ -1,3 +1,4 @@ +' Imports DocumentFormat.OpenXml Imports DocumentFormat.OpenXml.Drawing Imports DocumentFormat.OpenXml.Drawing.Charts @@ -9,18 +10,19 @@ Imports DocumentFormat.OpenXml.Spreadsheet Module MyModule Sub Main(args As String()) + InsertChartInSpreadsheet(args(0), args(1), args(2), New Dictionary(Of String, Integer) From {{"First", 1}, {"Second", 2}, {"Third", 3}}) End Sub ' Given a document name, a worksheet name, a chart title, and a Dictionary collection of text keys ' and corresponding integer data, creates a column chart with the text as the series ' and the integers as the values. - Private Sub InsertChartInSpreadsheet(ByVal docName As String, ByVal worksheetName As String, - ByVal title As String, ByVal data As Dictionary(Of String, Integer)) + Private Sub InsertChartInSpreadsheet(ByVal docName As String, ByVal worksheetName As String, ByVal title As String, ByVal data As Dictionary(Of String, Integer)) ' Open the document for editing. Using document As SpreadsheetDocument = SpreadsheetDocument.Open(docName, True) - Dim sheets As IEnumerable(Of Sheet) = - document.WorkbookPart.Workbook.Descendants(Of Sheet)() _ - .Where(Function(s) s.Name = worksheetName) + + ' + Dim sheets As IEnumerable(Of Sheet) = document.WorkbookPart.Workbook.Descendants(Of Sheet)().Where(Function(s) s.Name = worksheetName) + If sheets.Count() = 0 Then ' The specified worksheet does not exist. Return @@ -42,7 +44,9 @@ Module MyModule Dim chart As DocumentFormat.OpenXml.Drawing.Charts.Chart = chartPart.ChartSpace.AppendChild(Of DocumentFormat.OpenXml.Drawing.Charts _ .Chart)(New DocumentFormat.OpenXml.Drawing.Charts.Chart()) + ' + ' ' Create a new clustered column chart. Dim plotArea As PlotArea = chart.AppendChild(Of PlotArea)(New PlotArea()) Dim layout As Layout = plotArea.AppendChild(Of Layout)(New Layout()) @@ -76,7 +80,9 @@ Module MyModule i += 1 Next key + ' + ' barChart.Append(New AxisId() With {.Val = New UInt32Value(48650112UI)}) barChart.Append(New AxisId() With {.Val = New UInt32Value(48672768UI)}) @@ -105,7 +111,9 @@ Module MyModule ' Save the chart part. chartPart.ChartSpace.Save() + ' + ' ' Position the chart on the worksheet using a TwoCellAnchor object. drawingsPart.WorksheetDrawing = New WorksheetDrawing() Dim twoCellAnchor As TwoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild(Of @@ -134,10 +142,12 @@ Module MyModule "https://schemas.openxmlformats.org/drawingml/2006/chart"})) twoCellAnchor.Append(New ClientData()) + ' ' Save the WorksheetDrawing object. drawingsPart.WorksheetDrawing.Save() End Using End Sub -End Module \ No newline at end of file +End Module +' diff --git a/samples/spreadsheet/insert_a_new_worksheet/cs/Program.cs b/samples/spreadsheet/insert_a_new_worksheet/cs/Program.cs index e44a56d4..1d94ada5 100644 --- a/samples/spreadsheet/insert_a_new_worksheet/cs/Program.cs +++ b/samples/spreadsheet/insert_a_new_worksheet/cs/Program.cs @@ -2,8 +2,6 @@ using DocumentFormat.OpenXml.Spreadsheet; using System.Linq; -InsertWorksheet(args[0]); - // Given a document name, inserts a new worksheet. static void InsertWorksheet(string docName) { @@ -32,4 +30,6 @@ static void InsertWorksheet(string docName) Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName }; sheets.Append(sheet); } -} \ No newline at end of file +} + +InsertWorksheet(args[0]); diff --git a/samples/spreadsheet/insert_textto_a_cell/cs/Program.cs b/samples/spreadsheet/insert_textto_a_cell/cs/Program.cs index d847e946..d745ff90 100644 --- a/samples/spreadsheet/insert_textto_a_cell/cs/Program.cs +++ b/samples/spreadsheet/insert_textto_a_cell/cs/Program.cs @@ -1,14 +1,12 @@ - +// using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System.Linq; -InsertText(args[0], args[1]); - +// // Given a document name and text, // inserts a new work sheet and writes the text to cell "A1" of the new worksheet. - static void InsertText(string docName, string text) { // Open the document for editing. @@ -44,7 +42,9 @@ static void InsertText(string docName, string text) worksheetPart.Worksheet.Save(); } } +// +// // Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text // and inserts it into the SharedStringTablePart. If the item already exists, returns its index. static int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart) @@ -74,7 +74,9 @@ static int InsertSharedStringItem(string text, SharedStringTablePart shareString return i; } +// +// // Given a WorkbookPart, inserts a new worksheet. static WorksheetPart InsertWorksheet(WorkbookPart workbookPart) { @@ -110,7 +112,10 @@ static WorksheetPart InsertWorksheet(WorkbookPart workbookPart) return newWorksheetPart; } +// + +// // Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet. // If the cell already exists, returns it. static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart) @@ -158,3 +163,7 @@ static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPar return newCell; } } +// +// + +InsertText(args[0], args[1]); \ No newline at end of file diff --git a/samples/spreadsheet/insert_textto_a_cell/vb/Program.vb b/samples/spreadsheet/insert_textto_a_cell/vb/Program.vb index 6ec4d2cc..819035d3 100644 --- a/samples/spreadsheet/insert_textto_a_cell/vb/Program.vb +++ b/samples/spreadsheet/insert_textto_a_cell/vb/Program.vb @@ -1,3 +1,4 @@ +' Imports DocumentFormat.OpenXml Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Spreadsheet @@ -6,8 +7,10 @@ Imports DocumentFormat.OpenXml.Spreadsheet Module MyModule Sub Main(args As String()) + InsertText(args(0), args(1)) End Sub + ' ' Given a document name and text, ' inserts a new worksheet and writes the text to cell "A1" of the new worksheet. Public Function InsertText(ByVal docName As String, ByVal text As String) @@ -43,7 +46,9 @@ Module MyModule Return 0 End Using End Function + ' + ' ' Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text ' and inserts it into the SharedStringTablePart. If the item already exists, returns its index. Private Function InsertSharedStringItem(ByVal text As String, ByVal shareStringPart As SharedStringTablePart) As Integer @@ -68,7 +73,9 @@ Module MyModule Return i End Function + ' + ' ' Given a WorkbookPart, inserts a new worksheet. Private Function InsertWorksheet(ByVal workbookPart As WorkbookPart) As WorksheetPart ' Add a new worksheet part to the workbook. @@ -96,7 +103,9 @@ Module MyModule Return newWorksheetPart End Function + ' + ' ' Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet. ' If the cell already exists, return it. Private Function InsertCellInWorksheet(ByVal columnName As String, ByVal rowIndex As UInteger, ByVal worksheetPart As WorksheetPart) As Cell @@ -136,4 +145,7 @@ Module MyModule Return newCell End If End Function -End Module \ No newline at end of file + ' + +End Module +' diff --git a/samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs b/samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs index ace15a7a..44472c25 100644 --- a/samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs +++ b/samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs @@ -1,3 +1,4 @@ +// using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; @@ -6,7 +7,6 @@ using System.Linq; using System.Text.RegularExpressions; -MergeTwoCells(args[0], args[1], args[2], args[3]); // Given a document name, a worksheet name, and the names of two adjacent cells, merges the two cells. // When two cells are merged, only the content from one cell is preserved: @@ -147,4 +147,7 @@ static uint GetRowIndex(string cellName) Match match = regex.Match(cellName); return uint.Parse(match.Value); -} \ No newline at end of file +} +// + +MergeTwoCells(args[0], args[1], args[2], args[3]); \ No newline at end of file diff --git a/samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb b/samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb index ad293de9..d8b3f6aa 100644 --- a/samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb +++ b/samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb @@ -1,3 +1,4 @@ +' Imports System.Text.RegularExpressions Imports DocumentFormat.OpenXml Imports DocumentFormat.OpenXml.Packaging @@ -5,10 +6,9 @@ Imports DocumentFormat.OpenXml.Spreadsheet Module Program Sub Main(args As String()) + MergeTwoCells(args(0), args(1), args(2), args(3)) End Sub - - ' Given a document name, a worksheet name, and the names of two adjacent cells, merges the two cells. ' When two cells are merged, only the content from one cell is preserved: ' the upper-left cell for left-to-right languages or the upper-right cell for right-to-left languages. @@ -125,4 +125,5 @@ Module Program Dim match As Match = regex.Match(cellName) Return UInteger.Parse(match.Value) End Function -End Module \ No newline at end of file +End Module +' \ No newline at end of file diff --git a/samples/spreadsheet/open_for_read_only_access/cs/Program.cs b/samples/spreadsheet/open_for_read_only_access/cs/Program.cs index aef17368..c9cd2a8c 100644 --- a/samples/spreadsheet/open_for_read_only_access/cs/Program.cs +++ b/samples/spreadsheet/open_for_read_only_access/cs/Program.cs @@ -1,9 +1,14 @@ +// using DocumentFormat.OpenXml.Packaging; +using System.IO; +using System.IO.Packaging; -static void OpenSpreadsheetDocumentReadonly(string filepath) +static void OpenSpreadsheetDocumentReadonly(string filePath) { - // Open a SpreadsheetDocument based on a filepath. - using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filepath, false)) + // + // Open a SpreadsheetDocument based on a file path. + using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filePath, false)) + // { if (spreadsheetDocument.WorkbookPart is not null) { @@ -14,4 +19,40 @@ static void OpenSpreadsheetDocumentReadonly(string filepath) // The rest of the code will not be called. } } -} \ No newline at end of file + + // + // Open a SpreadsheetDocument based on a stream. + Stream stream = File.Open(filePath, FileMode.Open); + + using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(stream, false)) + // + { + if (spreadsheetDocument.WorkbookPart is not null) + { + // Attempt to add a new WorksheetPart. + // The call to AddNewPart generates an exception because the file is read-only. + WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart(); + + // The rest of the code will not be called. + } + } + + // + // Open System.IO.Packaging.Package. + Package spreadsheetPackage = Package.Open(filePath, FileMode.Open, FileAccess.Read); + + // Open a SpreadsheetDocument based on a package. + using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(spreadsheetPackage)) + // + { + if (spreadsheetDocument.WorkbookPart is not null) + { + // Attempt to add a new WorksheetPart. + // The call to AddNewPart generates an exception because the file is read-only. + WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart(); + + // The rest of the code will not be called. + } + } +} +// \ No newline at end of file diff --git a/samples/spreadsheet/open_for_read_only_access/vb/Program.vb b/samples/spreadsheet/open_for_read_only_access/vb/Program.vb index 55e48516..7432fab2 100644 --- a/samples/spreadsheet/open_for_read_only_access/vb/Program.vb +++ b/samples/spreadsheet/open_for_read_only_access/vb/Program.vb @@ -1,3 +1,6 @@ +' +Imports System.IO +Imports System.IO.Packaging Imports DocumentFormat.OpenXml.Packaging Module Program @@ -6,9 +9,41 @@ Module Program - Public Sub OpenSpreadsheetDocumentReadonly(ByVal filepath As String) - ' Open a SpreadsheetDocument based on a filepath. - Using spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Open(filepath, False) + Public Sub OpenSpreadsheetDocumentReadOnly(ByVal filePath As String) + ' + ' Open a SpreadsheetDocument based on a file path. + Using spreadsheetDocument As SpreadsheetDocument = SpreadsheetDocument.Open(filePath, False) + ' + + ' Attempt to add a new WorksheetPart. + ' The call to AddNewPart generates an exception because the file is read-only. + Dim newWorksheetPart As WorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart(Of WorksheetPart)() + + ' The rest of the code will not be called. + End Using + + ' + ' Open a SpreadsheetDocument based on a stream. + Dim stream = File.Open(filePath, FileMode.Open) + + Using spreadsheetDocument As SpreadsheetDocument = SpreadsheetDocument.Open(filePath, False) + ' + + ' Attempt to add a new WorksheetPart. + ' The call to AddNewPart generates an exception because the file is read-only. + Dim newWorksheetPart As WorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart(Of WorksheetPart)() + + ' The rest of the code will not be called. + End Using + + ' + ' Open System.IO.Packaging.Package. + Dim spreadsheetPackage As Package = Package.Open(filePath, FileMode.Open, FileAccess.Read) + + ' Open a SpreadsheetDocument based on a package. + Using spreadsheetDocument As SpreadsheetDocument = SpreadsheetDocument.Open(spreadsheetPackage) + ' + ' Attempt to add a new WorksheetPart. ' The call to AddNewPart generates an exception because the file is read-only. Dim newWorksheetPart As WorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart(Of WorksheetPart)() @@ -16,4 +51,5 @@ Module Program ' The rest of the code will not be called. End Using End Sub -End Module \ No newline at end of file +End Module +' \ No newline at end of file diff --git a/samples/spreadsheet/open_from_a_stream/cs/Program.cs b/samples/spreadsheet/open_from_a_stream/cs/Program.cs index 72d655f3..4abdb0fb 100644 --- a/samples/spreadsheet/open_from_a_stream/cs/Program.cs +++ b/samples/spreadsheet/open_from_a_stream/cs/Program.cs @@ -1,11 +1,9 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System.IO; using System.Linq; -FileStream fileStream = new(args[0], FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); -OpenAndAddToSpreadsheetStream(fileStream); - static void OpenAndAddToSpreadsheetStream(Stream stream) { // Open a SpreadsheetDocument based on a stream. @@ -16,10 +14,14 @@ static void OpenAndAddToSpreadsheetStream(Stream stream) // Get or create the WorkbookPart WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart ?? spreadsheetDocument.AddWorkbookPart(); + // + // Add a new worksheet. WorksheetPart newWorksheetPart = workbookPart.AddNewPart(); newWorksheetPart.Worksheet = new Worksheet(new SheetData()); newWorksheetPart.Worksheet.Save(); + + // Workbook workbook = workbookPart.Workbook ?? new Workbook(); @@ -50,4 +52,11 @@ static void OpenAndAddToSpreadsheetStream(Stream stream) // Dispose the document handle. spreadsheetDocument.Dispose(); } -} \ No newline at end of file +} + +// + +// +var fileStream = File.Open(args[0], FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); +OpenAndAddToSpreadsheetStream(fileStream); +// \ No newline at end of file diff --git a/samples/spreadsheet/open_from_a_stream/vb/Program.vb b/samples/spreadsheet/open_from_a_stream/vb/Program.vb index a280f5e6..b850d939 100644 --- a/samples/spreadsheet/open_from_a_stream/vb/Program.vb +++ b/samples/spreadsheet/open_from_a_stream/vb/Program.vb @@ -1,9 +1,16 @@ +' Imports System.IO Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Spreadsheet Module Program Sub Main(args As String()) + + ' + Dim fileStream As FileStream = New FileStream(args(0), FileMode.OpenOrCreate, FileAccess.ReadWrite) + OpenAndAddToSpreadsheetStream(fileStream) + ' + End Sub @@ -12,11 +19,15 @@ Module Program ' Open a SpreadsheetDocument based on a stream. Dim mySpreadsheetDocument As SpreadsheetDocument = SpreadsheetDocument.Open(stream, True) + ' + ' Add a new worksheet. Dim newWorksheetPart As WorksheetPart = mySpreadsheetDocument.WorkbookPart.AddNewPart(Of WorksheetPart)() newWorksheetPart.Worksheet = New Worksheet(New SheetData()) newWorksheetPart.Worksheet.Save() + ' + Dim sheets As Sheets = mySpreadsheetDocument.WorkbookPart.Workbook.GetFirstChild(Of Sheets)() Dim relationshipId As String = mySpreadsheetDocument.WorkbookPart.GetIdOfPart(newWorksheetPart) @@ -42,4 +53,6 @@ Module Program 'Caller must close the stream. End Sub -End Module \ No newline at end of file +End Module + +' \ No newline at end of file diff --git a/samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs b/samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs index 7ccb802a..5fe6e88a 100644 --- a/samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs +++ b/samples/spreadsheet/parse_and_read_a_large_spreadsheet/cs/Program.cs @@ -1,12 +1,10 @@ +// using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; using System.Linq; -ReadExcelFileDOM(args[0]); -ReadExcelFileSAX(args[0]); - // The DOM approach. // Note that the code below works only for cells that contain numeric values. // @@ -14,6 +12,8 @@ static void ReadExcelFileDOM(string fileName) { using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, false)) { + // + WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart ?? spreadsheetDocument.AddWorkbookPart(); WorksheetPart worksheetPart = workbookPart.WorksheetParts.First(); SheetData sheetData = worksheetPart.Worksheet.Elements().First(); @@ -27,6 +27,8 @@ static void ReadExcelFileDOM(string fileName) Console.Write(text + " "); } } + + // Console.WriteLine(); Console.ReadKey(); @@ -38,6 +40,8 @@ static void ReadExcelFileSAX(string fileName) { using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, false)) { + // + WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart ?? spreadsheetDocument.AddWorkbookPart(); WorksheetPart worksheetPart = workbookPart.WorksheetParts.First(); @@ -51,7 +55,17 @@ static void ReadExcelFileSAX(string fileName) Console.Write(text + " "); } } + + // + Console.WriteLine(); Console.ReadKey(); } -} \ No newline at end of file +} +// + +// +// Comment one of the following lines to test the method separately. +ReadExcelFileDOM(args[0]); // DOM +ReadExcelFileSAX(args[0]); // SAX +// \ No newline at end of file diff --git a/samples/spreadsheet/parse_and_read_a_large_spreadsheet/vb/Program.vb b/samples/spreadsheet/parse_and_read_a_large_spreadsheet/vb/Program.vb index c6f8a951..b9ed20e0 100644 --- a/samples/spreadsheet/parse_and_read_a_large_spreadsheet/vb/Program.vb +++ b/samples/spreadsheet/parse_and_read_a_large_spreadsheet/vb/Program.vb @@ -1,11 +1,19 @@ +' Imports DocumentFormat.OpenXml Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Spreadsheet Module Program Sub Main(args As String()) - End Sub + ' + + ' Comment one of the following lines to test each method separately. + ReadExcelFileDOM(args(0)) ' DOM + ReadExcelFileSAX(args(0)) ' SAX + + ' + End Sub ' The DOM approach. @@ -14,6 +22,9 @@ Module Program Private Sub ReadExcelFileDOM(ByVal fileName As String) Using spreadsheetDocument As SpreadsheetDocument = SpreadsheetDocument.Open(fileName, False) + + ' + Dim workbookPart As WorkbookPart = spreadsheetDocument.WorkbookPart Dim worksheetPart As WorksheetPart = workbookPart.WorksheetParts.First() Dim sheetData As SheetData = worksheetPart.Worksheet.Elements(Of SheetData)().First() @@ -24,6 +35,9 @@ Module Program Console.Write(text & " ") Next Next + + ' + Console.WriteLine() Console.ReadKey() End Using @@ -31,6 +45,9 @@ Module Program ' The SAX approach. Private Sub ReadExcelFileSAX(ByVal fileName As String) + + ' + Using spreadsheetDocument As SpreadsheetDocument = SpreadsheetDocument.Open(fileName, False) Dim workbookPart As WorkbookPart = spreadsheetDocument.WorkbookPart Dim worksheetPart As WorksheetPart = workbookPart.WorksheetParts.First() @@ -43,8 +60,13 @@ Module Program Console.Write(text & " ") End If End While + + ' + Console.WriteLine() Console.ReadKey() End Using End Sub -End Module \ No newline at end of file +End Module + +' \ No newline at end of file diff --git a/samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/cs/Program.cs b/samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/cs/Program.cs index 3ae2c819..d3677413 100644 --- a/samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/cs/Program.cs +++ b/samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/cs/Program.cs @@ -1,24 +1,25 @@ +// using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; using System.Collections.Generic; -GetDefinedNames(args[0]); - -static Dictionary - GetDefinedNames(String fileName) +static DictionaryGetDefinedNames(String fileName) { // Given a workbook name, return a dictionary of defined names. // The pairs include the range name and a string representing the range. var returnValue = new Dictionary(); + // // Open the spreadsheet document for read-only access. - using (SpreadsheetDocument document = - SpreadsheetDocument.Open(fileName, false)) + using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false)) { // Retrieve a reference to the workbook part. var wbPart = document.WorkbookPart; + // + + // // Retrieve a reference to the defined names collection. DefinedNames? definedNames = wbPart?.Workbook?.DefinedNames; @@ -33,12 +34,18 @@ static Dictionary } } } - } - foreach (var pair in returnValue) - { - Console.WriteLine("{0} {1}", pair.Key, pair.Value); + // } return returnValue; -} \ No newline at end of file +} + +// + +var definedNames = GetDefinedNames(args[0]); + +foreach (var pair in definedNames) +{ + Console.WriteLine("Name: {0} Value: {1}", pair.Key, pair.Value); +} diff --git a/samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/vb/Program.vb b/samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/vb/Program.vb index 49c57887..d634aaa2 100644 --- a/samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/vb/Program.vb +++ b/samples/spreadsheet/retrieve_a_dictionary_of_all_named_ranges/vb/Program.vb @@ -1,26 +1,33 @@ +' Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Spreadsheet Module Program Sub Main(args As String()) - End Sub + Dim definedNames = GetDefinedNames(args(0)) + For Each definedName In definedNames + Console.WriteLine("Name: {0} Value: {1}", definedName.Key, definedName.Value) + Next + End Sub - Public Function GetDefinedNames( - ByVal fileName As String) As Dictionary(Of String, String) + Public Function GetDefinedNames(ByVal fileName As String) As Dictionary(Of String, String) ' Given a workbook name, return a dictionary of defined names. ' The pairs include the range name and a string representing the range. Dim returnValue As New Dictionary(Of String, String) + ' ' Open the spreadsheet document for read-only access. - Using document As SpreadsheetDocument = - SpreadsheetDocument.Open(fileName, False) + Using document As SpreadsheetDocument = SpreadsheetDocument.Open(fileName, False) ' Retrieve a reference to the workbook part. Dim wbPart As WorkbookPart = document.WorkbookPart + ' + + ' ' Retrieve a reference to the defined names collection. Dim definedNames As DefinedNames = wbPart.Workbook.DefinedNames @@ -30,7 +37,11 @@ Module Program returnValue.Add(dn.Name.Value, dn.Text) Next End If + + ' End Using Return returnValue End Function -End Module \ No newline at end of file +End Module + +' From ba31743e0e07cd02c908b057b1bf66f95fb91466 Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Fri, 12 Jan 2024 13:58:27 -0800 Subject: [PATCH 005/139] Extract snippets from remaining SpreadsheetML tutorials, extract "Packages and Document Parts" section, and fix multiple xmlns errors (#298) --- docs/includes/spreadsheet/structure.md | 2 +- .../structure-of-a-presentationml-document.md | 2 +- ...add-custom-ui-to-a-spreadsheet-document.md | 118 +---- ...ange-of-cells-in-a-spreadsheet-document.md | 424 +----------------- ...sheet-document-by-providing-a-file-name.md | 79 +--- ...elete-text-from-a-cell-in-a-spreadsheet.md | 292 +----------- ...o-get-a-column-heading-in-a-spreadsheet.md | 172 +------ ...et-worksheet-information-from-a-package.md | 74 +-- ...readsheet-document-for-read-only-access.md | 2 +- ...en-a-spreadsheet-document-from-a-stream.md | 2 +- .../structure-of-a-spreadsheetml-document.md | 2 +- docs/spreadsheet/working-with-formulas.md | 2 +- docs/spreadsheet/working-with-tables.md | 4 +- .../working-with-the-shared-string-table.md | 2 +- .../spreadsheet/add_custom_ui/cs/Program.cs | 56 +-- .../spreadsheet/add_custom_ui/vb/Program.vb | 59 +-- .../cs/Program.cs | 23 +- .../vb/Program.vb | 23 +- .../cs/Program.cs | 12 +- .../vb/Program.vb | 14 +- .../delete_text_from_a_cell/cs/Program.cs | 13 +- .../delete_text_from_a_cell/vb/Program.vb | 11 +- .../get_a_column_heading/cs/Program.cs | 18 +- .../get_a_column_heading/vb/Program.vb | 19 +- .../cs/Program.cs | 22 +- .../vb/Program.vb | 23 +- 26 files changed, 310 insertions(+), 1160 deletions(-) diff --git a/docs/includes/spreadsheet/structure.md b/docs/includes/spreadsheet/structure.md index 3cdbdc31..3866d007 100644 --- a/docs/includes/spreadsheet/structure.md +++ b/docs/includes/spreadsheet/structure.md @@ -22,7 +22,7 @@ code example. ```xml - + diff --git a/docs/presentation/structure-of-a-presentationml-document.md b/docs/presentation/structure-of-a-presentationml-document.md index daadd7fc..676c0160 100644 --- a/docs/presentation/structure-of-a-presentationml-document.md +++ b/docs/presentation/structure-of-a-presentationml-document.md @@ -650,7 +650,7 @@ The following XML code is the PresentationML that represents the relationship pa ```xml - + diff --git a/docs/spreadsheet/how-to-add-custom-ui-to-a-spreadsheet-document.md b/docs/spreadsheet/how-to-add-custom-ui-to-a-spreadsheet-document.md index e6f6af76..ec91a417 100644 --- a/docs/spreadsheet/how-to-add-custom-ui-to-a-spreadsheet-document.md +++ b/docs/spreadsheet/how-to-add-custom-ui-to-a-spreadsheet-document.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/10/2024 ms.localizationpriority: high --- @@ -24,22 +24,15 @@ this task. ## Creating Custom UI -Before using the Open XML SDK to create a ribbon customization in an Excel workbook, you must first create the customization content. Describing the XML required to create a ribbon customization is beyond the scope of this topic. In addition, you will find it far easier to use the Ribbon Designer in Visual Studio 2010 to create the customization for you. For more information about customizing the ribbon by using the Visual Studio Ribbon Designer, see [Ribbon Designer](https://msdn.microsoft.com/library/26617206-f4da-416f-a18a-d817b2d4872d(Office.15).aspx) and [Walkthrough: Creating a Custom Tab by Using the Ribbon Designer](https://msdn.microsoft.com/library/312865e6-950f-46ab-88de-fe7eb8036bfe(Office.15).aspx). -For the purposes of this demonstration, you will need an XML file that contains a customization, and the following code provides a simple customization (or you can create your own by using the Visual Studio Ribbon Designer, and then right-click to export the customization to an XML file). Copy the following content into a text file that is named AddCustomUI.xml for use as part of this example. This XML content describes a ribbon customization that includes a button labeled "Click Me!" in a group named Group1 on the **Add-Ins** tab in Excel. When you click the button, it attempts to run a macro named **SampleMacro** in the host workbook. - -```xml - - - - - -