diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..a377943b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.cs -text +*.vb -text \ No newline at end of file diff --git a/.github/workflows/auto-publish.yml b/.github/workflows/auto-publish.yml new file mode 100644 index 00000000..aae337b6 --- /dev/null +++ b/.github/workflows/auto-publish.yml @@ -0,0 +1,38 @@ +name: auto-publish +run-name: Automatically publish documentation +on: + schedule: + - cron: '45 23 * * WED' +jobs: + auto-publish: + runs-on: ubuntu-latest + permissions: + contents: write + defaults: + run: + shell: bash + working-directory: ./ + steps: + - name: Check out repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Check out main + run: | + echo "Checking out main branch" + git config user.name github-actions + git config user.email github-actions@github.com + git checkout main + - name: Check out live + run: | + echo "Checking out live branch" + git checkout live + - name: Merge from main into live + run: | + echo "Merging from main to live" + git merge main + - name: Push changes + run: | + echo "Pushing changes to live branch" + git push origin live + diff --git a/LICENSE b/LICENSE index 4b1ad51b..21071075 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,21 @@ - MIT License - - Copyright (c) Microsoft Corporation. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/docs/general/diagnosticids.md b/docs/general/diagnosticids.md index bddef395..5094d5eb 100644 --- a/docs/general/diagnosticids.md +++ b/docs/general/diagnosticids.md @@ -5,13 +5,13 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/08/2025 ms.localizationpriority: high --- # Diagnostic IDs -Diagnostic IDs are used to identify APIs or patterns that can raise compiler warnings or errors. This can be done via [ObsoleteAttribute](/dotnet/api/system.obsoleteattribute.diagnosticid) or [ExperimentalAttribute](/dotnet/api/system.diagnostics.codeanalysis.experimentalattribute). These can be suppressed at the consumer level for each diagnostic id. +Diagnostic IDs are used to identify APIs or patterns that can raise compiler warnings or errors. This can be done via or . These can be suppressed at the consumer level for each diagnostic id. ## Experimental APIs @@ -19,7 +19,7 @@ Diagnostic IDs are used to identify APIs or patterns that can raise compiler war **Title**: IPackage related APIs are currently experimental -As of v3.0, a new abstraction layer was added in between `System.IO.Packaging` and `DocumentFormat.OpenXml.Packaging.OpenXmlPackage`. This is currently experimental, but can be used if needed. This will be stabalized in a future release, and may or may not require code changes. +As of v3.0, a new abstraction layer was added in between `System.IO.Packaging` and `DocumentFormat.OpenXml.Packaging.OpenXmlPackage`. This is currently experimental, but can be used if needed. This will be stabilized in a future release, and may or may not require code changes. ## Suppress warnings 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 512f0346..296f5d06 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 @@ -11,14 +11,14 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/08/2025 ms.localizationpriority: medium --- # Add a new document part that receives a relationship ID to a package This topic shows how to use the classes in the Open XML SDK for -Office to add a document part (file) that receives a relationship **Id** parameter for a word +Office to add a document part (file) that receives a relationship `Id` parameter for a word processing document. @@ -32,39 +32,51 @@ processing document. [!include[Structure](../includes/word/structure.md)] ----------------------------------------------------------------------------- -## Sample Code -The following code, adds a new document part that contains custom XML -from an external file and then populates the document part. You can call -the method **AddNewPart** by using a call like -the following code example. - -### [C#](#tab/cs-0) -```csharp - string document = @"C:\Users\Public\Documents\MyPkg1.docx"; - AddNewPart(document); -``` - -### [Visual Basic](#tab/vb-0) -```vb - Dim document As String = "C:\Users\Public\Documents\MyPkg1.docx" - AddNewPart(document) -``` + +## How the Sample Code Works + +The sample code, in this how-to, starts by passing in a parameter that represents the path to the Word document. It then creates +a new WordprocessingDocument object within a using statement. + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/word/add_a_new_part_that_receives_a_relationship_id_to_a_package/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/word/add_a_new_part_that_receives_a_relationship_id_to_a_package/vb/Program.vb#snippet1)] +*** + +It then adds the MainDocumentPart part in the new word processing document, with the relationship ID, rId1. It also adds the `CustomFilePropertiesPart` part and a `CoreFilePropertiesPart` in the new word processing document. + +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/word/add_a_new_part_that_receives_a_relationship_id_to_a_package/cs/Program.cs#snippet2)] + +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/word/add_a_new_part_that_receives_a_relationship_id_to_a_package/vb/Program.vb#snippet2)] *** +The code then adds the `DigitalSignatureOriginPart` part, the `ExtendedFilePropertiesPart` part, and the `ThumbnailPart` part in the new word processing document with realtionship IDs rId4, rId5, and rId6. -The following is the complete code example in both C\# and Visual Basic. +> [!NOTE] +> The method creates a relationship from the current document part to the new document part. This method returns the new document part. Also, you can use the method to fill the document part. + +## Sample Code + +The following code, adds a new document part that contains custom XML +from an external file and then populates the document part. Below is the +complete code example in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/add_a_new_part_that_receives_a_relationship_id_to_a_package/cs/Program.cs)] +[!code-csharp[](../../samples/word/add_a_new_part_that_receives_a_relationship_id_to_a_package/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/add_a_new_part_that_receives_a_relationship_id_to_a_package/vb/Program.vb)] +[!code-vb[](../../samples/word/add_a_new_part_that_receives_a_relationship_id_to_a_package/vb/Program.vb#snippet0)] +*** ----------------------------------------------------------------------------- -## See also +## See also - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) - + 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 bc5ba2d2..5cc51b22 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 @@ -9,7 +9,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 03/22/2022 +ms.date: 01/08/2025 ms.localizationpriority: medium --- @@ -23,77 +23,43 @@ This topic shows how to use the classes in the Open XML SDK for Office to add a The code starts with opening a package file by passing a file name to one of the overloaded methods of the that takes a string and a Boolean value that specifies whether the file should be opened for editing or for read-only access. In this case, the Boolean value is `true` specifying that the file should be opened in read/write mode. -### [C#](#tab/cs-0) -```csharp - using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, True) - ' Insert other code here. - End Using -``` +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/word/add_a_new_part_to_a_package/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/word/add_a_new_part_to_a_package/vb/Program.vb#snippet1)] *** -The **using** statement provides a recommended alternative to the typical .Create, .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 **wordDoc**. Because the class in the Open XML SDK -automatically saves and closes the object as part of its **System.IDisposable** implementation, and because the **Dispose** method is automatically called when you exit the block; you do not have to explicitly call **Save** and **Close**, as long as you use **using**. +[!include[Using Statement](../includes/word/using-statement.md)] [!include[Structure](../includes/word/structure.md)] ## How the sample code works -After opening the document for editing, in the **using** statement, as a object, the code creates a reference to the **MainDocumentPart** part and adds a new custom XML part. It then reads the contents of the external -file that contains the custom XML and writes it to the **CustomXmlPart** part. +After opening the document for editing, in the `using` statement, as a object, the code creates a reference to the `MainDocumentPart` part and adds a new custom XML part. It then reads the contents of the external +file that contains the custom XML and writes it to the `CustomXmlPart` part. > [!NOTE] > To use the new document part in the document, add a link to the document part in the relationship part for the new part. -### [C#](#tab/cs-1) -```csharp - MainDocumentPart mainPart = wordDoc.MainDocumentPart; - CustomXmlPart myXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml); - - using (FileStream stream = new FileStream(fileName, FileMode.Open)) - { - myXmlPart.FeedData(stream); - } -``` - -### [Visual Basic](#tab/vb-1) -```vb - Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart - - Dim myXmlPart As CustomXmlPart = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml) +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/word/add_a_new_part_to_a_package/cs/Program.cs#snippet2)] - Using stream As New FileStream(fileName, FileMode.Open) - myXmlPart.FeedData(stream) - End Using -``` +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/word/add_a_new_part_to_a_package/vb/Program.vb#snippet2)] *** ## Sample code -The following code adds a new document part that contains custom XML from an external file and then populates the part. To call the AddCustomXmlPart method in your program, use the following example that modifies the file "myPkg2.docx" by adding a new document part to it. +The following code adds a new document part that contains custom XML from an external file and then populates the part. To call the `AddCustomXmlPart` method in your program, use the following example that modifies a file by adding a new document part to it. -### [C#](#tab/cs-2) -```csharp - string document = @"C:\Users\Public\Documents\myPkg2.docx"; - string fileName = @"C:\Users\Public\Documents\myXML.xml"; - AddNewPart(document, fileName); -``` +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/word/add_a_new_part_to_a_package/cs/Program.cs#snippet3)] -### [Visual Basic](#tab/vb-2) -```vb - Dim document As String = "C:\Users\Public\Documents\myPkg2.docx" - Dim fileName As String = "C:\Users\Public\Documents\myXML.xml" - AddNewPart(document, fileName) -``` +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/word/add_a_new_part_to_a_package/vb/Program.vb#snippet3)] *** @@ -103,10 +69,11 @@ The following code adds a new document part that contains custom XML from an ext Following is the complete code example in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/add_a_new_part_to_a_package/cs/Program.cs)] +[!code-csharp[](../../samples/word/add_a_new_part_to_a_package/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/add_a_new_part_to_a_package/vb/Program.vb)] +[!code-vb[](../../samples/word/add_a_new_part_to_a_package/vb/Program.vb#snippet0)] +*** ## See also 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 5d9bf19f..5125daf0 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 @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/08/2025 ms.localizationpriority: medium --- @@ -30,43 +30,23 @@ programmatically. -------------------------------------------------------------------------------- ## Getting a WordprocessingDocument Object + To open an existing document, instantiate the class as shown in -the following two **using** statements. In the +the following two `using` statements. In the same statement, you open the word processing file with the specified -file name by using the [Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method, with the Boolean parameter. -For the source file that set the parameter to **false** to open it for read-only access. For the -target file, set the parameter to **true** in +file name by using the method, with the Boolean parameter. +For the source file that set the parameter to `false` to open it for read-only access. For the +target file, set the parameter to `true` in order to enable editing the document. -### [C#](#tab/cs-0) -```csharp - using (WordprocessingDocument wordDoc1 = WordprocessingDocument.Open(fromDocument1, false)) - using (WordprocessingDocument wordDoc2 = WordprocessingDocument.Open(toDocument2, true)) - { - // Insert other code here. - } -``` +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/word/copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif/cs/Program.cs#snippet1)] -### [Visual Basic](#tab/vb-0) -```vb - Dim wordDoc1 As WordprocessingDocument = WordprocessingDocument.Open(fromDocument1, False) - Dim wordDoc2 As WordprocessingDocument = WordprocessingDocument.Open(toDocument2, True) - Using (wordDoc2) - ' Insert other code here. - End Using -``` +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/word/copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif/vb/Program.vb#snippet1)] *** -The `using` statement provides a recommended -alternative to the typical .Create, .Save, .Close sequence. It ensures -that the 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. Because the class in the Open XML SDK -automatically saves and closes the object as part of its implementation, and because - is automatically called when you -exit the block, you do not have to explicitly call . +[!include[Using Statement](../includes/word/using-statement.md)] -------------------------------------------------------------------------------- @@ -74,6 +54,7 @@ exit the block, you do not have to explicitly call objects, and creates variables that reference the parts in each of the packages. -### [C#](#tab/cs-1) -```csharp - public static void CopyThemeContent(string fromDocument1, string toDocument2) - { - using (WordprocessingDocument wordDoc1 = WordprocessingDocument.Open(fromDocument1, false)) - using (WordprocessingDocument wordDoc2 = WordprocessingDocument.Open(toDocument2, true)) - { - ThemePart themePart1 = wordDoc1.MainDocumentPart.ThemePart; - ThemePart themePart2 = wordDoc2.MainDocumentPart.ThemePart; -``` +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/word/copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif/cs/Program.cs#snippet2)] -### [Visual Basic](#tab/vb-1) -```vb - Public Sub CopyThemeContent(ByVal fromDocument1 As String, ByVal toDocument2 As String) - Dim wordDoc1 As WordprocessingDocument = WordprocessingDocument.Open(fromDocument1, False) - Dim wordDoc2 As WordprocessingDocument = WordprocessingDocument.Open(toDocument2, True) - Using (wordDoc2) - Dim themePart1 As ThemePart = wordDoc1.MainDocumentPart.ThemePart - Dim themePart2 As ThemePart = wordDoc2.MainDocumentPart.ThemePart -``` +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/word/copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif/vb/Program.vb#snippet2)] *** -The code then reads the contents of the source part by using a **StreamReader** object and writes to the target +The code then reads the contents of the source part by using a `StreamReader` object and writes to the target part by using a . -### [C#](#tab/cs-2) -```csharp - using (StreamReader streamReader = new StreamReader(themePart1.GetStream())) - using (StreamWriter streamWriter = new StreamWriter(themePart2.GetStream(FileMode.Create))) - { - streamWriter.Write( streamReader.ReadToEnd()); - } -``` +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/word/copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif/cs/Program.cs#snippet3)] -### [Visual Basic](#tab/vb-2) -```vb - Dim streamReader As StreamReader = New StreamReader(themePart1.GetStream()) - Dim streamWriter As StreamWriter = New StreamWriter(themePart2.GetStream(FileMode.Create)) - Using (streamWriter) - streamWriter.Write(streamReader.ReadToEnd) - End Using -``` +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/word/copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif/vb/Program.vb#snippet3)] *** -------------------------------------------------------------------------------- ## Sample Code + The following code copies the contents of one document part in an Open -XML package to a document part in a different package. To call the `CopyThemeContent`` method, you can use the -following example, which copies the theme part from "MyPkg4.docx" to -"MyPkg3.docx." +XML package to a document part in a different package. To call the `CopyThemeContent` method, you can use the +following example, which copies the theme part from the packages located at `args[0]` to +one located at `args[1]`. -### [C#](#tab/cs-3) -```csharp - string fromDocument1 = @"C:\Users\Public\Documents\MyPkg4.docx"; - string toDocument2 = @"C:\Users\Public\Documents\MyPkg3.docx"; - CopyThemeContent(fromDocument1, toDocument2); -``` +### [C#](#tab/cs-4) +[!code-csharp[](../../samples/word/copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif/cs/Program.cs#snippet4)] -### [Visual Basic](#tab/vb-3) -```vb - Dim fromDocument1 As String = "C:\Users\Public\Documents\MyPkg4.docx" - Dim toDocument2 As String = "C:\Users\Public\Documents\MyPkg3.docx" - CopyThemeContent(fromDocument1, toDocument2) -``` +### [Visual Basic](#tab/vb-4) +[!code-vb[](../../samples/word/copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif/vb/Program.vb#snippet4)] *** > [!IMPORTANT] -> Before you run the program, make sure that the source document (MyPkg4.docx) has the theme part set; otherwise, an exception would be thrown. To add a theme to a document, open it in Microsoft Word, click the **Page Layout** tab, click **Themes**, and select one of the available themes. +> Before you run the program, make sure that the source document has the theme part set. To add a theme to a document, +> open it in Microsoft Word, click the **Design** tab then click **Themes**, and select one of the available themes. -After running the program, you can inspect the file "MyPkg3.docx" to see -the copied theme from the file "MyPkg4.docx." +After running the program, you can inspect the file to see +the changed theme. Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif/cs/Program.cs)] +[!code-csharp[](../../samples/word/copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif/vb/Program.vb)] +[!code-vb[](../../samples/word/copy_the_contents_of_an_open_xml_package_part_to_a_part_a_dif/vb/Program.vb#snippet0)] +*** -------------------------------------------------------------------------------- ## See also diff --git a/docs/general/how-to-create-a-package.md b/docs/general/how-to-create-a-package.md index c40dea47..2d26e059 100644 --- a/docs/general/how-to-create-a-package.md +++ b/docs/general/how-to-create-a-package.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/03/2025 ms.localizationpriority: medium --- @@ -19,7 +19,7 @@ ms.localizationpriority: medium 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. +from content in the form of `WordprocessingML` XML markup. [!include[Structure](../includes/word/packages-and-document-parts.md)] @@ -29,7 +29,7 @@ In the Open XML SDK, the class and populate it with parts. At a minimum, the document must have a main document part that serves as a container for the main text of the -document. The text is represented in the package as XML using **WordprocessingML** markup. +document. The text is represented in the package as XML using `WordprocessingML` markup. To create the class instance you call . Several methods are provided, each with a different signature. The first parameter takes a full path @@ -43,31 +43,14 @@ template. > [!NOTE] > Carefully select the appropriate and verify that the persisted file has the correct, matching file extension. If the does not match the file extension, an error occurs when you open the file in Microsoft Word. -### [C#](#tab/cs-0) -```csharp - using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(document, WordprocessingDocumentType.Document)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - Using wordDoc As WordprocessingDocument = WordprocessingDocument.Create(document, WordprocessingDocumentType.Document) - ' Insert other code here. - End Using -``` +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/word/create_a_package/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/word/create_a_package/vb/Program.vb#snippet1)] *** -The **using** statement provides a recommended -alternative to the typical .Create, .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 bracket 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 **wordDoc**. Because the class in the Open XML SDK -automatically saves and closes the object as part of its **System.IDisposable** implementation, and because -**Dispose** is automatically called when you exit the bracketed block, you do not have to explicitly call **Save** and **Close**─as -long as you use **using**. +[!include[Using Statement](../includes/word/using-statement.md)] Once you have created the Word document package, you can add parts to it. To add the main document part you call . Having done that, @@ -79,32 +62,20 @@ you can set about adding the document structure and text. The following is the complete code sample that you can use to create an Open XML word processing document package from XML content in the form -of **WordprocessingML** markup. In your -program, you can invoke the method **CreateNewWordDocument** by using the following -call: - -### [C#](#tab/cs-1) -```csharp - CreateNewWordDocument(@"C:\Users\Public\Documents\MyPkg4.docx"); -``` +of `WordprocessingML` markup. -### [Visual Basic](#tab/vb-1) -```vb - CreateNewWordDocument("C:\Users\Public\Documents\MyPkg4.docx") -``` -*** - -After you run the program, open the created file "myPkg4.docx" and +After you run the program, open the created file and examine its content; it should be one paragraph that contains the phrase "Hello world!" Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/create_a_package/cs/Program.cs)] +[!code-csharp[](../../samples/word/create_a_package/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/create_a_package/vb/Program.vb)] +[!code-vb[](../../samples/word/create_a_package/vb/Program.vb#snippet0)] +*** ## See also 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 8f2a83bc..8c1fe0b6 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 @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/08/2025 ms.localizationpriority: high --- # Get the contents of a document part from a package @@ -28,43 +28,23 @@ document programmatically. --------------------------------------------------------------------------------- ## Getting a WordprocessingDocument Object + The code starts with opening a package file by passing a file name to -one of the overloaded [Open()](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) methods (Visual Basic .NET Shared +one of the overloaded methods (Visual Basic .NET Shared method or C\# static method) of the class that takes a string and a Boolean value that specifies whether the file should be opened in read/write mode or not. In this case, the Boolean value is -**false** specifying that the file should be +`false` specifying that the file should be opened in read-only mode to avoid accidental changes. -### [C#](#tab/cs-0) -```csharp - // Open a Wordprocessing document for editing. - using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, false)) - { - // Insert other code here. - } -``` +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/word/get_the_contents_of_a_part_from_a_package/cs/Program.cs#snippet1)] -### [Visual Basic](#tab/vb-0) -```vb - ' Open a Wordprocessing document for editing. - Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, False) - ' Insert other code here. - End Using -``` +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/word/get_the_contents_of_a_part_from_a_package/vb/Program.vb#snippet1)] *** - -The **using** statement provides a recommended -alternative to the typical .Create, .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 **wordDoc**. Because the class in the Open XML SDK -automatically saves and closes the object as part of its **System.IDisposable** implementation, and because -the **Dispose** method is automatically called -when you exit the block; you do not have to explicitly call **Save** and **Close**─as -long as you use using. +[!include[Using Statement](../includes/word/using-statement.md)] --------------------------------------------------------------------------------- @@ -73,8 +53,9 @@ long as you use using. -------------------------------------------------------------------------------- ## Comments Element + In this how-to, you are going to work with comments. Therefore, it is -useful to familiarize yourself with the structure of the \<**comments**\> element. The following information +useful to familiarize yourself with the structure of the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification can be useful when working with this element. @@ -95,7 +76,7 @@ document: The **comments** element contains the single comment specified by this document in this example. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following XML schema fragment defines the contents of this element. @@ -109,88 +90,53 @@ The following XML schema fragment defines the contents of this element. -------------------------------------------------------------------------------- ## How the Sample Code Works -After you have opened the source file for reading, you create a **mainPart** object by instantiating the **MainDocumentPart**. Then you can create a reference -to the **WordprocessingCommentsPart** part of + +After you have opened the source file for reading, you create a `mainPart` object by instantiating the `MainDocumentPart`. Then you can create a reference +to the `WordprocessingCommentsPart` part of the document. -### [C#](#tab/cs-1) -```csharp - // To get the contents of a document part. - public static string GetCommentsFromDocument(string document) - { - string comments = null; - - using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true)) - { - MainDocumentPart mainPart = wordDoc.MainDocumentPart; - WordprocessingCommentsPart WordprocessingCommentsPart = mainPart.WordprocessingCommentsPart; -``` +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/word/get_the_contents_of_a_part_from_a_package/cs/Program.cs#snippet2)] -### [Visual Basic](#tab/vb-1) -```vb - ' To get the contents of a document part. - Public Shared Function GetCommentsFromDocument(ByVal document As String) As String - Dim comments As String = Nothing - - Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, True) - Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart - Dim WordprocessingCommentsPart As WordprocessingCommentsPart = mainPart.WordprocessingCommentsPart -``` +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/word/get_the_contents_of_a_part_from_a_package/vb/Program.vb#snippet2)] *** -You can then use a **StreamReader** object to -read the contents of the **WordprocessingCommentsPart** part of the document +You can then use a `StreamReader` object to +read the contents of the `WordprocessingCommentsPart` part of the document and return its contents. -### [C#](#tab/cs-2) -```csharp - using (StreamReader streamReader = new StreamReader(WordprocessingCommentsPart.GetStream())) - { - comments = streamReader.ReadToEnd(); - } - } - return comments; -``` +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/word/get_the_contents_of_a_part_from_a_package/cs/Program.cs#snippet3)] -### [Visual Basic](#tab/vb-2) -```vb - Using streamReader As New StreamReader(WordprocessingCommentsPart.GetStream()) - comments = streamReader.ReadToEnd() - End Using - Return comments -``` +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/word/get_the_contents_of_a_part_from_a_package/vb/Program.vb#snippet3)] *** -------------------------------------------------------------------------------- ## Sample Code -The following code retrieves the contents of a **WordprocessingCommentsPart** part contained in a -**WordProcessing** document package. You can -run the program by calling the **GetCommentsFromDocument** method as shown in the +The following code retrieves the contents of a `WordprocessingCommentsPart` part contained in a +`WordProcessing` document package. You can +run the program by calling the `GetCommentsFromDocument` method as shown in the following example. -### [C#](#tab/cs-3) -```csharp - string document = @"C:\Users\Public\Documents\MyPkg5.docx"; - GetCommentsFromDocument(document); -``` +### [C#](#tab/cs-4) +[!code-csharp[](../../samples/word/get_the_contents_of_a_part_from_a_package/cs/Program.cs#snippet4)] -### [Visual Basic](#tab/vb-3) -```vb - Dim document As String = "C:\Users\Public\Documents\MyPkg5.docx" - GetCommentsFromDocument(document) -``` +### [Visual Basic](#tab/vb-4) +[!code-vb[](../../samples/word/get_the_contents_of_a_part_from_a_package/vb/Program.vb#snippet4)] *** - Following is the complete code example in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/get_the_contents_of_a_part_from_a_package/cs/Program.cs)] +[!code-csharp[](../../samples/word/get_the_contents_of_a_part_from_a_package/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/get_the_contents_of_a_part_from_a_package/vb/Program.vb)] +[!code-vb[](../../samples/word/get_the_contents_of_a_part_from_a_package/vb/Program.vb#snippet0)] +*** -------------------------------------------------------------------------------- ## See also 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 fcfacedf..8d594ea4 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 @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/03/2025 ms.localizationpriority: medium --- # Remove a document part from a package @@ -28,42 +28,24 @@ programmatically. --------------------------------------------------------------------------------- ## Getting a WordprocessingDocument Object + The code example starts with opening a package file by passing a file -name as an argument to one of the overloaded [Open()](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) methods of the [DocumentFormat.OpenXml.Packaging.WordprocessingDocument](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument) +name as an argument to one of the overloaded methods of the + that takes a string and a Boolean value that specifies whether the file should be opened in read/write mode or not. In this case, the Boolean -value is **true** specifying that the file +value is `true` specifying that the file should be opened in read/write mode. -### [C#](#tab/cs-0) -```csharp - // Open a Wordprocessing document for editing. - using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true)) - { - // Insert other code here. - } -``` +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/word/remove_a_part_from_a_package/cs/Program.cs#snippet1)] -### [Visual Basic](#tab/vb-0) -```vb - ' Open a Wordprocessing document for editing. - Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, True) - ' Insert other code here. - End Using -``` +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/word/remove_a_part_from_a_package/vb/Program.vb#snippet1)] *** -The **using** statement provides a recommended -alternative to the typical .Create, .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 **wordDoc**. Because the class in the Open XML SDK -automatically saves and closes the object as part of its **System.IDisposable** implementation, and because -the **Dispose** method is automatically called -when you exit the block; you do not have to explicitly call **Save** and **Close**─as -long as you use **using**. +[!include[Using Statement](../includes/word/using-statement.md)] --------------------------------------------------------------------------------- @@ -73,7 +55,7 @@ long as you use **using**. -------------------------------------------------------------------------------- ## Settings Element The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification -introduces the settings element in a **PresentationML** package. +introduces the settings element in a `PresentationML` package. > This element specifies the settings that are applied to a > WordprocessingML document. This element is the root element of the @@ -94,65 +76,37 @@ introduces the settings element in a **PresentationML** package. > automatic tab stop increments of 0.5" using the **defaultTabStop** element, and no character level > white space compression using the **characterSpacingControl** element. > -> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -------------------------------------------------------------------------------- ## How the Sample Code Works -After you have opened the document, in the **using** statement, as a object, you create a -reference to the **DocumentSettingsPart** part. + +After you have opened the document, in the `using` statement, as a object, you create a +reference to the `DocumentSettingsPart` part. You can then check if that part exists, if so, delete that part from the -package. In this instance, the **settings.xml** +package. In this instance, the `settings.xml` part is removed from the package. -### [C#](#tab/cs-1) -```csharp - MainDocumentPart mainPart = wordDoc.MainDocumentPart; - if (mainPart.DocumentSettingsPart != null) - { - mainPart.DeletePart(mainPart.DocumentSettingsPart); - } -``` +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/word/remove_a_part_from_a_package/cs/Program.cs#snippet2)] -### [Visual Basic](#tab/vb-1) -```vb - Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart - If mainPart.DocumentSettingsPart IsNot Nothing Then - mainPart.DeletePart(mainPart.DocumentSettingsPart) - End If -``` +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/word/remove_a_part_from_a_package/vb/Program.vb#snippet2)] *** -------------------------------------------------------------------------------- ## Sample Code -The following code removes a document part from a package. To run the -program, call the method **RemovePart** like -this example. - -### [C#](#tab/cs-2) -```csharp - string document = @"C:\Users\Public\Documents\MyPkg6.docx"; - RemovePart(document); -``` - -### [Visual Basic](#tab/vb-2) -```vb - Dim document As String = "C:\Users\Public\Documents\MyPkg6.docx" - RemovePart(document) -``` -*** - -> [!NOTE] -> Before running the program on the test file, "MyPkg6.docs," for example, open the file by using the Open XML SDK Productivity Tool for Microsoft Office and examine its structure. After running the program, examine the file again, and you will notice that the **DocumentSettingsPart** part was removed. Following is the complete code example in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/remove_a_part_from_a_package/cs/Program.cs)] +[!code-csharp[](../../samples/word/remove_a_part_from_a_package/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/remove_a_part_from_a_package/vb/Program.vb)] +[!code-vb[](../../samples/word/remove_a_part_from_a_package/vb/Program.vb#snippet0)] +*** -------------------------------------------------------------------------------- ## See also 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 a8648b65..5d1b1527 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 @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/08/2025 ms.localizationpriority: medium --- # Replace the theme part in a word processing document @@ -27,55 +27,33 @@ document. In the sample code, you start by opening the word processing file by instantiating the class as shown in -the following **using** statement. In the same +the following `using` statement. In the same statement, you open the word processing file *document* by using the -[Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method, with the Boolean parameter set -to **true** to enable editing the document. - -### [C#](#tab/cs-0) -```csharp - using (WordprocessingDocument wordDoc = - WordprocessingDocument.Open(document, true)) - { - // Insert other code here. - } -``` + method, with the Boolean parameter set +to `true` to enable editing the document. -### [Visual Basic](#tab/vb-0) -```vb - Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, True) - ' Insert other code here. - End Using -``` -*** +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/word/replace_the_theme_part/cs/Program.cs#snippet1)] +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/word/replace_the_theme_part/vb/Program.vb#snippet1)] +*** -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 *wordDoc*. Because -the class in the -Open XML SDK automatically saves and closes the object as part of its -**System.IDisposable** implementation, and -because **Dispose** is automatically called -when you exit the block, you do not have to explicitly call **Save** and **Close**─as -long as you use **using**. +[!include[Using Statement](../includes/word/using-statement.md)] ## How to Change Theme in a Word Package If you would like to change the theme in a Word document, click the -ribbon **Page Layout** and then click **Themes**. The **Themes** pull-down -menu opens. To choose one of the built it themes and apply it to the +ribbon **Design** and then click **Themes**. The **Themes** pull-down +menu opens. To choose one of the built-in themes and apply it to the Word document, click the theme icon. You can also use the option **Browse for Themes...** to locate and apply a theme file in your computer. -## The Structure of the Theme Element +## The Structure of the Theme Element -The theme element constitutes of color, font, and format schemes. In +The theme element is constituted of color, font, and format schemes. In this how-to you learn how to change the theme programmatically. Therefore, it is useful to familiarize yourself with the theme element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification can @@ -93,28 +71,29 @@ how a theme can affect font, colors, backgrounds, fills, and effects for different objects in a presentation. end example] ![Theme sample](../media/a-theme01.gif) + In this example, we see how a theme can affect font, colors, backgrounds, fills, and effects for different objects in a presentation. *end example*] -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following table lists the possible child types of the Theme class. | PresentationML Element | Open XML SDK Class | Description | |---|---|---| -| custClrLst | [CustomColorList](/dotnet/api/documentformat.openxml.drawing.customcolorlist) |Custom Color List | -| extLst | [ExtensionList](/dotnet/api/documentformat.openxml.presentation.extensionlist) | Extension List | -| extraClrSchemeLst | [ExtraColorSchemeList](/dotnet/api/documentformat.openxml.drawing.theme.extracolorschemelist) | Extra Color Scheme List | -| objectDefaults | [ObjectDefaults](/dotnet/api/documentformat.openxml.drawing.theme.objectdefaults) | Object Defaults | -| themeElements | [ThemeElements](/dotnet/api/documentformat.openxml.drawing.theme.themeelements) | Theme Elements | +| `` | |Custom Color List | +| `` | | Extension List | +| `` | | Extra Color Scheme List | +| `` | | Object Defaults | +| `` | | Theme Elements | The following XML Schema fragment defines the four parts of the theme -element. The **themeElements** element is the +element. The `themeElements` element is the piece that holds the main formatting defined within the theme. The other parts provide overrides, defaults, and additions to the information -contained in **themeElements**. The complex -type defining a theme, **CT\_OfficeStyleSheet**, is defined in the following +contained in `themeElements`. The complex +type defining a theme, `CT_OfficeStyleSheet`, is defined in the following manner: ```xml @@ -130,68 +109,32 @@ manner: ``` -This complex type also holds a **CT\_OfficeArtExtensionList**, which is used for +This complex type also holds a `CT_OfficeArtExtensionList`, which is used for future extensibility of this complex type. ## How the Sample Code Works -After opening the file, you can instantiate the **MainDocumentPart** in the *wordDoc* object, and +After opening the file, you can instantiate the `MainDocumentPart` in the `wordDoc` object, and delete the old theme part. -### [C#](#tab/cs-1) -```csharp - public static void ReplaceTheme(string document, string themeFile) - { - using (WordprocessingDocument wordDoc = - WordprocessingDocument.Open(document, true)) - { - MainDocumentPart mainPart = wordDoc.MainDocumentPart; - - // Delete the old document part. - mainPart.DeletePart(mainPart.ThemePart); -``` - -### [Visual Basic](#tab/vb-1) -```vb - Public Shared Sub ReplaceTheme(ByVal document As String, ByVal themeFile As String) - Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, True) - Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/word/replace_the_theme_part/cs/Program.cs#snippet2)] - ' Delete the old document part. - mainPart.DeletePart(mainPart.ThemePart) -``` +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/word/replace_the_theme_part/vb/Program.vb#snippet2)] *** -You can then create add a new -object and add it to the **MainDocumentPart** -object. Then you add content by using a **StreamReader** and objects to copy the theme from the -*themeFile* to the object. +You can then create add a new +object and add it to the `MainDocumentPart` +object. Then you add content by using a `StreamReader` and objects to copy the theme from the +`themeFile` to the object. -### [C#](#tab/cs-2) -```csharp - // Add a new document part and then add content. - ThemePart themePart = mainPart.AddNewPart(); - - using (StreamReader streamReader = new StreamReader(themeFile)) - using (StreamWriter streamWriter = - new StreamWriter(themePart.GetStream(FileMode.Create))) - { - streamWriter.Write(streamReader.ReadToEnd()); - } -``` +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/word/replace_the_theme_part/cs/Program.cs#snippet3)] -### [Visual Basic](#tab/vb-2) -```vb - ' Add a new document part and then add content. - Dim themePart As ThemePart = mainPart.AddNewPart(Of ThemePart)() - - Using streamReader As New StreamReader(themeFile) - Using streamWriter As New StreamWriter(themePart.GetStream(FileMode.Create)) - streamWriter.Write(streamReader.ReadToEnd()) - End Using - End Using -``` +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/word/replace_the_theme_part/vb/Program.vb#snippet3)] *** @@ -202,36 +145,28 @@ in a word processing document with the theme part from another package. The theme file passed as the second argument must be a valid theme part in XML format (for example, Theme1.xml). You can extract this part from an existing document or theme file (.THMX) that has been renamed to be a -.Zip file. To call the method **ReplaceTheme** +.Zip file. To call the method `ReplaceTheme` you can use the following call example to copy the theme from the file -"Theme1.xml" to the file "MyPkg7.docx." +from `arg[1]` and to the file located at `arg[0]` -### [C#](#tab/cs-3) -```csharp - string document = @"C:\Users\Public\Documents\\MyPkg7.docx"; - string themeFile = @"C:\Users\Public\Documents\Theme1.xml"; - ReplaceTheme(document, themeFile); -``` +### [C#](#tab/cs-4) +[!code-csharp[](../../samples/word/replace_the_theme_part/cs/Program.cs#snippet4)] -### [Visual Basic](#tab/vb-3) -```vb - Dim document As String = "C:\Users\Public\Documents\\MyPkg7.docx" - Dim themeFile As String = "C:\Users\Public\Documents\Theme1.xml" - ReplaceTheme(document, themeFile) -``` +### [Visual Basic](#tab/vb-4) +[!code-vb[](../../samples/word/replace_the_theme_part/vb/Program.vb#snippet4)] *** -After you run the program open the Word file and notice the change in -font. +After you run the program open the Word file and notice the new theme changes. Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/replace_the_theme_part/cs/Program.cs)] +[!code-csharp[](../../samples/word/replace_the_theme_part/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/replace_the_theme_part/vb/Program.vb)] +[!code-vb[](../../samples/word/replace_the_theme_part/vb/Program.vb#snippet0)] +*** ## See also 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 9a73ba0a..4c72808a 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 @@ -27,70 +27,47 @@ processing document. --------------------------------------------------------------------------------- -## Getting a WordprocessingDocument Object +## Getting a WordprocessingDocument Object + In the sample code, you start by opening the word processing file by -instantiating the **** class as shown in -the following **using** statement. In the same -statement, you open the word processing file *document* by using the -**[Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open)** method, with the Boolean parameter set -to **true** to enable editing the document. - -### [C#](#tab/cs-0) -```csharp - using (WordprocessingDocument wordDoc = - WordprocessingDocument.Open(document, true)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - Using wordDoc As WordprocessingDocument = WordprocessingDocument.Open(document, True) - ' Insert other code here. - End Using -``` +instantiating the class as shown in +the following `using` statement. In the same +statement, you open the word processing file `document` by using the + method, with the Boolean parameter set +to `true` to enable editing the document. + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/word/search_and_replace_text_a_part/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/word/search_and_replace_text_a_part/vb/Program.vb#snippet1)] *** -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 *wordDoc*. Because -the class in the -Open XML SDK automatically saves and closes the object as part of its -**System.IDisposable** implementation, and -because **Dispose** is automatically called -when you exit the block, you do not have to explicitly call **Save** and **Close**─as -long as you use **using**. +[!include[Using Statement](../includes/word/using-statement.md)] -------------------------------------------------------------------------------- -## Sample Code +## Sample Code + The following example demonstrates a quick and easy way to search and replace. It may not be reliable because it retrieves the XML document in string format. Depending on the regular expression you might unintentionally replace XML tags and corrupt the document. If you simply want to search a document, but not replace the contents you can use -*MainDocumentPart.Document.InnerText*. +`MainDocumentPart.Document.InnerText`. This example also shows how to use a regular expression to search and -replace the text value, "Hello world!" stored in a word processing file -named "MyPkg8.docx," with the value "Hi Everyone!". To call the method -**SearchAndReplace**, you can use the following +replace the text value, "Hello World!" stored in a word processing file +with the value "Hi Everyone!". To call the method +`SearchAndReplace`, you can use the following example. -### [C#](#tab/cs-1) -```csharp - SearchAndReplace(@"C:\Users\Public\Documents\MyPkg8.docx"); -``` +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/word/search_and_replace_text_a_part/cs/Program.cs#snippet2)] -### [Visual Basic](#tab/vb-1) -```vb - SearchAndReplace("C:\Users\Public\Documents\MyPkg8.docx") -``` +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/word/search_and_replace_text_a_part/vb/Program.vb#snippet2)] *** @@ -100,15 +77,16 @@ the text, "Hello world!" The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/search_and_replace_text_a_part/cs/Program.cs)] +[!code-csharp[](../../samples/word/search_and_replace_text_a_part/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/search_and_replace_text_a_part/vb/Program.vb)] +[!code-vb[](../../samples/word/search_and_replace_text_a_part/vb/Program.vb#snippet0)] +*** -------------------------------------------------------------------------------- -## See also +## See also - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) -[Regular Expressions](/dotnet/standard/base-types/regular-expressions) +- [Regular Expressions](/dotnet/standard/base-types/regular-expressions) diff --git a/docs/general/introduction-to-markup-compatibility.md b/docs/general/introduction-to-markup-compatibility.md index 549dd965..fbbc0d69 100644 --- a/docs/general/introduction-to-markup-compatibility.md +++ b/docs/general/introduction-to-markup-compatibility.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/08/2025 ms.localizationpriority: high --- @@ -21,13 +21,13 @@ This topic introduces the markup compatibility features included in the Open XML ## Introduction -Suppose you have a Microsoft Word 2013 document that employs a feature introduced in Microsoft Office 2013. When you open that document in Microsoft Word 2010, an earlier version, what should happen? Ideally, you want the document to remain interoperable with Word 2010, even though Word 2010 will not understand the new feature. +Suppose you have a Microsoft Word 365 document that employs a feature introduced in Microsoft Office 365. When you open that document in Microsoft Word 2016, an earlier version, what should happen? Ideally, you want the document to remain interoperable with Word 2016, even though Word 2016 will not understand the new feature. -Consider also what should happen if you open that document in a hypothetical later version of Office. Here too, you want the document to work as expected. That is, you want the later version of Office to understand and support a feature employed in a document produced by Word 2013. +Consider also what should happen if you open that document in a hypothetical later version of Office. Here too, you want the document to work as expected. That is, you want the later version of Office to understand and support a feature employed in a document produced by Word 365. Open XML anticipates these scenarios. The Office Open XML File Formats specification describes facilities for achieving the above desired outcomes in [ECMA-376, Second Edition, Part 3 - Markup Compatibility and Extensibility](https://www.ecma-international.org/publications-and-standards/standards/ecma-376/). -The Open XML SDK supports markup compatibility in a way that makes it easy for you to achieve the above desired outcomes for and Office 2013 without having to necessarily become an expert in the specification details. +The Open XML SDK supports markup compatibility in a way that makes it easy for you to achieve the above desired outcomes for and Office 365 without having to necessarily become an expert in the specification details. ## What is markup compatibility? @@ -35,48 +35,44 @@ Open XML defines formats for word-processing, spreadsheet and presentation docum ## Markup compatibility in the Open XML file formats specification -Markup compatibility is discussed in [ECMA-376, Second Edition, Part 3 - Markup Compatibility and Extensibility](https://www.ecma-international.org/wp-content/uploads/ECMA-376-3_5th_edition_december_2015.zip), which is recommended reading to understand markup compatibility. The specification defines XML attributes to express compatibility rules, and XML elements to specify alternate content. For example, the **Ignorable** attribute specifies namespaces that can be ignored when they are not understood by the consuming application. Alternate-Content elements specify markup alternatives that can be chosen by an application at run time. For example, Word 2013 can choose only the markup alternative that it recognizes. The complete list of compatibility-rule attributes and alternate-content elements and their details can be found in the specification. +Markup compatibility is discussed in [ECMA-376, Second Edition, Part 3 - Markup Compatibility and Extensibility](https://www.ecma-international.org/wp-content/uploads/ECMA-376-3_5th_edition_december_2015.zip), which is recommended reading to understand markup compatibility. The specification defines XML attributes to express compatibility rules, and XML elements to specify alternate content. For example, the `Ignorable` attribute specifies namespaces that can be ignored when they are not understood by the consuming application. Alternate-Content elements specify markup alternatives that can be chosen by an application at run time. For example, Word 2013 can choose only the markup alternative that it recognizes. The complete list of compatibility-rule attributes and alternate-content elements and their details can be found in the specification. ## Open XML SDK support for markup compatibility The work that the Open XML SDK does for markup compatibility is detailed and subtle. However, the goal can be summarized as: using settings that you assign when you open a document, preprocess the document to: -1. Filter or remove any elements from namespaces that will not be understood (for example, Office 2013 document opened in Office 2010 context) +1. Filter or remove any elements from namespaces that will not be understood (for example, Office 365 document opened in Office 2016 context) 2. Process any markup compatibility elements and attributes as specified in the Open XML specification. The preprocessing performed is in accordance with ECMA-376, Second Edition: Part 3.13. -The Open XML SDK support for markup compatibility comes primarily in the form of two classes and in the manner in which content is preprocessed in accordance with ECMA-376, Second Edition. The two classes are **OpenSettings** and **MarkupCompatibilityProcessSettings**. Use the former to provide settings that apply to SDK behavior overall. Use the latter to supply one part of those settings, specifically those that apply to markup compatibility. +The Open XML SDK support for markup compatibility comes primarily in the form of two classes and in the manner in which content is preprocessed in accordance with ECMA-376, Second Edition. The two classes are `OpenSettings` and `MarkupCompatibilityProcessSettings`. Use the former to provide settings that apply to SDK behavior overall. Use the latter to supply one part of those settings, specifically those that apply to markup compatibility. ## Set the stage when you open -When you open a document using the Open XML SDK, you have the option of using an overload with a signature that accepts an instance of the **[OpenSettings](/dotnet/api/documentformat.openxml.packaging.opensettings)** class as a parameter. You use the open settings class to provide certain important settings that govern the behavior of the SDK. One set of settings in particular, stored in the **[MarkupCompatibilityProcessSettings](/dotnet/api/documentformat.openxml.packaging.opensettings.markupcompatibilityprocesssettings)** property, determines how markup compatibility elements and attributes are processed. You set the property to an instance of the **[MarkupCompatibilityProcessSettings](/dotnet/api/documentformat.openxml.packaging.markupcompatibilityprocesssettings)** class prior to opening a document. +When you open a document using the Open XML SDK, you have the option of using an overload with a signature that accepts an instance of the class as a parameter. You use the open settings class to provide certain important settings that govern the behavior of the SDK. One set of settings in particular, stored in the property, determines how markup compatibility elements and attributes are processed. You set the property to an instance of the class prior to opening a document. The class has the following properties: -- **[ProcessMode](/dotnet/api/documentformat.openxml.packaging.markupcompatibilityprocesssettings.processmode)** - Determines the parts that are preprocessed. +- - Determines the parts that are preprocessed. -- **[TargetFileFormatVersions](/dotnet/api/documentformat.openxml.packaging.markupcompatibilityprocesssettings.targetfileformatversions)** - Specifies the context that applies to preprocessing. +- - Specifies the context that applies to preprocessing. By default, documents are not preprocessed. If however you do specify open settings and provide markup compatibility process settings, then the document is preprocessed in accordance with those settings. -The following code example demonstrates how to call the Open method with an instance of the open settings class as a parameter. Notice that the **ProcessMode** and **TargetFileFormatVersions** properties are initialized as part of the **MarkupCompatiblityProcessSettings** constructor. +The following code example demonstrates how to call the Open method with an instance of the open settings class as a parameter. Notice that the `ProcessMode` and `TargetFileFormatVersions` properties are initialized as part of the `MarkupCompatiblityProcessSettings` constructor. ```csharp // Create instance of OpenSettings OpenSettings openSettings = new OpenSettings(); // Add the MarkupCompatibilityProcessSettings - openSettings.MarkupCompatibilityProcessSettings = - new MarkupCompatibilityProcessSettings( - MarkupCompatibilityProcessMode.ProcessAllParts, + openSettings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings( + MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2007); // Open the document with OpenSettings - using (WordprocessingDocument wordDocument = - WordprocessingDocument.Open(filename, - true, - openSettings)) + using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(filename, true, openSettings)) { // ... more code here } @@ -86,24 +82,23 @@ The following code example demonstrates how to call the Open method with an inst During preprocessing, the Open XML SDK removes elements and attributes in the markup compatibility namespace, removing the contents of unselected alternate-content elements, and interpreting compatibility-rule attributes as appropriate. This work is guided by the process mode and target file format versions properties. -The **ProcessMode** property determines the parts to be preprocessed. The content in *those* parts is filtered to contain only elements that are understood by the application version indicated in the **TargetFileFormatVersions** property. +The `ProcessMode` property determines the parts to be preprocessed. The content in *those* parts is filtered to contain only elements that are understood by the application version indicated in the `TargetFileFormatVersions` property. > [!WARNING] > Preprocessing affects what gets saved. When you save a file, the only markup that is saved is that which remains after preprocessing. ## Understand process mode -The process mode specifies which document parts should be preprocessed. You set this property to a member of the **[MarkupCompatibilityProcessMode](/dotnet/api/documentformat.openxml.packaging.markupcompatibilityprocessmode)** enumeration. The default value, **NoProcess**, indicates that no preprocessing is performed. Your application must be able to understand and handle any elements and attributes present in the document markup, including any of the elements and attributes in the Markup Compatibility namespace. +The process mode specifies which document parts should be preprocessed. You set this property to a member of the enumeration. The default value, `NoProcess`, indicates that no preprocessing is performed. Your application must be able to understand and handle any elements and attributes present in the document markup, including any of the elements and attributes in the Markup Compatibility namespace. -You might want to work on specific document parts while leaving the rest untouched. For example, you might want to ensure minimal modification to the file. In that case, specify **ProcessLoadedPartsOnly** for the process mode. With this setting, preprocessing and the associated filtering is only applied to the loaded document parts, not the entire document. +You might want to work on specific document parts while leaving the rest untouched. For example, you might want to ensure minimal modification to the file. In that case, specify `ProcessLoadedPartsOnly` for the process mode. With this setting, preprocessing and the associated filtering is only applied to the loaded document parts, not the entire document. -Finally, there is **ProcessAllParts**, which specifies what the name implies. When you choose this value, the entire document is preprocessed. +Finally, there is `ProcessAllParts`, which specifies what the name implies. When you choose this value, the entire document is preprocessed. ## Set the target file format version -The target file format versions property lets you choose to process markup compatibility content in either Office 2010 or Office 2013 context. Set the **TargetFileFormatVersions** property to a member of the **[FileFormatVersions](/dotnet/api/documentformat.openxml.fileformatversions)** enumeration. +The target file format versions property lets you choose to process markup compatibility content in the context of a specific Office version, e.g. Office 365. Set the `TargetFileFormatVersions` property to a member of the enumeration. -The default value, **Office2010**, means the SDK will assume that namespaces defined in Office 2010 are understood, but not namespaces defined in Office 2013. Thus, during preprocessing, the SDK will ignore the namespaces defined in Office 2013 and choose the Office 2010 compatible alternate-content. +The default value, `Office2007`, means the SDK will assume that namespaces defined in Office 2007 are understood, but not namespaces defined in Office 2010 or later. Thus, during preprocessing, the SDK will ignore the namespaces defined in newer Office versions and choose the Office 2007 compatible alternate-content. -When you set the target file format versions property to **Office2013**, the Open XML SDK assumes that all of the namespaces defined in Office 2010 and Office 2013 are understood, does not ignore any content defined under Office 2013, and will choose -the Office 2013 compatible alternate-content. +When you set the target file format versions property to `Office2013`, the Open XML SDK assumes that all of the namespaces defined in Office 2010 and Office 2013 are understood, does not ignore any content defined under Office 2013, and will choose the Office 2013 compatible alternate-content. diff --git a/docs/general/overview.md b/docs/general/overview.md index 04771389..32a0e485 100644 --- a/docs/general/overview.md +++ b/docs/general/overview.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/03/2025 ms.localizationpriority: high --- @@ -25,24 +25,24 @@ This section provides how-to topics for working with documents and packages usin - [Introduction to markup compatibility](introduction-to-markup-compatibility.md) -- [Add a new document part that receives a relationship ID to a package](how-to-add-a-new-document-part-that-receives-a-relationship-id-to-a-package.md) +- [Add a new document part that receives a relationship ID to a package](how-to-add-a-new-document-part-that-receives-a-relationship-id-to-a-package.md) -- [Add a new document part to a package](how-to-add-a-new-document-part-to-a-package.md) +- [Add a new document part to a package](how-to-add-a-new-document-part-to-a-package.md) -- [Copy the contents of an Open XML package part to a document part in a different package](how-to-copy-the-contents-of-an-open-xml-package-part-to-a-document-part-in-a-dif.md) +- [Copy the contents of an Open XML package part to a document part in a different package](how-to-copy-the-contents-of-an-open-xml-package-part-to-a-document-part-in-a-dif.md) -- [Create a package](how-to-create-a-package.md) +- [Create a package](how-to-create-a-package.md) -- [Get the contents of a document part from a package](how-to-get-the-contents-of-a-document-part-from-a-package.md) +- [Get the contents of a document part from a package](how-to-get-the-contents-of-a-document-part-from-a-package.md) -- [Remove a document part from a package](how-to-remove-a-document-part-from-a-package.md) +- [Remove a document part from a package](how-to-remove-a-document-part-from-a-package.md) -- [Replace the theme part in a word processing document](how-to-replace-the-theme-part-in-a-word-processing-document.md) +- [Replace the theme part in a word processing document](how-to-replace-the-theme-part-in-a-word-processing-document.md) -- [Search and replace text in a document part](how-to-search-and-replace-text-in-a-document-part.md) +- [Search and replace text in a document part](how-to-search-and-replace-text-in-a-document-part.md) - [Diagnostic IDs](diagnosticids.md) -## Related sections +## Related sections -- [Getting started with the Open XML SDK for Office](../getting-started.md) +- [Getting started with the Open XML SDK for Office](../getting-started.md) diff --git a/docs/includes/presentation/modern-comment-description.md b/docs/includes/presentation/modern-comment-description.md new file mode 100644 index 00000000..d3bb6e83 --- /dev/null +++ b/docs/includes/presentation/modern-comment-description.md @@ -0,0 +1,68 @@ +## The Structure of the Modern Comment Element + +The following XML element specifies a single comment. +It contains the text of the comment (`t`) and attributes referring to its author +(`authorId`), date time created (`created`), and comment id (`id`). + +```xml + + + + + + + Needs more cowbell + + + + +``` + +The following tables list the definitions of the possible child elements and attributes +of the `cm` (comment) element. For the complete definition see [MS-PPTX 2.16.3.3 CT_Comment](/openspecs/office_standards/ms-pptx/161bc2c9-98fc-46b7-852b-ba7ee77e2e54) + + +| Attribute | Definition | +|---|---| +| id | Specifies the ID of a comment or a comment reply. | +| authorId | Specifies the author ID of a comment or a comment reply. | +| status | Specifies the status of a comment or a comment reply. | +| created | Specifies the date time when the comment or comment reply is created. | +| startDate | Specifies start date of the comment. | +| dueDate | Specifies due date of the comment. | +| assignedTo | Specifies a list of authors to whom the comment is assigned. | +| complete | Specifies the completion percentage of the comment. | +| title | Specifies the title for a comment. | + +| Child Element | Definition | +|------------|---------------| +| pc:sldMkLst | Specifies a content moniker that identifies the slide to which the comment is anchored. | +| ac:deMkLst | Specifies a content moniker that identifies the drawing element to which the comment is anchored. | +| ac:txMkLst | Specifies a content moniker that identifies the text character range to which the comment is anchored. | +| unknownAnchor | Specifies an unknown anchor to which the comment is anchored. | +| pos | Specifies the position of the comment, relative to the top-left corner of the first object to which the comment is anchored. | +| replyLst | Specifies the list of replies to the comment. | +| txBody | Specifies the text of a comment or a comment reply. | +| extLst | Specifies a list of extensions for a comment or a comment reply. | + + + +The following XML schema example defines the members of the `cm` element in addition to the required and +optional attributes. + +```xml + + + + + + + + + + + + + + +``` \ No newline at end of file diff --git a/docs/includes/presentation/structure.md b/docs/includes/presentation/structure.md index ba3d3091..7a16c732 100644 --- a/docs/includes/presentation/structure.md +++ b/docs/includes/presentation/structure.md @@ -1,13 +1,13 @@ ## Basic Presentation Document Structure -The basic document structure of a **PresentationML** document consists of a number of +The basic document structure of a `PresentationML` document consists of a number of parts, among which is the main part that contains the presentation definition. The following text from the [!include[ISO/IEC 29500 URL](../iso-iec-29500-link.md)] specification -introduces the overall form of a **PresentationML** package. +introduces the overall form of a `PresentationML` package. -> The main part of a **PresentationML** package +> The main part of a `PresentationML` package > starts with a presentation root element. That element contains a -> presentation, which, in turn, refers to a **slide** list, a *slide master* list, a *notes +> presentation, which, in turn, refers to a *slide* list, a *slide master* list, a *notes > master* list, and a *handout master* list. The slide list refers to > all of the slides in the presentation; the slide master list refers to > the entire slide masters used in the presentation; the notes master @@ -23,15 +23,15 @@ introduces the overall form of a **PresentationML** package. > maintaining the presentation slide deck. A note is a reminder or piece > of text intended for the presenter or the audience. > -> Other features that a **PresentationML** +> Other features that a `PresentationML` > document can include the following: *animation*, *audio*, *video*, and > *transitions* between slides. > -> A **PresentationML** document is not stored +> A `PresentationML` document is not stored > as one large body in a single part. Instead, the elements that > implement certain groupings of functionality are stored in separate -> parts. For example, all comments in a document are stored in one -> comment part while each slide has its own part. +> parts. For example, all authors in a document are stored in one +> authors part while each slide has its own part. > > [!include[ISO/IEC 29500 version](../iso-iec-29500-version.md)] @@ -65,13 +65,13 @@ two slides denoted by the IDs 267 and 256. Using the Open XML SDK, you can create document structure and content using strongly-typed classes that correspond to PresentationML -elements. You can find these classes in the [DocumentFormat.OpenXml.Presentation](/dotnet/api/documentformat.openxml.presentation) +elements. You can find these classes in the namespace. The following table lists the class names of the classes that -correspond to the **sld**, **sldLayout**, **sldMaster**, and **notesMaster** elements. +correspond to the `sld`, `sldLayout`, `sldMaster`, and `notesMaster` elements. -| PresentationML Element | Open XML SDK Class | Description | +| **PresentationML Element** | **Open XML SDK Class** | **Description** | |---|---|---| -| sld | [Slide](/dotnet/api/documentformat.openxml.presentation.slide) | Presentation Slide. It is the root element of SlidePart. | -| sldLayout | [SlideLayout](/dotnet/api/documentformat.openxml.presentation.slidelayout) | Slide Layout. It is the root element of SlideLayoutPart. | -| sldMaster | [SlideMaster](/dotnet/api/documentformat.openxml.presentation.slidemaster) | Slide Master. It is the root element of SlideMasterPart. | -| notesMaster | [NotesMaster](/dotnet/api/documentformat.openxml.presentation.notesmaster) | Notes Master (or handoutMaster). It is the root element of NotesMasterPart. | \ No newline at end of file +| `` | | Presentation Slide. It is the root element of SlidePart. | +| `` | | Slide Layout. It is the root element of SlideLayoutPart. | +| `` | | Slide Master. It is the root element of SlideMasterPart. | +| `` | | Notes Master (or handoutMaster). It is the root element of NotesMasterPart. | \ No newline at end of file diff --git a/docs/includes/presentation/using-statement.md b/docs/includes/presentation/using-statement.md new file mode 100644 index 00000000..d2cc37e4 --- /dev/null +++ b/docs/includes/presentation/using-statement.md @@ -0,0 +1,5 @@ +With v3.0.0+ the method +has been removed in favor of relying on the [using statement](/dotnet/csharp/language-reference/statements/using). +This ensures that the method 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 diff --git a/docs/includes/spreadsheet/open-spreadsheet.md b/docs/includes/spreadsheet/open-spreadsheet.md new file mode 100644 index 00000000..a1c0db01 --- /dev/null +++ b/docs/includes/spreadsheet/open-spreadsheet.md @@ -0,0 +1,17 @@ +## Getting a SpreadsheetDocument Object + +In the Open XML SDK, the 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 + methods. Several are provided, each +with a different signature. The sample code in this topic uses the @"DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open*?text=Open(String, Boolean)" 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`. \ No newline at end of file diff --git a/docs/includes/spreadsheet/spreadsheet-object.md b/docs/includes/spreadsheet/spreadsheet-object.md new file mode 100644 index 00000000..d2c8a6d6 --- /dev/null +++ b/docs/includes/spreadsheet/spreadsheet-object.md @@ -0,0 +1,55 @@ +## The SpreadsheetDocument Object + +The basic document structure of a SpreadsheetML document consists of the + and elements, which reference the +worksheets in the . A separate XML file is created +for each . For example, the SpreadsheetML +for a workbook that has two worksheets name MySheet1 and MySheet2 is +located in the Workbook.xml file and is as follows. + +```xml + + + + + + + +``` + +The worksheet XML files contain one or more block level elements such as +. `sheetData` represents the cell table and contains +one or more elements. A `row` contains one or more elements. Each cell contains a 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 as follows. + +```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** | +|--|--|--| +| ``||The root element for the main document part. | +| ``||The container for the block level structures such as sheet, fileVersion, and |others specified in the [!include[ISO/IEC 29500 URL](../iso-iec-29500-link.md)] specification. +| ``||A sheet that points to a sheet definition file. | +| ``||A sheet definition file that contains the sheet data. | +| ``||The cell table, grouped together by rows. | +| ``||A row in the cell table. | +| ``||A cell in a row. | +| ``||The value of a cell. | \ No newline at end of file diff --git a/docs/includes/spreadsheet/structure.md b/docs/includes/spreadsheet/structure.md index 51b9e03e..7bb22036 100644 --- a/docs/includes/spreadsheet/structure.md +++ b/docs/includes/spreadsheet/structure.md @@ -1,6 +1,6 @@ ## Basic structure of a spreadsheetML document -The basic document structure of a **SpreadsheetML** document consists of the [Sheets](/dotnet/api/documentformat.openxml.spreadsheet.sheets) and [Sheet](/dotnet/api/documentformat.openxml.spreadsheet.sheet) elements, which reference the worksheets in the workbook. A separate XML file is created for each worksheet. For example, the **SpreadsheetML** for a [Workbook](/dotnet/api/documentformat.openxml.spreadsheet.workbook) that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example. +The basic document structure of a `SpreadsheetML` document consists of the and elements, which reference the worksheets in the workbook. A separate XML file is created for each worksheet. For example, the `SpreadsheetML` for a that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example. ```xml @@ -13,9 +13,9 @@ The basic document structure of a **SpreadsheetML** document consists of the [Sh ``` The worksheet XML files contain one or more block level elements such as -[sheetData](/dotnet/api/documentformat.openxml.spreadsheet.sheetdata) represents the cell table and contains -one or more [Row](/dotnet/api/documentformat.openxml.spreadsheet.row) elements. A **row** contains one or more [Cell](/dotnet/api/documentformat.openxml.spreadsheet.cell) elements. Each cell contains a [CellValue](/dotnet/api/documentformat.openxml.spreadsheet.cellvalue) element that represents the value -of the cell. For example, the **SpreadsheetML** + represents the cell table and contains +one or more elements. A `row` contains one or more elements. Each cell contains a 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. @@ -34,18 +34,18 @@ code example. ``` 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 +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. +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 [!include[ISO/IEC 29500 URL](../iso-iec-29500-link.md)] 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. | +| `` | DocumentFormat.OpenXML.Spreadsheet.Workbook | The root element for the main document part. | +| `` | DocumentFormat.OpenXML.Spreadsheet.Sheets | The container for the block level structures such as sheet, fileVersion, and others specified in the [!include[ISO/IEC 29500 URL](../iso-iec-29500-link.md)] specification. | +| `` | DocumentFormat.OpenXml.Spreadsheet.Sheet | A sheet that points to a sheet definition file. | +| `` | DocumentFormat.OpenXML.Spreadsheet. Worksheet | A sheet definition file that contains the sheet data. | +| `` | DocumentFormat.OpenXML.Spreadsheet.SheetData | The cell table, grouped together by rows. | +| `` | DocumentFormat.OpenXml.Spreadsheet.Row | A row in the cell table. | +| `` | DocumentFormat.OpenXml.Spreadsheet.Cell | A cell in a row. | +| `` | DocumentFormat.OpenXml.Spreadsheet.CellValue | The value of a cell. | diff --git a/docs/includes/word/structure.md b/docs/includes/word/structure.md index f6dbc699..56f1614a 100644 --- a/docs/includes/word/structure.md +++ b/docs/includes/word/structure.md @@ -1,6 +1,6 @@ ## Structure of a WordProcessingML Document -The basic document structure of a **WordProcessingML** document consists of the **document** and **body** elements, followed by one or more block level elements such as **p**, which represents a paragraph. A paragraph contains one or more **r** elements. The **r** stands for run, which is a region of text with a common set of properties, such as formatting. A run contains one or more **t** elements. The **t** element contains a range of text. The following code example shows the **WordprocessingML** markup for a document that contains the text "Example text." +The basic document structure of a `WordProcessingML` document consists of the `document` and `body` elements, followed by one or more block level elements such as `p`, which represents a paragraph. A paragraph contains one or more `r` elements. The `r` stands for run, which is a region of text with a common set of properties, such as formatting. A run contains one or more `t` elements. The `t` element contains a range of text. The following code example shows the `WordprocessingML` markup for a document that contains the text "Example text." ```xml @@ -14,14 +14,14 @@ The basic document structure of a **WordProcessingML** document consists of the ``` -Using the Open XML SDK, you can create document structure and content using strongly-typed classes that correspond to **WordprocessingML** elements. You will find these classes in the [DocumentFormat.OpenXml.Wordprocessing](/dotnet/api/documentformat.openxml.wordprocessing) namespace. The following table lists the class names of the classes that correspond to the **document**, **body**, **p**, **r**, and **t** elements. +Using the Open XML SDK, you can create document structure and content using strongly-typed classes that correspond to `WordprocessingML` elements. You will find these classes in the namespace. The following table lists the class names of the classes that correspond to the `document`, `body`, `p`, `r`, and `t` elements. -| WordprocessingML Element | Open XML SDK Class | Description | +| **WordprocessingML Element** | **Open XML SDK Class** | **Description** | |---|---|---| -| document | [Document](/dotnet/api/documentformat.openxml.wordprocessing.document) | The root element for the main document part. | -| body | [Body](/dotnet/api/documentformat.openxml.wordprocessing.body) | The container for the block level structures such as paragraphs, tables, annotations and others specified in the [!include[ISO/IEC 29500 URL](../iso-iec-29500-link.md)] specification. | -| p | [Paragraph](/dotnet/api/documentformat.openxml.wordprocessing.paragraph) | A paragraph. | -| r | [Run](/dotnet/api/documentformat.openxml.wordprocessing.run) | A run. | -| t | [Text](/dotnet/api/documentformat.openxml.wordprocessing.text) | A range of text. | +| `` | | The root element for the main document part. | +| `` | | The container for the block level structures such as paragraphs, tables, annotations and others specified in the [!include[ISO/IEC 29500 URL](../iso-iec-29500-link.md)] specification. | +| `

` | | A paragraph. | +| `` | | A run. | +| `` | | A range of text. | For more information about the overall structure of the parts and elements of a WordprocessingML document, see [Structure of a WordprocessingML document](../../word/structure-of-a-wordprocessingml-document.md). \ No newline at end of file diff --git a/docs/includes/word/using-statement.md b/docs/includes/word/using-statement.md new file mode 100644 index 00000000..68e0d9f4 --- /dev/null +++ b/docs/includes/word/using-statement.md @@ -0,0 +1,10 @@ +With v3.0.0+ the method +has been removed in favor of relying on the [using statement](/dotnet/csharp/language-reference/statements/using). +It ensures that the method 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. Because the class in the Open XML SDK +automatically saves and closes the object as part of its implementation, and because + is automatically called when you +exit the block, you do not have to explicitly call or + as long as you use a `using` statement. \ No newline at end of file diff --git a/docs/media/custom-property-menu.png b/docs/media/custom-property-menu.png new file mode 100644 index 00000000..8cdc0edc Binary files /dev/null and b/docs/media/custom-property-menu.png differ diff --git a/docs/migration/migrate-v2-to-v3.md b/docs/migration/migrate-v2-to-v3.md index 4b42b2fb..199c92ef 100644 --- a/docs/migration/migrate-v2-to-v3.md +++ b/docs/migration/migrate-v2-to-v3.md @@ -93,7 +93,7 @@ if (theCell.DataType.Value == CellValues.SharedString) ### OpenXmlElementList is now a struct -[OpenXmlElementList](/dotnet/api/documentformat.openxml.openxmlelementlist) is now a struct. It still implements `IEnumerable` in addition to `IReadOnlyList` where available. + is now a struct. It still implements `IEnumerable` in addition to `IReadOnlyList` where available. **Action needed**: Because this is a struct, code patterns that may have a `null` result will now be a `OpenXmlElementList?` instead. Null checks will be flagged by the compiler and the value itself will need to be unwrapped, such as: @@ -117,7 +117,7 @@ This type is used to enumerate pairs within a part and caused many unnecessary a ### OpenXmlPartReader no longer knows about all parts -In previous versions, [OpenXmlPartReader](/dotnet/api/documentformat.openxml.openxmlpartreader) knew about about all strongly typed part. In order to reduce coupling required for better AOT scenarios, we now have typed readers for known packages: `WordprocessingDocumentPartReader`, `SpreadsheetDocumentPartReader`, and `PresentationDocumentPartReader`. +In previous versions, knew about about all strongly typed part. In order to reduce coupling required for better AOT scenarios, we now have typed readers for known packages: `WordprocessingDocumentPartReader`, `SpreadsheetDocumentPartReader`, and `PresentationDocumentPartReader`. **Action needed**: Replace usage of `OpenXmlPartReader` with document specific readers if needed. If creating a part reader from a known package, please use the constructors that take an existing `OpenXmlPart` which will then create the expected strongly typed parts. diff --git a/docs/presentation/how-to-add-a-comment-to-a-slide-in-a-presentation.md b/docs/presentation/how-to-add-a-comment-to-a-slide-in-a-presentation.md index 0fcef1de..5a414143 100644 --- a/docs/presentation/how-to-add-a-comment-to-a-slide-in-a-presentation.md +++ b/docs/presentation/how-to-add-a-comment-to-a-slide-in-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: 01/02/2025 ms.localizationpriority: medium --- @@ -21,77 +21,91 @@ This topic shows how to use the classes in the Open XML SDK for Office to add a comment to the first slide in a presentation programmatically. +> [!NOTE] +> This sample is for PowerPoint modern comments. For classic comments view +> the [archived sample on GitHub](https://github.com/OfficeDev/open-xml-docs/blob/7002d692ab4abc629d617ef6a0214fc2bf2910c8/docs/how-to-add-a-comment-to-a-slide-in-a-presentation.md). + [!include[Structure](../includes/presentation/structure.md)] -## The Structure of the Comment Element - -A comment is a text note attached to a slide, with the primary purpose -of enabling readers of a presentation to provide feedback to the -presentation author. Each comment contains an unformatted text string -and information about its author, and is attached to a particular -location on a slide. Comments can be visible while editing the -presentation, but do not appear when a slide show is given. The -displaying application decides when to display comments and determines -their visual appearance. - -The following XML element specifies a single comment attached to a -slide. It contains the text of the comment (**text**), its position on the slide (**pos**), and attributes referring to its author -(**authorId**), date and time (**dt**), and comment index (**idx**). - -```xml - - - Add diagram to clarify. - -``` - -The following table contains the definitions of the members and -attributes of the **cm** (comment) element. - -| Member/Attribute | Definition | -|---|---| -| authorId | Refers to the ID of an author in the comment author list for the document. | -| dt | The date and time this comment was last modified. | -| idx | An identifier for this comment that is unique within a list of all comments by this author in this document. An author's first comment in a document has index 1. | -| pos | The positioning information for the placement of a comment on a slide surface. | -| text | Comment text. | -| extLst | Specifies the extension list with modification ability within which all future extensions of element type ext are defined. The extension list along with corresponding future extensions is used to extend the storage capabilities of the PresentationML framework. This allows for various new kinds of data to be stored natively within the framework. | - - -The following XML schema code example defines the members of the **cm** element in addition to the required and -optional attributes. - -```xml - - - - - - - - - - -``` +[!include[description of a comment](../includes/presentation/modern-comment-description.md)] -## Sample Code +## How the Sample Code Works + +The sample code opens the presentation document in the using statement. Then it instantiates the CommentAuthorsPart, and verifies that there is an existing comment authors part. If there is not, it adds one. + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/add_comment/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/add_comment/vb/Program.vb#snippet1)] +*** + +The code determines whether there is an existing PowerPoint author part in the presentation part; if not, it adds one, then checks if there is an authors list +and adds one if it is missing. It also verifies that the author that is passed in is on the list of existing authors; if so, it assigns the existing author ID. If not, it adds a new author to the list of authors and assigns an author ID and the parameter values. + +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/add_comment/cs/Program.cs#snippet2)] + +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/add_comment/vb/Program.vb#snippet2)] +*** + +Next the code determines if there is a slide id and returns if one does not exist + +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/presentation/add_comment/cs/Program.cs#snippet3)] -The following code example shows how to add comments to a -presentation document. To run the program, you can pass in the arguments: +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/presentation/add_comment/vb/Program.vb#snippet3)] +*** + +In the segment below, the code gets the relationship ID. If it exists, it is used to find the slide part +otherwise the first slide in the slide parts enumerable is taken. Then it verifies that there is +a PowerPoint comments part for the slide and if not adds one. + +### [C#](#tab/cs-4) +[!code-csharp[](../../samples/presentation/add_comment/cs/Program.cs#snippet4)] + +### [Visual Basic](#tab/vb-4) +[!code-vb[](../../samples/presentation/add_comment/vb/Program.vb#snippet4)] +*** + +Below the code creates a new modern comment then adds a comment list to the PowerPoint comment part +if one does not exist and adds the comment to that comment list. + +### [C#](#tab/cs-5) +[!code-csharp[](../../samples/presentation/add_comment/cs/Program.cs#snippet5)] + +### [Visual Basic](#tab/vb-5) +[!code-vb[](../../samples/presentation/add_comment/vb/Program.vb#snippet5)] +*** + +With modern comments the slide needs to have the correct extension list and extension. +The following code determines if the slide already has a SlideExtensionList and +SlideExtension and adds them to the slide if they are not present. + +### [C#](#tab/cs-6) +[!code-csharp[](../../samples/presentation/add_comment/cs/Program.cs#snippet6)] + +### [Visual Basic](#tab/vb-6) +[!code-vb[](../../samples/presentation/add_comment/vb/Program.vb#snippet6)] +*** + +## Sample Code -```dotnetcli -dotnet run -- [filePath] [initials] [name] [test ...] -``` +Following is the complete code sample showing how to add a new comment with +a new or existing author to a slide with or without existing comments. > [!NOTE] > To get the exact author name and initials, open the presentation file and click the **File** menu item, and then click **Options**. The **PowerPointOptions** window opens and the content of the **General** tab is displayed. The author name and initials must match the **User name** and **Initials** in this tab. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/add_comment/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/add_comment/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/add_comment/vb/Program.vb)] +[!code-vb[](../../samples/presentation/add_comment/vb/Program.vb#snippet0)] +*** ## See also diff --git a/docs/presentation/how-to-add-a-video-to-a-slide-in-a-presentation.md b/docs/presentation/how-to-add-a-video-to-a-slide-in-a-presentation.md new file mode 100644 index 00000000..8ea4ea4b --- /dev/null +++ b/docs/presentation/how-to-add-a-video-to-a-slide-in-a-presentation.md @@ -0,0 +1,138 @@ +--- + +api_name: +- Microsoft.Office.DocumentFormat.OpenXML.Packaging +api_type: +- schema +ms.assetid: 536c94b5-dd25-4173-ad6a-b72b95dd7f31 +title: 'How to: Add a video to a slide in a presentation' +ms.suite: office + +ms.author: o365devx +author: o365devx +ms.topic: conceptual +ms.date: 04/03/2025 +ms.localizationpriority: medium +--- + +# Add a video to a slide in a presentation + +This topic shows how to use the classes in the Open XML SDK for +Office to add a video to the first slide in a presentation +programmatically. + +## Getting a Presentation Object + +In the Open XML SDK, the class represents a +presentation document package. To work with a presentation document, +first create an instance of the **PresentationDocument** class, and then work with +that instance. To create the class instance from the document call the + method that uses a file path, and a +Boolean value as the second parameter to specify whether a document is +editable. To open a document for read/write, specify the value `true` for this parameter as shown in the following +`using` statement. In this code, the file +parameter is a string that represents the path for the file from which +you want to open the document. + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/add_video/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/add_video/vb/Program.vb#snippet1)] +*** + + +[!include[Using Statement](../includes/presentation/using-statement.md)] `ppt`. + + +## The Structure of the Video From File + +The PresentationML document consists of a number of parts, among which is the Picture (``) element. + +The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the overall form of a `PresentationML` package. + +Video File (``) specifies the presence of a video file. It is defined within the non-visual properties of an object. The video shall be attached to an object as this is how it is represented within the document. The actual playing of the video however is done within the timing node list that is specified under the timing element. + +Consider the following `Picture` object that has a video attached to it. + +```xml + + + + + + + + + + + + + +``` + +In the above example, we see that there is a single videoFile element attached to this picture. This picture is placed within the document just as a normal picture or shape would be. The id of this picture, namely 7 in this case, is used to refer to this videoFile element from within the timing node list. The Linked relationship id is used to retrieve the actual video file for playback purposes. + +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] + +The following XML Schema fragment defines the contents of videoFile. + +```xml + + + + + + +``` + +## How the Sample Code Works + +After opening the presentation file for read/write access in the `using` statement, the code gets the presentation +part from the presentation document. Then it gets the relationship ID of +the last slide, and gets the slide part from the relationship ID. + + +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/add_video/cs/Program.cs#snippet2)] + +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/add_video/vb/Program.vb#snippet2)] +*** + +The code first creates a media data part for the video file to be added. With the video file stream open, it feeds the media data part object. Next, video and media relationship references are added to the slide using the provided embedId for future reference to the video file and mediaEmbedId for media reference. + +An image part is then added with a sample picture to be used as a placeholder for the video. A picture object is created with various elements, such as Non-Visual Drawing Properties (``), which specify non-visual canvas properties. This allows for additional information that does not affect the appearance of the picture to be stored. The `` element, explained above, is also included. The HyperLinkOnClick (``) element specifies the on-click hyperlink information to be applied to a run of text or image. When the hyperlink text or image is clicked, the link is fetched. Non-Visual Picture Drawing Properties (``) specify the non-visual properties for the picture canvas. For a detailed explanation of the elements used, please refer to [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] + +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/presentation/add_video/cs/Program.cs#snippet3)] + +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/presentation/add_video/vb/Program.vb#snippet3)] +*** + +Next Media(CT_Media) element is created with use of previously referenced mediaEmbedId(Embedded Picture Reference). The Blip element is also added; this element specifies the existence of an image (binary large image or picture) and contains a reference to the image data. Blip's Embed attribute is used to specify a placeholder image in the Image Part created previously. + +### [C#](#tab/cs-4) +[!code-csharp[](../../samples/presentation/add_video/cs/Program.cs#snippet4)] + +### [Visual Basic](#tab/vb-4) +[!code-vb[](../../samples/presentation/add_video/vb/Program.vb#snippet4)] +*** + +All other elements such Offset(``), Stretch(``), FillRectangle(``), are appended to the ShapeProperties(``) and ShapeProperties are appended to the Picture element(``). Finally the picture element that incudes video is added to the ShapeTree(``) of the slide. + +Following is the complete sample code that you can use to add video to the slide. + +## Sample Code + +### [C#](#tab/cs) +[!code-csharp[](../../samples/presentation/add_video/cs/Program.cs#snippet0)] + +### [Visual Basic](#tab/vb) +[!code-vb[](../../samples/presentation/add_video/vb/Program.vb#snippet0)] +*** + +## See also + +- [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) diff --git a/docs/presentation/how-to-add-an-audio-to-a-slide-in-a-presentation.md b/docs/presentation/how-to-add-an-audio-to-a-slide-in-a-presentation.md new file mode 100644 index 00000000..03daef46 --- /dev/null +++ b/docs/presentation/how-to-add-an-audio-to-a-slide-in-a-presentation.md @@ -0,0 +1,133 @@ +--- + +api_name: +- Microsoft.Office.DocumentFormat.OpenXML.Packaging +api_type: +- schema +ms.assetid: 0265732e-d81a-4654-b0ba-d9d87e544f7c +title: 'How to: Add an audio file to a slide in a presentation' +ms.suite: office + +ms.author: o365devx +author: o365devx +ms.topic: conceptual +ms.date: 03/31/2025 +ms.localizationpriority: medium +--- + +# Add an audio file to a slide in a presentation + +This topic shows how to use the classes in the Open XML SDK for +Office to add an audio file to the last slide in a presentation +programmatically. + +## Getting a Presentation Object + +In the Open XML SDK, the class represents a presentation document package. To work with a presentation document, +first create an instance of the `PresentationDocument` class, and then work with +that instance. To create the class instance from the document call the method that uses a file path, and a +Boolean value as the second parameter to specify whether a document is editable. To open a document for read/write, specify the value `true` for this parameter as shown in the following +`using` statement. In this code, the file parameter is a string that represents the path for the file from which you want to open the document. + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/add_audio/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/add_audio/vb/Program.vb#snippet1)] +*** + + +[!include[Using Statement](../includes/presentation/using-statement.md)] `ppt`. + + +## The Structure of the Audio From File + +The PresentationML document consists of a number of parts, among which is the Picture (``) element. + +The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the overall form of a `PresentationML` package. + +Audio File (``) specifies the presence of an audio file. This element is specified within the non-visual properties of an object. The audio shall be attached to an object as this is how it is represented within the document. The actual playing of the audio however is done within the timing node list that is specified under the timing element. + +Consider the following ``Picture`` object that has an audio file attached to it. + +```xml + + + + + + + + + + + + + +``` + +In the above example, we see that there is a single audioFile element attached to this picture. This picture is placed within the document just as a normal picture or shape would be. The id of this picture, namely 7 in this case, is used to refer to this audioFile element from within the timing node list. The Linked relationship id is used to retrieve the actual audio file for playback purposes. + +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] + +The following XML Schema fragment defines the contents of audioFile. + +```xml + + + + + + +``` + +## How the Sample Code Works + +After opening the presentation file for read/write access in the `using` statement, the code gets the presentation +part from the presentation document. Then it gets the relationship ID of +the last slide, and gets the slide part from the relationship ID. + + +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/add_audio/cs/Program.cs#snippet2)] + +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/add_audio/vb/Program.vb#snippet2)] +*** + +The code first creates a media data part for the audio file to be added. With the audio file stream open, it feeds the media data part object. Next, audio and media relationship references are added to the slide using the provided embedId for future reference to the audio file and mediaEmbedId for media reference. + +An image part is then added with a sample picture to be used as a placeholder for the audio. A picture object is created with various elements, such as Non-Visual Drawing Properties (``), which specify non-visual canvas properties. This allows for additional information that does not affect the appearance of the picture to be stored. The `` element, explained above, is also included. The HyperLinkOnClick (``) element specifies the on-click hyperlink information to be applied to a run of text or image. When the hyperlink text or image is clicked, the link is fetched. Non-Visual Picture Drawing Properties (``) specify the non-visual properties for the picture canvas. For a detailed explanation of the elements used, please refer to [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] + +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/presentation/add_audio/cs/Program.cs#snippet3)] + +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/presentation/add_audio/vb/Program.vb#snippet3)] +*** + +Next the Media(CT_Media) element is created with use of the previously referenced mediaEmbedId(Embedded Picture Reference). The Blip element is also added; this element specifies the existence of an image (binary large image or picture) and contains a reference to the image data. Blip's Embed attribute is used to specify an placeholder image in the Image Part created previously. + +### [C#](#tab/cs-4) +[!code-csharp[](../../samples/presentation/add_audio/cs/Program.cs#snippet4)] + +### [Visual Basic](#tab/vb-4) +[!code-vb[](../../samples/presentation/add_audio/vb/Program.vb#snippet4)] +*** + +All other elements such as Offset(``), Stretch(``), fillRectangle(``), are appended to the ShapeProperties(``) and ShapeProperties are appended to the Picture element(``). Finally the picture element that includes audio is added to the ShapeTree(``) of the slide. + +Following is the complete sample code that you can use to add audio to the slide. + +## Sample Code + +### [C#](#tab/cs) +[!code-csharp[](../../samples/presentation/add_audio/cs/Program.cs#snippet0)] + +### [Visual Basic](#tab/vb) +[!code-vb[](../../samples/presentation/add_audio/vb/Program.vb#snippet0)] +*** + +## See also + +- [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) diff --git a/docs/presentation/how-to-add-transitions-between-slides-in-a-presentation.md b/docs/presentation/how-to-add-transitions-between-slides-in-a-presentation.md new file mode 100644 index 00000000..2f230bae --- /dev/null +++ b/docs/presentation/how-to-add-transitions-between-slides-in-a-presentation.md @@ -0,0 +1,133 @@ +--- + +api_name: +- Microsoft.Office.DocumentFormat.OpenXML.Packaging +api_type: +- schema +ms.assetid: 5471f369-ad02-41c3-a5d3-ebaf618d185a +title: 'How to: Add transitions between slides in a presentation' +ms.suite: office + +ms.author: o365devx +author: o365devx +ms.topic: conceptual +ms.date: 04/03/2025 +ms.localizationpriority: medium +--- + +# Add Transitions between slides in a presentation + +This topic shows how to use the classes in the Open XML SDK to +add transition between all slides in a presentation programmatically. + +## Getting a Presentation Object + +In the Open XML SDK, the class represents a +presentation document package. To work with a presentation document, +first create an instance of the `PresentationDocument` class, and then work with +that instance. To create the class instance from the document, call the + method, that uses a file path, and a +Boolean value as the second parameter to specify whether a document is +editable. To open a document for read/write, specify the value `true` for this parameter as shown in the following +`using` statement. In this code, the file parameter, is a string that represents the path for the file from which you want to open the document. + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/add_transition/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/add_transition/vb/Program.vb#snippet1)] +*** + +[!include[Using Statement](../includes/presentation/using-statement.md)] `ppt`. + +## The Structure of the Transition + +Transition element `` specifies the kind of slide transition that should be used to transition to the current slide from the +previous slide. That is, the transition information is stored on the slide that appears after the transition is +complete. + +The following table lists the attributes of the Transition along +with the description of each. + +| Attribute | Description | +|---|---| +| advClick (Advance on Click) | Specifies whether a mouse click advances the slide or not. If this attribute is not specified then a value of true is assumed. | +| advTm (Advance after time) | Specifies the time, in milliseconds, after which the transition should start. This setting can be used in conjunction with the advClick attribute. If this attribute is not specified then it is assumed that no auto-advance occurs. | +| spd (Transition Speed) |Specifies the transition speed that is to be used when transitioning from the current slide to the next. | + +[*Example*: Consider the following example + +```xml + + + +``` +In the above example, the transition speed `` is set to slow (available options: slow, med, fast). Advance on Click `` is set to true, and Advance after time `` is set to 3000 milliseconds. The Random Bar child element `` describes the randomBar slide transition effect, which uses a set of randomly placed horizontal `` or vertical `` bars on the slide that continue to be added until the new slide is fully shown. *end example*] + +A full list of Transition's child elements can be viewed here: + +## The Structure of the Alternate Content + +Office Open XML defines a mechanism for the storage of content that is not defined by the ISO/IEC 29500 Office Open XML specification, such as extensions developed by future software applications that leverage the Office Open XML formats. This mechanism allows for the storage of a series of alternative representations of content, from which the consuming application can use the first alternative whose requirements are met. + +Consider an application that creates a new transition object intended to specify the duration of the transition. This functionality is not defined in the Office Open XML specification. Using an AlternateContent block as follows allows specifying the duration `` in milliseconds. + +[*Example*: +```xml + + + + + + + + + + + + +``` + +The Choice element in the above example requires the attribute to specify the duration of the transition, and the Fallback element allows clients that do not support this namespace to see an appropriate alternative representation. *end example*] + +More details on the P14 class can be found here: + +## How the Sample Code Works ## +After opening the presentation file for read/write access in the using statement, the code gets the presentation part from the presentation document. Then, it retrieves the relationship IDs of all slides in the presentation and gets the slides part from the relationship ID. The code then checks if there are no existing transitions set on the slides and replaces them with a new RandomBarTransition. + +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/add_transition/cs/Program.cs#snippet2)] + +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/add_transition/vb/Program.vb#snippet2)] +*** + +If there are currently no transitions on the slide, code creates new transition. In both cases as a fallback transition, +RandomBarTransition is used but without `P14:dur`(duration) to allow grater support for clients that aren't supporting this namespace + +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/presentation/add_transition/cs/Program.cs#snippet3)] + +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/presentation/add_transition/vb/Program.vb#snippet3)] +*** + +## Sample Code + +Following is the complete sample code that you can use to add RandomBarTransition to all slides. + +### [C#](#tab/cs) +[!code-csharp[](../../samples/presentation/add_transition/cs/Program.cs#snippet0)] + +### [Visual Basic](#tab/vb) +[!code-vb[](../../samples/presentation/add_transition/vb/Program.vb#snippet0)] +*** + +## See also + +- [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) + + + + 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 2182b0ad..ae640f93 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 @@ -25,11 +25,11 @@ programmatically. ----------------------------------------------------------------------------- ## Getting a PresentationDocument Object -In the Open XML SDK, the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class represents a +In the Open XML SDK, the class represents a presentation document package. To work with a presentation document, first create an instance of the **PresentationDocument** class, and then work with that instance. To create the class instance from the document call the -[Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) method that uses a + method that uses a file path, and a Boolean value as the second parameter to specify whether a document is editable. To open a document for read-only access, specify the value **false** for this parameter. @@ -51,12 +51,7 @@ represents the path for the target presentation document. *** -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 **themeDocument** and **presentationDocument**. + [!include[Using Statement](../includes/presentation/using-statement.md)] `themeDocument` and `presentationDocument`. ----------------------------------------------------------------------------- @@ -83,7 +78,7 @@ be useful when working with this element. > backgrounds, fills, and effects for different objects in a > presentation. *end example*] > -> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following table lists the possible child types of the Theme class. diff --git a/docs/presentation/how-to-change-the-fill-color-of-a-shape-in-a-presentation.md b/docs/presentation/how-to-change-the-fill-color-of-a-shape-in-a-presentation.md index 8d0cb092..a3380383 100644 --- a/docs/presentation/how-to-change-the-fill-color-of-a-shape-in-a-presentation.md +++ b/docs/presentation/how-to-change-the-fill-color-of-a-shape-in-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: 01/02/2025 ms.localizationpriority: medium --- @@ -25,60 +25,43 @@ programmatically. ## Getting a Presentation Object -In the Open XML SDK, the **PresentationDocument** class represents a +In the Open XML SDK, the `PresentationDocument` class represents a presentation document package. To work with a presentation document, -first create an instance of the **PresentationDocument** class, and then work with +first create an instance of the `PresentationDocument` class, and then work with that instance. To create the class instance from the document call the -**Open** method that uses a file path, and a +`Open` method that uses a file path, and a Boolean value as the second parameter to specify whether a document is -editable. To open a document for read/write, specify the value **true** for this parameter as shown in the following -**using** statement. In this code, the file +editable. To open a document for read/write, specify the value `true` for this parameter as shown in the following +`using` statement. In this code, the file parameter is a string that represents the path for the file from which you want to open the document. -### [C#](#tab/cs-0) -```csharp - using (PresentationDocument ppt = PresentationDocument.Open(docName, true)) - { - // Insert other code here. - } -``` +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/change_the_fill_color_of_a_shape/cs/Program.cs#snippet1)] -### [Visual Basic](#tab/vb-0) -```vb - Using ppt As PresentationDocument = PresentationDocument.Open(docName, True) - ' Insert other code here. - End Using -``` +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/change_the_fill_color_of_a_shape/vb/Program.vb#snippet1)] *** -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 *ppt*. +[!include[Using Statement](../includes/presentation/using-statement.md)] `ppt`. ## The Structure of the Shape Tree The basic document structure of a PresentationML document consists of a -number of parts, among which is the Shape Tree (**sp -Tree**) element. +number of parts, among which is the Shape Tree (``) element. The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification -introduces the overall form of a **PresentationML** package. +introduces the overall form of a `PresentationML` package. > This element specifies all shapes within a slide. Contained within > here are all the shapes, either grouped or not, that can be referenced > on a given slide. As most objects within a slide are shapes, this > represents the majority of content within a slide. Text and effects -> are attached to shapes that are contained within the class="keyword">spTree** element. +> are attached to shapes that are contained within the `spTree` element. > -> [*Example*: Consider the following class="keyword">PresentationML** slide +> [*Example*: Consider the following `PresentationML` slide ```xml @@ -102,7 +85,7 @@ introduces the overall form of a **PresentationML** package. > In the above example the shape tree specifies all the shape properties > for this slide. *end example*] > -> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following table lists the child elements of the Shape Tree along with the description of each. @@ -139,134 +122,45 @@ The following XML Schema fragment defines the contents of this element. ## How the Sample Code Works -After opening the presentation file for read/write access in the **using** statement, the code gets the presentation +After opening the presentation file for read/write access in the `using` statement, the code gets the presentation part from the presentation document. Then it gets the relationship ID of the first slide, and gets the slide part from the relationship ID. > [!NOTE] -> The test file must have a filled shape as the first shape on the first slide. - -### [C#](#tab/cs-1) -```csharp - using (PresentationDocument ppt = PresentationDocument.Open(docName, true)) - { - // Get the relationship ID of the first slide. - PresentationPart part = ppt.PresentationPart; - OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; - string relId = (slideIds[0] as SlideId).RelationshipId; - - // Get the slide part from the relationship ID. - SlidePart slide = (SlidePart)part.GetPartById(relId); -``` - -### [Visual Basic](#tab/vb-1) -```vb - Using ppt As PresentationDocument = PresentationDocument.Open(docName, True) - - ' Get the relationship ID of the first slide. - Dim part As PresentationPart = ppt.PresentationPart - Dim slideIds As OpenXmlElementList = part.Presentation.SlideIdList.ChildElements - Dim relId As String = CType(slideIds(0), SlideId).RelationshipId - - ' Get the slide part from the relationship ID. - Dim slide As SlidePart = CType(part.GetPartById(relId), SlidePart) -``` -*** - - -The code then gets the shape tree that contains the shape whose fill -color is to be changed, and gets the first shape in the shape tree. It -then gets the style of the shape and the fill reference of the style, -and assigns a new fill color to the shape. Finally it saves the modified -presentation. +> The test file must have a shape on the first slide. ### [C#](#tab/cs-2) -```csharp - if (slide != null) - { - // Get the shape tree that contains the shape to change. - ShapeTree tree = slide.Slide.CommonSlideData.ShapeTree; - - // Get the first shape in the shape tree. - Shape shape = tree.GetFirstChild(); - - if (shape != null) - { - // Get the style of the shape. - ShapeStyle style = shape.ShapeStyle; - - // Get the fill reference. - Drawing.FillReference fillRef = style.FillReference; - - // Set the fill color to SchemeColor Accent 6; - fillRef.SchemeColor = new Drawing.SchemeColor(); - fillRef.SchemeColor.Val = Drawing.SchemeColorValues.Accent6; - - // Save the modified slide. - slide.Slide.Save(); - } - } -``` +[!code-csharp[](../../samples/presentation/change_the_fill_color_of_a_shape/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-2) -```vb - If (Not (slide) Is Nothing) Then - - ' Get the shape tree that contains the shape to change. - Dim tree As ShapeTree = slide.Slide.CommonSlideData.ShapeTree - - ' Get the first shape in the shape tree. - Dim shape As Shape = tree.GetFirstChild(Of Shape)() - - If (Not (shape) Is Nothing) Then - - ' Get the style of the shape. - Dim style As ShapeStyle = shape.ShapeStyle - - ' Get the fill reference. - Dim fillRef As Drawing.FillReference = style.FillReference - - ' Set the fill color to SchemeColor Accent 6; - fillRef.SchemeColor = New Drawing.SchemeColor - fillRef.SchemeColor.Val = Drawing.SchemeColorValues.Accent6 - - ' Save the modified slide. - slide.Slide.Save() - End If - End If -``` +[!code-vb[](../../samples/presentation/change_the_fill_color_of_a_shape/vb/Program.vb#snippet2)] *** -## Sample Code - -Following is the complete sample code that you can use to change the -fill color of a shape in a presentation. In your program, you can invoke -the method **SetPPTShapeColor** to change the -fill color in the file "Myppt3.pptx" by using the following call. +The code then gets the shape tree that contains the shape whose fill +color is to be changed, and gets the first shape in the shape tree. It +then gets the shape properties of the shape and the solid fill reference of the shape properties, +and assigns a new fill color to the shape. There is no need to explicitly +save the file when inside of a using. ### [C#](#tab/cs-3) -```csharp - string docName = @"C:\Users\Public\Documents\Myppt3.pptx"; - SetPPTShapeColor(docName); -``` +[!code-csharp[](../../samples/presentation/change_the_fill_color_of_a_shape/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-3) -```vb - Dim docName As String = "C:\Users\Public\Documents\Myppt3.pptx" - SetPPTShapeColor(docName) -``` +[!code-vb[](../../samples/presentation/change_the_fill_color_of_a_shape/vb/Program.vb#snippet3)] *** -After running the program, examine the file "Myppt3.pptx" to see the -change in the fill color. +## Sample Code +Following is the complete sample code that you can use to change the +fill color of a shape in a presentation. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/change_the_fill_color_of_a_shape/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/change_the_fill_color_of_a_shape/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/change_the_fill_color_of_a_shape/vb/Program.vb)] +[!code-vb[](../../samples/presentation/change_the_fill_color_of_a_shape/vb/Program.vb#snippet0)] +*** ## See also diff --git a/docs/presentation/how-to-create-a-presentation-document-by-providing-a-file-name.md b/docs/presentation/how-to-create-a-presentation-document-by-providing-a-file-name.md index a825670c..8ad5735f 100644 --- a/docs/presentation/how-to-create-a-presentation-document-by-providing-a-file-name.md +++ b/docs/presentation/how-to-create-a-presentation-document-by-providing-a-file-name.md @@ -12,7 +12,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 12/31/2024 ms.localizationpriority: high --- @@ -30,69 +30,59 @@ create a presentation document programmatically. A presentation file, like all files defined by the Open XML standard, consists of a package file container. This is the file that users see in their file explorer; it usually has a .pptx extension. The package file -is represented in the Open XML SDK by the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class. The +is represented in the Open XML SDK by the class. The presentation document contains, among other parts, a presentation part. -The presentation part, represented in the Open XML SDK by the [PresentationPart](/dotnet/api/documentformat.openxml.packaging.presentationpart) class, contains the basic +The presentation part, represented in the Open XML SDK by the class, contains the basic *PresentationML* definition for the slide presentation. PresentationML is the markup language used for creating presentations. Each package can -contain only one presentation part, and its root element must be -\. +contain only one presentation part, and its root element must be ``. The API calls used to create a new presentation document package are -relatively simple. The first step is to call the static [Create(String,PresentationDocumentType)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.create) -method of the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class, as shown here -in the **CreatePresentation** procedure, which is the first part of the +relatively simple. The first step is to call the static +method of the class, as shown here +in the `CreatePresentation` procedure, which is the first part of the complete code sample presented later in the article. The -**CreatePresentation** code calls the override of the **Create** method that takes as arguments the path to +`CreatePresentation` code calls the override of the `Create` method that takes as arguments the path to the new document and the type of presentation document to be created. The types of presentation documents available in that argument are -defined by a [PresentationDocumentType](/dotnet/api/documentformat.openxml.presentationdocumenttype) enumerated value. +defined by a enumerated value. -Next, the code calls [AddPresentationPart()](/dotnet/api/documentformat.openxml.packaging.presentationdocument.addpresentationpart), which creates and -returns a **PresentationPart**. After the **PresentationPart** class instance is created, a new -root element for the presentation is added by setting the [Presentation](/dotnet/api/documentformat.openxml.packaging.presentationpart.presentation) property equal to the instance -of the [Presentation](/dotnet/api/documentformat.openxml.presentation.presentation) class returned from a call to -the **Presentation** class constructor. +Next, the code calls , which creates and +returns a `PresentationPart`. After the `PresentationPart` class instance is created, a new +root element for the presentation is added by setting the property equal to the instance of the class returned from a call to +the `Presentation` class constructor. In order to create a complete, useable, and valid presentation, the code must also add a number of other parts to the presentation package. In the example code, this is taken care of by a call to a utility function -named **CreatePresentationsParts**. That function then calls a number of +named `CreatePresentationsParts`. That function then calls a number of other utility functions that, taken together, create all the presentation parts needed for a basic presentation, including slide, slide layout, slide master, and theme parts. -```csharp - public static void CreatePresentation(string filepath) - { - // Create a presentation at a specified file path. The presentation document type is pptx, by default. - PresentationDocument presentationDoc = PresentationDocument.Create(filepath, PresentationDocumentType.Presentation); - PresentationPart presentationPart = presentationDoc.AddPresentationPart(); - presentationPart.Presentation = new Presentation(); +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/create_by_providing_a_file_name/cs/Program.cs#snippet1)] - CreatePresentationParts(presentationPart); - - // Close the presentation handle - presentationDoc.Close(); - } -``` +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/create_by_providing_a_file_name/vb/Program.vb#snippet1)] +*** Using the Open XML SDK, you can create presentation structure and content by using strongly-typed classes that correspond to -PresentationML elements. You can find these classes in the [DocumentFormat.OpenXml.Presentation](/dotnet/api/documentformat.openxml.presentation) +PresentationML elements. You can find these classes in the namespace. The following table lists the names of the classes that correspond to the presentation, slide, slide master, slide layout, and theme elements. The class that corresponds to the theme element is -actually part of the [DocumentFormat.OpenXml.Drawing](/dotnet/api/documentformat.openxml.drawing) namespace. +actually part of the namespace. Themes are common to all Open XML markup languages. | PresentationML Element | Open XML SDK Class | |---|---| -| <presentation> | [Presentation](/dotnet/api/documentformat.openxml.presentation.presentation) | -| <sld> | [Slide](/dotnet/api/documentformat.openxml.presentation.slide) | -| <sldMaster> | [SlideMaster](/dotnet/api/documentformat.openxml.presentation.slidemaster) | -| <sldLayout> | [SlideLayout](/dotnet/api/documentformat.openxml.presentation.slidelayout) | -| <theme> | [Theme](/dotnet/api/documentformat.openxml.drawing.theme) | +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | The PresentationML code that follows is the XML in the presentation part (in the file presentation.xml) for a simple presentation that contains @@ -126,10 +116,11 @@ Following is the complete sample C\# and VB code to create a presentation, given a file path. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/create_by_providing_a_file_name/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/create_by_providing_a_file_name/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/create_by_providing_a_file_name/vb/Program.vb)] +[!code-vb[](../../samples/presentation/create_by_providing_a_file_name/vb/Program.vb#snippet0)] +*** -------------------------------------------------------------------------------- diff --git a/docs/presentation/how-to-delete-a-slide-from-a-presentation.md b/docs/presentation/how-to-delete-a-slide-from-a-presentation.md index f27d74ca..a0b4a046 100644 --- a/docs/presentation/how-to-delete-a-slide-from-a-presentation.md +++ b/docs/presentation/how-to-delete-a-slide-from-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/31/2024 ms.localizationpriority: medium --- # Delete a slide from a presentation @@ -30,253 +30,92 @@ slides, and the second is deleting a slide at a specific index. -------------------------------------------------------------------------------- -## Getting a Presentation Object - -In the Open XML SDK, the **[PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument)** class represents a presentation document package. To work with a presentation document, first create an instance of the **PresentationDocument** class, and then work with that instance. To create the class instance from the document call one of the **Open** method overloads. The code in this topic uses the **[PresentationDocument.Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open)** method, which takes a file path as the first parameter to specify the file to open, and a Boolean value as the second parameter to specify whether a document is editable. Set this second parameter to **false** to open the file for read-only access, or **true** if you want to open the file for read/write access. The code in this topic opens the file twice, once to count the number of slides and once to delete a specific slide. When you count the number of slides in a presentation, it is best to open the file for read-only access to protect the file against accidental writing. The following **using** statement opens the file for read-only access. In this code example, the **presentationFile** parameter is a string that represents the path for the file from which you want to open the document. - -### [C#](#tab/cs-0) -```csharp - // Open the presentation as read-only. - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - ' Open the presentation as read-only. - Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, False) - ' Insert other code here. - End Using -``` +## Getting a Presentation Object + +In the Open XML SDK, the class represents a presentation document package. To work with a presentation document, first create an instance of the `PresentationDocument` class, and then work with that instance. To create the class instance from the document call one of the `Open` method overloads. The code in this topic uses the method, which takes a file path as the first parameter to specify the file to open, and a Boolean value as the second parameter to specify whether a document is editable. Set this second parameter to `false` to open the file for read-only access, or `true` if you want to open the file for read/write access. The code in this topic opens the file twice, once to count the number of slides and once to delete a specific slide. When you count the number of slides in a presentation, it is best to open the file for read-only access to protect the file against accidental writing. The following `using` statement opens the file for read-only access. In this code example, the `presentationFile` parameter is a string that represents the path for the file from which you want to open the document. + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/delete_a_slide_from/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/delete_a_slide_from/vb/Program.vb#snippet1)] *** To delete a slide from the presentation file, open it for read/write -access as shown in the following **using** +access as shown in the following `using` statement. -### [C#](#tab/cs-1) -```csharp - // Open the source document as read/write. - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true)) - { - // Place other code here. - } -``` +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/delete_a_slide_from/cs/Program.cs#snippet2)] -### [Visual Basic](#tab/vb-1) -```vb - ' Open the source document as read/write. - Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, True) - ' Place other code here. - End Using -``` +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/delete_a_slide_from/vb/Program.vb#snippet2)] *** -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 **presentationDocument**. +[!include[Using Statement](../includes/presentation/using-statement.md)] `presentationDocument`. [!include[Structure](../includes/presentation/structure.md)] -## Counting the Number of Slides +## Counting the Number of Slides -The sample code consists of two overloads of the **CountSlides** method. The first overload uses a **string** parameter and the second overload uses a **PresentationDocument** parameter. In the first **CountSlides** method, the sample code opens the presentation document in the **using** statement. Then it passes the **PresentationDocument** object to the second **CountSlides** method, which returns an integer number that represents the number of slides in the presentation. +The sample code consists of two overloads of the `CountSlides` method. The first overload uses a `string` parameter and the second overload uses a `PresentationDocument` parameter. In the first `CountSlides` method, the sample code opens the presentation document in the `using` statement. Then it passes the `PresentationDocument` object to the second `CountSlides` method, which returns an integer number that represents the number of slides in the presentation. -### [C#](#tab/cs-2) -```csharp - // Pass the presentation to the next CountSlides method - // and return the slide count. - return CountSlides(presentationDocument); -``` +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/presentation/delete_a_slide_from/cs/Program.cs#snippet3)] -### [Visual Basic](#tab/vb-2) -```vb - ' Pass the presentation to the next CountSlides method - ' and return the slide count. - Return CountSlides(presentationDocument) -``` +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/presentation/delete_a_slide_from/vb/Program.vb#snippet3)] *** -In the second **CountSlides** method, the code -verifies that the **PresentationDocument** -object passed in is not **null**, and if it is -not, it gets a **PresentationPart** object from -the **PresentationDocument** object. By using -the **SlideParts** the code gets the slideCount +In the second `CountSlides` method, the code +verifies that the `PresentationDocument` +object passed in is not `null`, and if it is +not, it gets a `PresentationPart` object from +the `PresentationDocument` object. By using +the `SlideParts` the code gets the slideCount and returns it. -### [C#](#tab/cs-3) -```csharp - // Check for a null document object. - if (presentationDocument == null) - { - throw new ArgumentNullException("presentationDocument"); - } - - int slidesCount = 0; - - // Get the presentation part of document. - PresentationPart presentationPart = presentationDocument.PresentationPart; - - // Get the slide count from the SlideParts. - if (presentationPart != null) - { - slidesCount = presentationPart.SlideParts.Count(); - } - // Return the slide count to the previous method. - return slidesCount; -``` +### [C#](#tab/cs-4) +[!code-csharp[](../../samples/presentation/delete_a_slide_from/cs/Program.cs#snippet4)] -### [Visual Basic](#tab/vb-3) -```vb - ' Check for a null document object. - If presentationDocument Is Nothing Then - Throw New ArgumentNullException("presentationDocument") - End If - - Dim slidesCount As Integer = 0 - - ' Get the presentation part of document. - Dim presentationPart As PresentationPart = presentationDocument.PresentationPart - - ' Get the slide count from the SlideParts. - If presentationPart IsNot Nothing Then - slidesCount = presentationPart.SlideParts.Count() - End If - ' Return the slide count to the previous method. - Return slidesCount -``` +### [Visual Basic](#tab/vb-4) +[!code-vb[](../../samples/presentation/delete_a_slide_from/vb/Program.vb#snippet4)] *** - -------------------------------------------------------------------------------- -## Deleting a Specific Slide +## Deleting a Specific Slide -The code for deleting a slide uses two overloads of the **DeleteSlide** method. The first overloaded **DeleteSlide** method takes two parameters: a string +The code for deleting a slide uses two overloads of the `DeleteSlide` method. The first overloaded `DeleteSlide` method takes two parameters: a string that represents the presentation file name and path, and an integer that represents the zero-based index position of the slide to delete. It -opens the presentation file for read/write access, gets a **PresentationDocument** object, and then passes that -object and the index number to the next overloaded **DeleteSlide** method, which performs the deletion. +opens the presentation file for read/write access, gets a `PresentationDocument` object, and then passes that +object and the index number to the next overloaded `DeleteSlide` method, which performs the deletion. -### [C#](#tab/cs-4) -```csharp - // Get the presentation object and pass it to the next DeleteSlide method. - public static void DeleteSlide(string presentationFile, int slideIndex) - { - // Open the source document as read/write. - - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true)) - { - // Pass the source document and the index of the slide to be deleted to the next DeleteSlide method. - DeleteSlide(presentationDocument, slideIndex); - } - } -``` +### [C#](#tab/cs-5) +[!code-csharp[](../../samples/presentation/delete_a_slide_from/cs/Program.cs#snippet5)] -### [Visual Basic](#tab/vb-4) -```vb - ' Check for a null document object. - If presentationDocument Is Nothing Then - Throw New ArgumentNullException("presentationDocument") - End If - - Dim slidesCount As Integer = 0 - - ' Get the presentation part of document. - Dim presentationPart As PresentationPart = presentationDocument.PresentationPart - - ' Get the slide count from the SlideParts. - If presentationPart IsNot Nothing Then - slidesCount = presentationPart.SlideParts.Count() - End If - ' Return the slide count to the previous method. - Return slidesCount -``` +### [Visual Basic](#tab/vb-5) +[!code-vb[](../../samples/presentation/delete_a_slide_from/vb/Program.vb#snippet5)] *** -The first section of the second overloaded **DeleteSlide** method uses the **CountSlides** method to get the number of slides in +The first section of the second overloaded `DeleteSlide` method uses the `CountSlides` method to get the number of slides in the presentation. Then, it gets the list of slide IDs in the presentation, identifies the specified slide in the slide list, and removes the slide from the slide list. -### [C#](#tab/cs-5) -```csharp - // Delete the specified slide from the presentation. - public static void DeleteSlide(PresentationDocument presentationDocument, int slideIndex) - { - if (presentationDocument == null) - { - throw new ArgumentNullException("presentationDocument"); - } - - // Use the CountSlides sample to get the number of slides in the presentation. - int slidesCount = CountSlides(presentationDocument); - - if (slideIndex < 0 || slideIndex >= slidesCount) - { - throw new ArgumentOutOfRangeException("slideIndex"); - } - - // Get the presentation part from the presentation document. - PresentationPart presentationPart = presentationDocument.PresentationPart; - - // Get the presentation from the presentation part. - Presentation presentation = presentationPart.Presentation; - - // Get the list of slide IDs in the presentation. - SlideIdList slideIdList = presentation.SlideIdList; - - // Get the slide ID of the specified slide - SlideId slideId = slideIdList.ChildElements[slideIndex] as SlideId; - - // Get the relationship ID of the slide. - string slideRelId = slideId.RelationshipId; - - // Remove the slide from the slide list. - slideIdList.RemoveChild(slideId); -``` - -### [Visual Basic](#tab/vb-5) -```vb - ' Delete the specified slide from the presentation. - Public Shared Sub DeleteSlide(ByVal presentationDocument As - If presentationDocument Is Nothing Then - Throw New ArgumentNullException("presentationDocument") - End If - - ' Use the CountSlides sample to get the number of slides in the presentation. - Dim slidesCount As Integer = CountSlides(presentationDocument) - - If slideIndex < 0 OrElse slideIndex >= slidesCount Then - Throw New ArgumentOutOfRangeException("slideIndex") - End If - - ' Get the presentation part from the presentation document. - Dim presentationPart As PresentationPart = presentationDocument.PresentationPart - - ' Get the presentation from the presentation part. - Dim presentation As Presentation = presentationPart.Presentation - - ' Get the list of slide IDs in the presentation. - Dim slideIdList As SlideIdList = presentation.SlideIdList - - ' Get the slide ID of the specified slide - Dim slideId As SlideId = TryCast(slideIdList.ChildElements(slideIndex), SlideId) - - ' Get the relationship ID of the slide. - Dim slideRelId As String = slideId.RelationshipId +### [C#](#tab/cs-6) +[!code-csharp[](../../samples/presentation/delete_a_slide_from/cs/Program.cs#snippet6)] - ' Remove the slide from the slide list. - slideIdList.RemoveChild(slideId) -``` +### [Visual Basic](#tab/vb-6) +[!code-vb[](../../samples/presentation/delete_a_slide_from/vb/Program.vb#snippet6)] *** -The next section of the second overloaded **DeleteSlide** method removes all references to the +The next section of the second overloaded `DeleteSlide` method removes all references to the deleted slide from custom shows. It does that by iterating through the list of custom shows and through the list of slides in each custom show. It then declares and instantiates a linked list of slide list entries, @@ -285,145 +124,38 @@ of that slide. It adds those references to the list of slide list entries, and then removes each such reference from the slide list of its respective custom show. -### [C#](#tab/cs-6) -```csharp - // Remove references to the slide from all custom shows. - if (presentation.CustomShowList != null) - { - // Iterate through the list of custom shows. - foreach (var customShow in presentation.CustomShowList.Elements()) - { - if (customShow.SlideList != null) - { - // Declare a link list of slide list entries. - LinkedList slideListEntries = new LinkedList(); - foreach (SlideListEntry slideListEntry in customShow.SlideList.Elements()) - { - // Find the slide reference to remove from the custom show. - if (slideListEntry.Id != null && slideListEntry.Id == slideRelId) - { - slideListEntries.AddLast(slideListEntry); - } - } - - // Remove all references to the slide from the custom show. - foreach (SlideListEntry slideListEntry in slideListEntries) - { - customShow.SlideList.RemoveChild(slideListEntry); - } - } - } - } -``` - -### [Visual Basic](#tab/vb-6) -```vb - ' Remove references to the slide from all custom shows. - If presentation.CustomShowList IsNot Nothing Then - ' Iterate through the list of custom shows. - For Each customShow In presentation.CustomShowList.Elements(Of CustomShow)() - If customShow.SlideList IsNot Nothing Then - ' Declare a link list of slide list entries. - Dim slideListEntries As New LinkedList(Of SlideListEntry)() - For Each slideListEntry As SlideListEntry In customShow.SlideList.Elements() - ' Find the slide reference to remove from the custom show. - If slideListEntry.Id IsNot Nothing AndAlso slideListEntry.Id = slideRelId Then - slideListEntries.AddLast(slideListEntry) - End If - Next slideListEntry - - ' Remove all references to the slide from the custom show. - For Each slideListEntry As SlideListEntry In slideListEntries - customShow.SlideList.RemoveChild(slideListEntry) - Next slideListEntry - End If - Next customShow - End If -``` -*** - - -Finally, the code saves the modified presentation, and deletes the slide -part for the deleted slide. - ### [C#](#tab/cs-7) -```csharp - // Save the modified presentation. - presentation.Save(); - - // Get the slide part for the specified slide. - SlidePart slidePart = presentationPart.GetPartById(slideRelId) as SlidePart; - - // Remove the slide part. - presentationPart.DeletePart(slidePart); - } -``` +[!code-csharp[](../../samples/presentation/delete_a_slide_from/cs/Program.cs#snippet7)] ### [Visual Basic](#tab/vb-7) -```vb - ' Save the modified presentation. - presentation.Save() - - ' Get the slide part for the specified slide. - Dim slidePart As SlidePart = TryCast(presentationPart.GetPartById(slideRelId), SlidePart) - - ' Remove the slide part. - presentationPart.DeletePart(slidePart) - End Sub -``` +[!code-vb[](../../samples/presentation/delete_a_slide_from/vb/Program.vb#snippet7)] *** --------------------------------------------------------------------------------- -## Sample Code - -The following is the complete sample code for the two overloaded -methods, **CountSlides** and **DeleteSlide**. To use the code, you can use the -following call as an example to delete the slide at index 2 in the -presentation file "Myppt6.pptx." +Finally, the code deletes the slide part for the deleted slide. ### [C#](#tab/cs-8) -```csharp - DeleteSlide(@"C:\Users\Public\Documents\Myppt6.pptx", 2); -``` +[!code-csharp[](../../samples/presentation/delete_a_slide_from/cs/Program.cs#snippet8)] ### [Visual Basic](#tab/vb-8) -```vb - DeleteSlide("C:\Users\Public\Documents\Myppt6.pptx", 0) -``` +[!code-vb[](../../samples/presentation/delete_a_slide_from/vb/Program.vb#snippet8)] *** -You can also use the following call to count the number of slides in the -presentation. - -### [C#](#tab/cs-9) -```csharp - Console.WriteLine("Number of slides = {0}", - CountSlides(@"C:\Users\Public\Documents\Myppt6.pptx")); -``` - -### [Visual Basic](#tab/vb-9) -```vb - Console.WriteLine("Number of slides = {0}", _ - CountSlides("C:\Users\Public\Documents\Myppt6.pptx")) -``` -*** - - -It might be a good idea to count the number of slides before and after -performing the deletion. +-------------------------------------------------------------------------------- +## Sample Code Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/delete_a_slide_from/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/delete_a_slide_from/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/delete_a_slide_from/vb/Program.vb)] +[!code-vb[](../../samples/presentation/delete_a_slide_from/vb/Program.vb#snippet0)] +*** -------------------------------------------------------------------------------- -## See also +## See also diff --git a/docs/presentation/how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentatio.md b/docs/presentation/how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentatio.md deleted file mode 100644 index 83f73734..00000000 --- a/docs/presentation/how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentatio.md +++ /dev/null @@ -1,271 +0,0 @@ ---- - -api_name: -- Microsoft.Office.DocumentFormat.OpenXML.Packaging -api_type: -- schema -ms.assetid: 3b892a6a-2972-461e-94a9-0a1ede854bda -title: 'Delete all the comments by an author from all the slides in a presentation' -ms.suite: office - -ms.author: o365devx -author: o365devx -ms.topic: conceptual -ms.date: 11/01/2017 -ms.localizationpriority: medium ---- -# Delete all the comments by an author from all the slides in a presentation - -This topic shows how to use the classes in the Open XML SDK for -Office to delete all of the comments by a specific author in a -presentation programmatically. - - - -## Getting a PresentationDocument Object - -In the Open XML SDK, the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class represents a -presentation document package. To work with a presentation document, -first create an instance of the **PresentationDocument** class, and then work with -that instance. To create the class instance from the document call the -[Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) method that uses a -file path, and a Boolean value as the second parameter to specify -whether a document is editable. To open a document for read/write, -specify the value **true** for this parameter -as shown in the following **using** statement. -In this code, the *fileName* parameter is a string that represents the -path for the file from which you want to open the document, and the -author is the user name displayed in the General tab of the PowerPoint -Options. - -### [C#](#tab/cs-0) -```csharp - public static void DeleteCommentsByAuthorInPresentation(string fileName, string author) - { - using (PresentationDocument doc = PresentationDocument.Open(fileName, true)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - Public Shared Sub DeleteCommentsByAuthorInPresentation(ByVal fileName As String, ByVal author As String) - - Using doc As PresentationDocument = PresentationDocument.Open(fileName, 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 *doc*. - -[!include[Structure](../includes/presentation/structure.md)] - -## The Structure of the Comment Element - -The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification -introduces comments in a presentation package. - -> A comment is a text note attached to a slide, with the primary purpose -> of allowing readers of a presentation to provide feedback to the -> presentation author. Each comment contains an unformatted text string -> and information about its author, and is attached to a particular -> location on a slide. Comments can be visible while editing the -> presentation, but do not appear when a slide show is given. The -> displaying application decides when to display comments and determines -> their visual appearance. -> -> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] - -The following XML element specifies a single comment attached to a -slide. It contains the text of the comment (**text**), its position on the slide (**pos**), and attributes referring to its author -(**authorId**), date and time (**dt**), and comment index (**idx**). - -```xml - - - Add diagram to clarify. - -``` - -The following table lists the definitions of the members and attributes -of the **cm** (comment) element. - -| Member/Attribute | Definition | -|---|---| -| authorId | Refers to the ID of an author in the comment author list for the document. | -| dt | The date and time this comment was last modified. | -| idx | An identifier for this comment that is unique within a list of all comments by this author in this document. An author's first comment in a document has index 1. | -| pos | The positioning information for the placement of a comment on a slide surface. | -| text | Comment's text content. | -| extLst | Specifies the extension list with modification ability within which all future extensions of element type ext are defined. The extension list along with corresponding future extensions is used to extend the storage capabilities of the PresentationML framework. This allows for various new kinds of data to be stored natively within the framework. | - -The following XML schema example defines the members of the **cm** element in addition to the required and -optional attributes. - -```xml - - - - - - - - - - -``` - -## How the Sample Code Works - -After opening the presentation document for read/write access and -instantiating the **PresentationDocument** -class, the code gets the specified comment author from the list of -comment authors. - -### [C#](#tab/cs-1) -```csharp - // Get the specifed comment author. - IEnumerable commentAuthors = - doc.PresentationPart.CommentAuthorsPart.CommentAuthorList.Elements() - .Where(e => e.Name.Value.Equals(author)); -``` - -### [Visual Basic](#tab/vb-1) -```vb - ' Get the specifed comment author. - Dim commentAuthors As IEnumerable(Of CommentAuthor) = _ - doc.PresentationPart.CommentAuthorsPart.CommentAuthorList.Elements _ - (Of CommentAuthor)().Where(Function(e) e.Name.Value.Equals(author)) -``` -*** - - -By iterating through the matching authors and all the slides in the -presentation the code gets all the slide parts, and the comments part of -each slide part. It then gets the list of comments by the specified -author and deletes each one. It also verifies that the comment part has -no existing comment, in which case it deletes that part. It also deletes -the comment author from the comment authors part. - -### [C#](#tab/cs-2) -```csharp - // Iterate through all the matching authors. - foreach (CommentAuthor commentAuthor in commentAuthors) - { - UInt32Value authorId = commentAuthor.Id; - - // Iterate through all the slides and get the slide parts. - foreach (SlidePart slide in doc.PresentationPart.SlideParts) - { - SlideCommentsPart slideCommentsPart = slide.SlideCommentsPart; - // Get the list of comments. - if (slideCommentsPart != null && slide.SlideCommentsPart.CommentList != null) - { - IEnumerable commentList = - slideCommentsPart.CommentList.Elements().Where(e => e.AuthorId == authorId.Value); - List comments = new List(); - comments = commentList.ToList(); - - foreach (Comment comm in comments) - { - // Delete all the comments by the specified author. - slideCommentsPart.CommentList.RemoveChild(comm); - } - - // If the commentPart has no existing comment. - if (slideCommentsPart.CommentList.ChildElements.Count == 0) - // Delete this part. - slide.DeletePart(slideCommentsPart); - } - } - // Delete the comment author from the comment authors part. - doc.PresentationPart.CommentAuthorsPart.CommentAuthorList.RemoveChild(commentAuthor); - } -``` - -### [Visual Basic](#tab/vb-2) -```vb - 'Iterate through all the matching authors - For Each commentAuthor In commentAuthors - - Dim authorId = commentAuthor.Id - - ' Iterate through all the slides and get the slide parts. - For Each slide In doc.PresentationPart.GetPartsOfType(Of SlidePart)() - - ' Get the slide comments part of each slide. - For Each slideCommentsPart In slide.GetPartsOfType(Of SlideCommentsPart)() - - ' Delete all the comments by the specified author. - Dim commentList = slideCommentsPart.CommentList.Elements(Of Comment)(). _ - Where(Function(e) e.AuthorId.Value.Equals(authorId.Value)) - - Dim comments As List(Of Comment) = commentList.ToList() - - For Each comm As Comment In comments - slideCommentsPart.CommentList.RemoveChild(Of Comment)(comm) - Next - - Next - - Next - - ' Delete the comment author from the comment authors part. - doc.PresentationPart.CommentAuthorsPart.CommentAuthorList.RemoveChild(Of CommentAuthor)(commentAuthor) - - Next -``` -*** - - -## Sample Code - -The following method takes as parameters the source presentation file -name and path and the name of the comment author whose comments are to -be deleted. It finds all the comments by the specified author in the -presentation and deletes them. It then deletes the comment author from -the list of comment authors. - -You can use the following example to call the -*DeleteCommentsByAuthorInPresentation* method to remove the comments of -the specified author from the presentation file, *myppt5.pptx*. - -### [C#](#tab/cs-3) -```csharp - string fileName = @"C:\Users\Public\Documents\myppt5.pptx"; - string author = "Katie Jordan"; - DeleteCommentsByAuthorInPresentation(fileName, author); -``` - -### [Visual Basic](#tab/vb-3) -```vb - Dim fileName As String = "C:\Users\Public\Documents\myppt5.pptx" - Dim author As String = "Katie Jordan" - DeleteCommentsByAuthorInPresentation(fileName, author) -``` -*** - -> [!NOTE] -> To get the exact author's name, open the presentation file and click the **File** menu item, and then click **Options**. The **PowerPoint Options** window opens and the content of the **General** tab is displayed. The author's name must match the **User name** in this tab. - -The following is the complete sample code in both C\# and Visual Basic. - -### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/delete_all_the_comments_by_an_author_from_all_the_slides_a_presentatio/cs/Program.cs)] - -### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/delete_all_the_comments_by_an_author_from_all_the_slides_a_presentatio/vb/Program.vb)] - -## See also - - - -- [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) diff --git a/docs/presentation/how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentation.md b/docs/presentation/how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentation.md new file mode 100644 index 00000000..1613e2a0 --- /dev/null +++ b/docs/presentation/how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentation.md @@ -0,0 +1,131 @@ +--- + +api_name: +- Microsoft.Office.DocumentFormat.OpenXML.Packaging +api_type: +- schema +ms.assetid: 3b892a6a-2972-461e-94a9-0a1ede854bda +title: 'Delete all the comments by an author from all the slides in a presentation' +ms.suite: office + +ms.author: o365devx +author: o365devx +ms.topic: conceptual +ms.date: 12/30/2024 +ms.localizationpriority: medium +--- +# Delete all the comments by an author from all the slides in a presentation + +This topic shows how to use the classes in the Open XML SDK for +Office to delete all of the comments by a specific author in a +presentation programmatically. + +> [!NOTE] +> This sample is for PowerPoint modern comments. For classic comments view +> the [archived sample on GitHub](https://github.com/OfficeDev/open-xml-docs/blob/7002d692ab4abc629d617ef6a0214fc2bf2910c8/docs/how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentatio.md). + + + + + +## Getting a PresentationDocument Object + +In the Open XML SDK, the class represents a +presentation document package. To work with a presentation document, +first create an instance of the `PresentationDocument` class, and then work with +that instance. To create the class instance from the document call the + method that uses a +file path, and a Boolean value as the second parameter to specify +whether a document is editable. To open a document for read/write, +specify the value `true` for this parameter +as shown in the following `using` statement. +In this code, the *fileName* parameter is a string that represents the +path for the file from which you want to open the document, and the +author is the user name displayed in the General tab of the PowerPoint +Options. + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/delete_all_the_comments_by_an_author_from_all_the_slides_a_presentatio/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/delete_all_the_comments_by_an_author_from_all_the_slides_a_presentatio/vb/Program.vb#snippet1)] +*** + + +[!include[Using Statement](../includes/presentation/using-statement.md)] `doc`. + +[!include[Structure](../includes/presentation/structure.md)] + +## The Structure of the Comment Element + +The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification +introduces comments in a presentation package. + +> A comment is a text note attached to a slide, with the primary purpose +> of allowing readers of a presentation to provide feedback to the +> presentation author. Each comment contains an unformatted text string +> and information about its author, and is attached to a particular +> location on a slide. Comments can be visible while editing the +> presentation, but do not appear when a slide show is given. The +> displaying application decides when to display comments and determines +> their visual appearance. +> +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] + +[!include[description of a comment](../includes/presentation/modern-comment-description.md)] + +## How the Sample Code Works + +After opening the presentation document for read/write access and +instantiating the `PresentationDocument` +class, the code gets the specified comment author from the list of +comment authors. + +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/delete_all_the_comments_by_an_author_from_all_the_slides_a_presentatio/cs/Program.cs#snippet2)] + +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/delete_all_the_comments_by_an_author_from_all_the_slides_a_presentatio/vb/Program.vb#snippet2)] +*** + + +By iterating through the matching authors and all the slides in the +presentation the code gets all the slide parts, and the comments part of +each slide part. It then gets the list of comments by the specified +author and deletes each one. It also verifies that the comment part has +no existing comment, in which case it deletes that part. It also deletes +the comment author from the comment authors part. + +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/presentation/delete_all_the_comments_by_an_author_from_all_the_slides_a_presentatio/cs/Program.cs#snippet3)] + +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/presentation/delete_all_the_comments_by_an_author_from_all_the_slides_a_presentatio/vb/Program.vb#snippet3)] +*** + + +## Sample Code + +The following method takes as parameters the source presentation file +name and path and the name of the comment author whose comments are to +be deleted. It finds all the comments by the specified author in the +presentation and deletes them. It then deletes the comment author from +the list of comment authors. + +> [!NOTE] +> To get the exact author's name, open the presentation file and click the **File** menu item, and then click **Options**. The **PowerPoint Options** window opens and the content of the **General** tab is displayed. The author's name must match the **User name** in this tab. + +The following is the complete sample code in both C\# and Visual Basic. + +### [C#](#tab/cs) +[!code-csharp[](../../samples/presentation/delete_all_the_comments_by_an_author_from_all_the_slides_a_presentatio/cs/Program.cs#snippet0)] + +### [Visual Basic](#tab/vb) +[!code-vb[](../../samples/presentation/delete_all_the_comments_by_an_author_from_all_the_slides_a_presentatio/vb/Program.vb#snippet0)] +*** + +## See also + + + +- [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) diff --git a/docs/presentation/how-to-get-all-the-external-hyperlinks-in-a-presentation.md b/docs/presentation/how-to-get-all-the-external-hyperlinks-in-a-presentation.md index d7ba13a1..60210e84 100644 --- a/docs/presentation/how-to-get-all-the-external-hyperlinks-in-a-presentation.md +++ b/docs/presentation/how-to-get-all-the-external-hyperlinks-in-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/06/2024 ms.localizationpriority: medium --- # Get all the external hyperlinks in a presentation @@ -24,46 +24,30 @@ programmatically. -------------------------------------------------------------------------------- ## Getting a PresentationDocument Object -In the Open XML SDK, the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class represents a +In the Open XML SDK, the class represents a presentation document package. To work with a presentation document, -first create an instance of the **PresentationDocument** class, and then work with +first create an instance of the `PresentationDocument` class, and then work with that instance. To create the class instance from the document call the -[PresentationDocument.Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) + method that uses a file path, and a Boolean value as the second parameter to specify whether a document is editable. Set this second -parameter to **false** to open the file for -read-only access, or **true** if you want to +parameter to `false` to open the file for +read-only access, or `true` if you want to open the file for read/write access. In this topic, it is best to open the file for read-only access to protect the file against accidental -writing. The following **using** statement -opens the file for read-only access. In this code segment, the **fileName** parameter is a string that represents the +writing. The following `using` statement +opens the file for read-only access. In this code segment, the `fileName` parameter is a string that represents the path for the file from which you want to open the document. -### [C#](#tab/cs-0) -```csharp - // Open the presentation file as read-only. - using (PresentationDocument document = PresentationDocument.Open(fileName, false)) - { - // Insert other code here. - } -``` +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/get_all_the_external_hyperlinks/cs/Program.cs#snippet1)] -### [Visual Basic](#tab/vb-0) -```vb - ' Open the presentation file as read-only. - Using document As PresentationDocument = PresentationDocument.Open(fileName, False) - ' Insert other code here. - End Using -``` +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/get_all_the_external_hyperlinks/vb/Program.vb#snippet1)] *** -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[Using Statement](../includes/presentation/using-statement.md)] `document`. -------------------------------------------------------------------------------- @@ -75,19 +59,18 @@ object that is created or named in the **using** statement, in this case **docum In this how-to code example, you are going to work with external hyperlinks. Therefore, it is best to familiarize yourself with the hyperlink element. The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification -introduces the **id** (Hyperlink Target). +introduces the `id` (Hyperlink Target). > Specifies the ID of the relationship whose target shall be used as the > target for thishyperlink. -> +> > If this attribute is omitted, then there shall be no external > hyperlink target for the current hyperlink - a location in the current > document can still be target via the anchor attribute. If this > attribute exists, it shall supersede the value in the anchor > attribute. -> -> [*Example*: Consider the following class="keyword">PresentationML** fragment for a hyperlink: +> +> [*Example*: Consider the following `PresentationML` fragment for a hyperlink: ```xml @@ -97,7 +80,7 @@ introduces the **id** (Hyperlink Target). ``` -> The **id** attribute value of **rId9** specifies that relationship in the +> The `id` attribute value of `rId9` specifies that relationship in the > associated relationship part item with a corresponding Id attribute > value must be navigated to when this hyperlink is invoked. For > example, if the following XML is present in the associated @@ -105,19 +88,18 @@ introduces the **id** (Hyperlink Target). ```xml - + ``` > The target of this hyperlink would therefore be the target of -> relationship **rId9** - in this case, +> relationship `rId9` - in this case, > https://www.example.com. *end example*] -> +> > The possible values for this attribute are defined by the > ST\_RelationshipId simple type(§22.8.2.1). -> -> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +> +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -------------------------------------------------------------------------------- @@ -128,79 +110,37 @@ all the slides in the presentation and returns a list of strings that represent the Universal Resource Identifiers (URIs) of all the external hyperlinks in the presentation. -### [C#](#tab/cs-1) -```csharp - // Iterate through all the slide parts in the presentation part. - foreach (SlidePart slidePart in document.PresentationPart.SlideParts) - { - IEnumerable links = slidePart.Slide.Descendants(); - - // Iterate through all the links in the slide part. - foreach (Drawing.HyperlinkType link in links) - { - - // Iterate through all the external relationships in the slide part. - foreach (HyperlinkRelationship relation in slidePart.HyperlinkRelationships) - { - // If the relationship ID matches the link ID… - if (relation.Id.Equals(link.Id)) - { - // Add the URI of the external relationship to the list of strings. - ret.Add(relation.Uri.AbsoluteUri); - - } -``` +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/get_all_the_external_hyperlinks/cs/Program.cs#snippet2)] -### [Visual Basic](#tab/vb-1) -```vb - ' Iterate through all the slide parts in the presentation part. - For Each slidePart As SlidePart In document.PresentationPart.SlideParts - Dim links As IEnumerable(Of Drawing.HyperlinkType) = slidePart.Slide.Descendants(Of Drawing.HyperlinkType)() - - ' Iterate through all the links in the slide part. - For Each link As Drawing.HyperlinkType In links - - ' Iterate through all the external relationships in the slide part. - For Each relation As HyperlinkRelationship In slidePart.HyperlinkRelationships - ' If the relationship ID matches the link ID… - If relation.Id.Equals(link.Id) Then - ' Add the URI of the external relationship to the list of strings. - ret.Add(relation.Uri.AbsoluteUri) - End If -``` +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/get_all_the_external_hyperlinks/vb/Program.vb#snippet2)] *** -------------------------------------------------------------------------------- ## Sample Code + Following is the complete code sample that you can use to return the list of all external links in a presentation. You can use the following -loop in your program to call the **GetAllExternalHyperlinksInPresentation** method to +loop in your program to call the `GetAllExternalHyperlinksInPresentation` method to get the list of URIs in your presentation. -### [C#](#tab/cs-2) -```csharp - string fileName = @"C:\Users\Public\Documents\Myppt7.pptx"; - foreach (string s in GetAllExternalHyperlinksInPresentation(fileName)) - Console.WriteLine(s); -``` +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/presentation/get_all_the_external_hyperlinks/cs/Program.cs#snippet3)] -### [Visual Basic](#tab/vb-2) -```vb - Dim fileName As String - fileName = "C:\Users\Public\Documents\Myppt7.pptx" - For Each s As String In GetAllExternalHyperlinksInPresentation(fileName) - Console.WriteLine(s) - Next -``` +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/presentation/get_all_the_external_hyperlinks/vb/Program.vb#snippet3)] *** +Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/get_all_the_external_hyperlinks/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/get_all_the_external_hyperlinks/cs/Program.cs#snippet)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/get_all_the_external_hyperlinks/vb/Program.vb)] +[!code-vb[](../../samples/presentation/get_all_the_external_hyperlinks/vb/Program.vb#snippet)] +*** -------------------------------------------------------------------------------- ## See also diff --git a/docs/presentation/how-to-get-all-the-text-in-a-slide-in-a-presentation.md b/docs/presentation/how-to-get-all-the-text-in-a-slide-in-a-presentation.md index 083855d4..5a1ae012 100644 --- a/docs/presentation/how-to-get-all-the-text-in-a-slide-in-a-presentation.md +++ b/docs/presentation/how-to-get-all-the-text-in-a-slide-in-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/06/2024 ms.localizationpriority: medium --- # Get all the text in a slide in a presentation @@ -24,44 +24,29 @@ programmatically. -------------------------------------------------------------------------------- ## Getting a PresentationDocument object -In the Open XML SDK, the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class represents a +In the Open XML SDK, the class represents a presentation document package. To work with a presentation document, -first create an instance of the **PresentationDocument** class, and then work with +first create an instance of the `PresentationDocument` class, and then work with that instance. To create the class instance from the document call the -[PresentationDocument.Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) + method that uses a file path, and a Boolean value as the second parameter to specify whether a document is editable. To open a document -for read/write access, assign the value **true** to this parameter; for read-only access -assign it the value **false** as shown in the -following **using** statement. In this code, -the **file** parameter is a string that +for read/write access, assign the value `true` to this parameter; for read-only access +assign it the value `false` as shown in the +following `using` statement. In this code, +the `file` parameter is a string that represents the path for the file from which you want to open the document. -### [C#](#tab/cs-0) -```csharp - // Open the presentation as read-only. - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - Using presentationDocument As PresentationDocument = PresentationDocument.Open(file, False) - ' Insert other code here. - End Using -``` +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/get_all_the_text_a_slide/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/get_all_the_text_a_slide/vb/Program.vb#snippet1)] *** -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 **presentationDocument**. +[!include[Using Statement](../includes/presentation/using-statement.md)] `presentationDocument`. -------------------------------------------------------------------------------- @@ -69,42 +54,19 @@ object that is created or named in the **using** statement, in this case **prese [!include[Structure](../includes/presentation/structure.md)] ## How the Sample Code Works -The sample code consists of three overloads of the **GetAllTextInSlide** method. In the following + +The sample code consists of three overloads of the `GetAllTextInSlide` method. In the following segment, the first overloaded method opens the source presentation that contains the slide with text to get, and passes the presentation to the second overloaded method, which gets the slide part. This method returns the array of strings that the second method returns to it, each of which represents a paragraph of text in the specified slide. -### [C#](#tab/cs-1) -```csharp - // Get all the text in a slide. - public static string[] GetAllTextInSlide(string presentationFile, int slideIndex) - { - // Open the presentation as read-only. - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false)) - { - // Pass the presentation and the slide index - // to the next GetAllTextInSlide method, and - // then return the array of strings it returns. - return GetAllTextInSlide(presentationDocument, slideIndex); - } - } -``` +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/get_all_the_text_a_slide/cs/Program.cs#snippet2)] -### [Visual Basic](#tab/vb-1) -```vb - ' Get all the text in a slide. - Public Shared Function GetAllTextInSlide(ByVal presentationFile As String, ByVal slideIndex As Integer) As String() - ' Open the presentation as read-only. - Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, False) - ' Pass the presentation and the slide index - ' to the next GetAllTextInSlide method, and - ' then return the array of strings it returns. - Return GetAllTextInSlide(presentationDocument, slideIndex) - End Using - End Function -``` +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/get_all_the_text_a_slide/vb/Program.vb#snippet2)] *** @@ -114,239 +76,57 @@ to the first overloaded method the array of strings that the third overloaded method returns to it, each of which represents a paragraph of text in the specified slide. -### [C#](#tab/cs-2) -```csharp - public static string[] GetAllTextInSlide(PresentationDocument presentationDocument, int slideIndex) - { - // Verify that the presentation document exists. - if (presentationDocument == null) - { - throw new ArgumentNullException("presentationDocument"); - } - - // Verify that the slide index is not out of range. - if (slideIndex < 0) - { - throw new ArgumentOutOfRangeException("slideIndex"); - } - - // Get the presentation part of the presentation document. - PresentationPart presentationPart = presentationDocument.PresentationPart; - - // Verify that the presentation part and presentation exist. - if (presentationPart != null && presentationPart.Presentation != null) - { - // Get the Presentation object from the presentation part. - Presentation presentation = presentationPart.Presentation; - - // Verify that the slide ID list exists. - if (presentation.SlideIdList != null) - { - // Get the collection of slide IDs from the slide ID list. - var slideIds = presentation.SlideIdList.ChildElements; - - // If the slide ID is in range... - if (slideIndex < slideIds.Count) - { - // Get the relationship ID of the slide. - string slidePartRelationshipId = (slideIds[slideIndex] as SlideId).RelationshipId; - - // Get the specified slide part from the relationship ID. - SlidePart slidePart = (SlidePart)presentationPart.GetPartById(slidePartRelationshipId); - - // Pass the slide part to the next method, and - // then return the array of strings that method - // returns to the previous method. - return GetAllTextInSlide(slidePart); - } - } - } - // Else, return null. - return null; - } -``` +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/presentation/get_all_the_text_a_slide/cs/Program.cs#snippet3)] -### [Visual Basic](#tab/vb-2) -```vb - Public Shared Function GetAllTextInSlide(ByVal presentationDocument As PresentationDocument, ByVal slideIndex As Integer) As String() - ' Verify that the presentation document exists. - If presentationDocument Is Nothing Then - Throw New ArgumentNullException("presentationDocument") - End If - - ' Verify that the slide index is not out of range. - If slideIndex < 0 Then - Throw New ArgumentOutOfRangeException("slideIndex") - End If - - ' Get the presentation part of the presentation document. - Dim presentationPart As PresentationPart = presentationDocument.PresentationPart - - ' Verify that the presentation part and presentation exist. - If presentationPart IsNot Nothing AndAlso presentationPart.Presentation IsNot Nothing Then - ' Get the Presentation object from the presentation part. - Dim presentation As Presentation = presentationPart.Presentation - - ' Verify that the slide ID list exists. - If presentation.SlideIdList IsNot Nothing Then - ' Get the collection of slide IDs from the slide ID list. - Dim slideIds = presentation.SlideIdList.ChildElements - - ' If the slide ID is in range... - If slideIndex < slideIds.Count Then - ' Get the relationship ID of the slide. - Dim slidePartRelationshipId As String = (TryCast(slideIds(slideIndex), SlideId)).RelationshipId - - ' Get the specified slide part from the relationship ID. - Dim slidePart As SlidePart = CType(presentationPart.GetPartById(slidePartRelationshipId), SlidePart) - - ' Pass the slide part to the next method, and - ' then return the array of strings that method - ' returns to the previous method. - Return GetAllTextInSlide(slidePart) - End If - End If - End If - - ' Else, return null. - Return Nothing - End Function -``` +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/presentation/get_all_the_text_a_slide/vb/Program.vb#snippet3)] *** - The following code segment shows the third overloaded method, which takes takes the slide part passed in, and returns to the second overloaded method a string array of text paragraphs. It starts by verifying that the slide part passed in exists, and then it creates a linked list of strings. It iterates through the paragraphs in the slide -passed in, and using a **StringBuilder** object +passed in, and using a `StringBuilder` object to concatenate all the lines of text in a paragraph, it assigns each paragraph to a string in the linked list. It then returns to the second overloaded method an array of strings that represents all the text in the specified slide in the presentation. -### [C#](#tab/cs-3) -```csharp - public static string[] GetAllTextInSlide(SlidePart slidePart) - { - // Verify that the slide part exists. - if (slidePart == null) - { - throw new ArgumentNullException("slidePart"); - } - - // Create a new linked list of strings. - LinkedList texts = new LinkedList(); - - // If the slide exists... - if (slidePart.Slide != null) - { - // Iterate through all the paragraphs in the slide. - foreach (var paragraph in slidePart.Slide.Descendants()) - { - // Create a new string builder. - StringBuilder paragraphText = new StringBuilder(); - - // Iterate through the lines of the paragraph. - foreach (var text in paragraph.Descendants()) - { - // Append each line to the previous lines. - paragraphText.Append(text.Text); - } - - if (paragraphText.Length > 0) - { - // Add each paragraph to the linked list. - texts.AddLast(paragraphText.ToString()); - } - } - } - - if (texts.Count > 0) - { - // Return an array of strings. - return texts.ToArray(); - } - else - { - return null; - } - } -``` +### [C#](#tab/cs-4) +[!code-csharp[](../../samples/presentation/get_all_the_text_a_slide/cs/Program.cs#snippet4)] -### [Visual Basic](#tab/vb-3) -```vb - Public Shared Function GetAllTextInSlide(ByVal slidePart As SlidePart) As String() - ' Verify that the slide part exists. - If slidePart Is Nothing Then - Throw New ArgumentNullException("slidePart") - End If - - ' Create a new linked list of strings. - Dim texts As New LinkedList(Of String)() - - ' If the slide exists... - If slidePart.Slide IsNot Nothing Then - ' Iterate through all the paragraphs in the slide. - For Each paragraph In slidePart.Slide.Descendants(Of DocumentFormat.OpenXml.Drawing.Paragraph)() - ' Create a new string builder. - Dim paragraphText As New StringBuilder() - - ' Iterate through the lines of the paragraph. - For Each text In paragraph.Descendants(Of DocumentFormat.OpenXml.Drawing.Text)() - ' Append each line to the previous lines. - paragraphText.Append(text.Text) - Next text - - If paragraphText.Length > 0 Then - ' Add each paragraph to the linked list. - texts.AddLast(paragraphText.ToString()) - End If - Next paragraph - End If - - If texts.Count > 0 Then - ' Return an array of strings. - Return texts.ToArray() - Else - Return Nothing - End If - End Function -``` +### [Visual Basic](#tab/vb-4) +[!code-vb[](../../samples/presentation/get_all_the_text_a_slide/vb/Program.vb#snippet4)] *** + -------------------------------------------------------------------------------- ## Sample Code + Following is the complete sample code that you can use to get all the text in a specific slide in a presentation file. For example, you can -use the following **foreach** loop in your -program to get the array of strings returned by the method **GetAllTextInSlide**, which represents the text in -the second slide of the presentation file "Myppt8.pptx." +use the following `foreach` loop in your +program to get the array of strings returned by the method `GetAllTextInSlide`, which represents the text in +the slide at the index of `slideIndex` of the presentation file found at the `filePath`. -### [C#](#tab/cs-4) -```csharp - foreach (string s in GetAllTextInSlide(@"C:\Users\Public\Documents\Myppt8.pptx", 1)) - Console.WriteLine(s); -``` +### [C#](#tab/cs-5) +[!code-csharp[](../../samples/presentation/get_all_the_text_a_slide/cs/Program.cs#snippet5)] -### [Visual Basic](#tab/vb-4) -```vb - For Each s As String In GetAllTextInSlide("C:\Users\Public\Documents\Myppt8.pptx", 1) - Console.WriteLine(s) - Next -``` +### [Visual Basic](#tab/vb-5) +[!code-vb[](../../samples/presentation/get_all_the_text_a_slide/vb/Program.vb#snippet5)] *** Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/get_all_the_text_a_slide/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/get_all_the_text_a_slide/cs/Program.cs#snippet)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/get_all_the_text_a_slide/vb/Program.vb)] +[!code-vb[](../../samples/presentation/get_all_the_text_a_slide/vb/Program.vb#snippet)] -------------------------------------------------------------------------------- ## See also diff --git a/docs/presentation/how-to-get-all-the-text-in-all-slides-in-a-presentation.md b/docs/presentation/how-to-get-all-the-text-in-all-slides-in-a-presentation.md index 1c03a39c..5b168982 100644 --- a/docs/presentation/how-to-get-all-the-text-in-all-slides-in-a-presentation.md +++ b/docs/presentation/how-to-get-all-the-text-in-all-slides-in-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/04/2024 ms.localizationpriority: medium --- # Get all the text in all slides in a presentation @@ -24,44 +24,29 @@ all of the text in all of the slides in a presentation programmatically. -------------------------------------------------------------------------------- ## Getting a PresentationDocument object -In the Open XML SDK, the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class represents a +In the Open XML SDK, the class represents a presentation document package. To work with a presentation document, -first create an instance of the **PresentationDocument** class, and then work with +first create an instance of the `PresentationDocument` class, and then work with that instance. To create the class instance from the document call the -[PresentationDocument.Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) + method that uses a file path, and a Boolean value as the second parameter to specify whether a document is editable. To open a document -for read/write access, assign the value **true** to this parameter; for read-only access -assign it the value **false** as shown in the -following **using** statement. In this code, -the **presentationFile** parameter is a string +for read/write access, assign the value `true` to this parameter; for read-only access +assign it the value `false` as shown in the +following `using` statement. In this code, +the `presentationFile` parameter is a string that represents the path for the file from which you want to open the document. -### [C#](#tab/cs-0) -```csharp - // Open the presentation as read-only. - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, False) - ' Insert other code here. - End Using -``` +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/get_all_the_text_all_slides/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/get_all_the_text_all_slides/vb/Program.vb#snippet1)] *** -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 **presentationDocument**. +[!include[Using Statement](../includes/presentation/using-statement.md)] `presentationDocument`. -------------------------------------------------------------------------------- @@ -70,55 +55,29 @@ object that is created or named in the **using** statement, in this case **prese ## Sample Code The following code gets all the text in all the slides in a specific -presentation file. For example, you can enter the name of the -presentation file from the keyboard, and then use a **foreach** loop in your program to get the array of -strings returned by the method **GetSlideIdAndText** as shown in the following +presentation file. For example, you can pass the name of the file as an argument, +and then use a `foreach` loop in your program to get the array of +strings returned by the method `GetSlideIdAndText` as shown in the following example. -### [C#](#tab/cs-1) -```csharp - Console.Write("Please enter a presentation file name without extension: "); - string fileName = Console.ReadLine(); - string file = @"C:\Users\Public\Documents\" + fileName + ".pptx"; - int numberOfSlides = CountSlides(file); - System.Console.WriteLine("Number of slides = {0}", numberOfSlides); - string slideText; - for (int i = 0; i < numberOfSlides; i++) - { - GetSlideIdAndText(out slideText, file, i); - System.Console.WriteLine("Slide #{0} contains: {1}", i + 1, slideText); - } - System.Console.ReadKey(); -``` +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/get_all_the_text_all_slides/cs/Program.cs#snippet2)] -### [Visual Basic](#tab/vb-1) -```vb - Console.Write("Please enter a presentation file name without extension: ") - Dim fileName As String = System.Console.ReadLine() - Dim file As String = "C:\Users\Public\Documents\" + fileName + ".pptx" - Dim numberOfSlides As Integer = CountSlides(file) - System.Console.WriteLine("Number of slides = {0}", numberOfSlides) - Dim slideText As String = Nothing - For i As Integer = 0 To numberOfSlides - 1 - GetSlideIdAndText(slideText, file, i) - System.Console.WriteLine("Slide #{0} contains: {1}", i + 1, slideText) - Next - System.Console.ReadKey() -``` +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/get_all_the_text_all_slides/vb/Program.vb#snippet2)] *** - The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/get_all_the_text_all_slides/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/get_all_the_text_all_slides/cs/Program.cs#snippet)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/get_all_the_text_all_slides/vb/Program.vb)] +[!code-vb[](../../samples/presentation/get_all_the_text_all_slides/vb/Program.vb#snippet)] +*** -------------------------------------------------------------------------------- ## See also -[Open XML SDK class library -reference](/office/open-xml/open-xml-sdk) +[Open XML SDK class library reference](/office/open-xml/open-xml-sdk) diff --git a/docs/presentation/how-to-get-the-titles-of-all-the-slides-in-a-presentation.md b/docs/presentation/how-to-get-the-titles-of-all-the-slides-in-a-presentation.md index f06c1b30..15916510 100644 --- a/docs/presentation/how-to-get-the-titles-of-all-the-slides-in-a-presentation.md +++ b/docs/presentation/how-to-get-the-titles-of-all-the-slides-in-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/04/2024 ms.localizationpriority: medium --- # Get the titles of all the slides in a presentation @@ -25,66 +25,44 @@ programmatically. --------------------------------------------------------------------------------- ## Getting a PresentationDocument Object -In the Open XML SDK, the **[PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument)** class represents a +In the Open XML SDK, the class represents a presentation document package. To work with a presentation document, -first create an instance of the **PresentationDocument** class, and then work with +first create an instance of the `PresentationDocument` class, and then work with that instance. To create the class instance from the document call the -**[PresentationDocument.Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open)** + method that uses a file path, and a Boolean value as the second parameter to specify whether a document is editable. To open a document -for read-only, specify the value **false** for -this parameter as shown in the following **using** statement. In this code, the **presentationFile** parameter is a string that +for read-only, specify the value `false` for +this parameter as shown in the following `using` statement. In this code, the `presentationFile` parameter is a string that represents the path for the file from which you want to open the document. -### [C#](#tab/cs-0) -```csharp - // Open the presentation as read-only. - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - ' Open the presentation as read-only. - Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, False) - ' Insert other code here. - End Using -``` +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/get_the_titles_of_all_the_slides/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/get_the_titles_of_all_the_slides/vb/Program.vb#snippet1)] *** -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 -*presentationDocument*. +[!include[Using Statement](../includes/presentation/using-statement.md)] `presentationDocument`. + [!include[Structure](../includes/presentation/structure.md)] ## Sample Code -The following is the complete sample code that you can use to get the +The following sample code gets all the titles of the slides in a presentation file. For example you can use the -following **foreach** statement in your program -to return all the titles in the presentation file, "Myppt9.pptx." +following `foreach` statement in your program +to return all the titles in the presentation file located at +the first argument. -### [C#](#tab/cs-1) -```csharp - foreach (string s in GetSlideTitles(@"C:\Users\Public\Documents\Myppt9.pptx")) - Console.WriteLine(s); -``` +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/get_the_titles_of_all_the_slides/cs/Program.cs#snippet2)] -### [Visual Basic](#tab/vb-1) -```vb - For Each s As String In GetSlideTitles("C:\Users\Public\Documents\Myppt9.pptx") - Console.WriteLine(s) - Next -``` +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/get_the_titles_of_all_the_slides/vb/Program.vb#snippet2)] *** @@ -94,10 +72,11 @@ the presentation, each on a separate line. Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/get_the_titles_of_all_the_slides/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/get_the_titles_of_all_the_slides/cs/Program.cs#snippet)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/get_the_titles_of_all_the_slides/vb/Program.vb)] +[!code-vb[](../../samples/presentation/get_the_titles_of_all_the_slides/vb/Program.vb#snippet)] +*** -------------------------------------------------------------------------------- ## See also diff --git a/docs/presentation/how-to-insert-a-new-slide-into-a-presentation.md b/docs/presentation/how-to-insert-a-new-slide-into-a-presentation.md index 1c0c65f2..b307498f 100644 --- a/docs/presentation/how-to-insert-a-new-slide-into-a-presentation.md +++ b/docs/presentation/how-to-insert-a-new-slide-into-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/03/2024 ms.localizationpriority: high --- # Insert a new slide into a presentation @@ -23,75 +23,103 @@ insert a new slide into a presentation programmatically. ## Getting a PresentationDocument Object -In the Open XML SDK, the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class represents a +In the Open XML SDK, the class represents a presentation document package. To work with a presentation document, -first create an instance of the **PresentationDocument** class, and then work with -that instance. To create the class instance from the document call the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) method that uses a +first create an instance of the `PresentationDocument` class, and then work with +that instance. To create the class instance from the document call the method that uses a file path, and a Boolean value as the second parameter to specify whether a document is editable. To open a document for read/write, -specify the value **true** for this parameter -as shown in the following **using** statement. -In this code segment, the *presentationFile* parameter is a string that +specify the value `true` for this parameter +as shown in the following `using` statement. +In this code segment, the `presentationFile` parameter is a string that represents the full path for the file from which you want to open the document. -### [C#](#tab/cs-0) -```csharp - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, True) - ' Insert other code here. - End Using -``` +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/insert_a_new_slideto/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/insert_a_new_slideto/vb/Program.vb#snippet1)] *** -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 -*presentationDocument*. +[!include[Using Statement](../includes/presentation/using-statement.md)] `presentationDocument`. [!include[Structure](../includes/presentation/structure.md)] -## Sample Code +## How the Sample Code Works -By using the sample code you can add a new slide to an existing -presentation. In your program, you can use the following call to the -**InsertNewSlide** method to add a new slide to -a presentation file named "Myppt10.pptx," with the title "My new slide," -at position 1. +The sample code consists of two overloads of the `InsertNewSlide` method. The first overloaded +method takes three parameters: the full path to the presentation file to +which to add a slide, an integer that represents the zero-based slide +index position in the presentation where to add the slide, and the +string that represents the title of the new slide. It opens the +presentation file as read/write, gets a `PresentationDocument` object, and then passes that +object to the second overloaded `InsertNewSlide` method, which performs the +insertion. -### [C#](#tab/cs-1) -```csharp - InsertNewSlide(@"C:\Users\Public\Documents\Myppt10.pptx", 1, "My new slide"); -``` +### [C#](#tab/cs-10) +[!code-csharp[](../../samples/presentation/insert_a_new_slideto/cs/Program.cs#snippet10)] -### [Visual Basic](#tab/vb-1) -```vb - InsertNewSlide("C:\Users\Public\Documents\Myppt10.pptx", 1, "My new slide") -``` +### [Visual Basic](#tab/vb-10) +[!code-vb[](../../samples/presentation/insert_a_new_slideto/vb/Program.vb#snippet10)] +*** + +The second overloaded `InsertNewSlide` method +creates a new `Slide` object, sets its +properties, and then inserts it into the slide order in the +presentation. The first section of the method creates the slide and sets +its properties. + +### [C#](#tab/cs-11) +[!code-csharp[](../../samples/presentation/insert_a_new_slideto/cs/Program.cs#snippet11)] + +### [Visual Basic](#tab/vb-11) +[!code-vb[](../../samples/presentation/insert_a_new_slideto/vb/Program.vb#snippet11)] +*** + +The next section of the second overloaded `InsertNewSlide` method adds a title shape to the +slide and sets its properties, including its text. + +### [C#](#tab/cs-12) +[!code-csharp[](../../samples/presentation/insert_a_new_slideto/cs/Program.cs#snippet12)] + +### [Visual Basic](#tab/vb-12) +[!code-vb[](../../samples/presentation/insert_a_new_slideto/vb/Program.vb#snippet12)] +*** + +The next section of the second overloaded `InsertNewSlide` method adds a body shape to the +slide and sets its properties, including its text. + +### [C#](#tab/cs-13) +[!code-csharp[](../../samples/presentation/insert_a_new_slideto/cs/Program.cs#snippet13)] + +### [Visual Basic](#tab/vb-13) +[!code-vb[](../../samples/presentation/insert_a_new_slideto/vb/Program.vb#snippet13)] *** +The final section of the second overloaded `InsertNewSlide` method creates a new slide part, +finds the specified index position where to insert the slide, and then +inserts it and assigns the new slide to the new slide part. -After you have run the program, the new slide would show up as the -second slide in the presentation. +### [C#](#tab/cs-14) +[!code-csharp[](../../samples/presentation/insert_a_new_slideto/cs/Program.cs#snippet14)] + +### [Visual Basic](#tab/vb-14) +[!code-vb[](../../samples/presentation/insert_a_new_slideto/vb/Program.vb#snippet14)] +*** + + +## Sample Code The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/insert_a_new_slideto/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/insert_a_new_slideto/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/insert_a_new_slideto/vb/Program.vb)] +[!code-vb[](../../samples/presentation/insert_a_new_slideto/vb/Program.vb#snippet0)] +*** ## See also diff --git a/docs/presentation/how-to-move-a-paragraph-from-one-presentation-to-another.md b/docs/presentation/how-to-move-a-paragraph-from-one-presentation-to-another.md index e800cebe..cb3d60f0 100644 --- a/docs/presentation/how-to-move-a-paragraph-from-one-presentation-to-another.md +++ b/docs/presentation/how-to-move-a-paragraph-from-one-presentation-to-another.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 12/02/2024 ms.localizationpriority: medium --- # Move a paragraph from one presentation to another @@ -24,41 +24,27 @@ programmatically. ## Getting a PresentationDocument Object -In the Open XML SDK, the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class represents a +In the Open XML SDK, the class represents a presentation document package. To work with a presentation document, -first create an instance of the **PresentationDocument** class, and then work with +first create an instance of the `PresentationDocument` class, and then work with that instance. To create the class instance from the document call the -[Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) method that uses a + method that uses a file path, and a Boolean value as the second parameter to specify whether a document is editable. To open a document for read/write, -specify the value **true** for this parameter -as shown in the following **using** statement. -In this code, the *file* parameter is a string that represents the path +specify the value `true` for this parameter +as shown in the following `using` statement. +In this code, the `sourceFile` parameter is a string that represents the path for the file from which you want to open the document. -### [C#](#tab/cs-0) -```csharp - using (PresentationDocument doc = PresentationDocument.Open(file, true)) - { - // Insert other code here. - } -``` +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/move_a_paragraph_from_one_presentation_to_another/cs/Program.cs#snippet1)] -### [Visual Basic](#tab/vb-0) -```vb - Using doc As PresentationDocument = PresentationDocument.Open(file, True) - ' Insert other code here. - End Using -``` +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/move_a_paragraph_from_one_presentation_to_another/vb/Program.vb#snippet1)] *** -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 *doc*. +[!include[Using Statement](../includes/presentation/using-statement.md)] `sourceDoc`. [!include[Structure](../includes/presentation/structure.md)] @@ -72,7 +58,7 @@ introduces the structure of this element. > properties are contained within this element. There can be multiple > paragraphs and within paragraphs multiple runs of text. > -> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following table lists the child elements of the shape text body and the description of each. @@ -97,194 +83,52 @@ The following XML Schema fragment defines the contents of this element: ## How the Sample Code Works -The code in this topic consists of two methods, **MoveParagraphToPresentation** and **GetFirstSlide**. The first method takes two string +The code in this topic consists of two methods, `MoveParagraphToPresentation` and `GetFirstSlide`. The first method takes two string parameters: one that represents the source file, which contains the paragraph to move, and one that represents the target file, to which the paragraph is moved. The method opens both presentation files and then -calls the **GetFirstSlide** method to get the -first slide in each file. It then gets the first **TextBody** shape in each slide and the first -paragraph in the source shape. It performs a **deep -clone** of the source paragraph, copying not only the source **Paragraph** object itself, but also everything +calls the `GetFirstSlide` method to get the +first slide in each file. It then gets the first `TextBody` shape in each slide and the first +paragraph in the source shape. It performs a `deep clone` of the source paragraph, +copying not only the source `Paragraph` object itself, but also everything contained in that object, including its text. It then inserts the cloned paragraph in the target file and removes the source paragraph from the source file, replacing it with a placeholder paragraph. Finally, it saves the modified slides in both presentations. -### [C#](#tab/cs-1) -```csharp - // Moves a paragraph range in a TextBody shape in the source document - // to another TextBody shape in the target document. - public static void MoveParagraphToPresentation(string sourceFile, string targetFile) - { - // Open the source file as read/write. - using (PresentationDocument sourceDoc = PresentationDocument.Open(sourceFile, true)) - { - // Open the target file as read/write. - using (PresentationDocument targetDoc = PresentationDocument.Open(targetFile, true)) - { - // Get the first slide in the source presentation. - SlidePart slide1 = GetFirstSlide(sourceDoc); - - // Get the first TextBody shape in it. - TextBody textBody1 = slide1.Slide.Descendants().First(); - - // Get the first paragraph in the TextBody shape. - // Note: "Drawing" is the alias of namespace DocumentFormat.OpenXml.Drawing - Drawing.Paragraph p1 = textBody1.Elements().First(); - - // Get the first slide in the target presentation. - SlidePart slide2 = GetFirstSlide(targetDoc); - - // Get the first TextBody shape in it. - TextBody textBody2 = slide2.Slide.Descendants().First(); - - // Clone the source paragraph and insert the cloned. paragraph into the target TextBody shape. - // Passing "true" creates a deep clone, which creates a copy of the - // Paragraph object and everything directly or indirectly referenced by that object. - textBody2.Append(p1.CloneNode(true)); - - // Remove the source paragraph from the source file. - textBody1.RemoveChild(p1); - - // Replace the removed paragraph with a placeholder. - textBody1.AppendChild(new Drawing.Paragraph()); - - // Save the slide in the source file. - slide1.Slide.Save(); - - // Save the slide in the target file. - slide2.Slide.Save(); - } - } - } -``` +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/move_a_paragraph_from_one_presentation_to_another/cs/Program.cs#snippet2)] -### [Visual Basic](#tab/vb-1) -```vb - ' Moves a paragraph range in a TextBody shape in the source document - ' to another TextBody shape in the target document. - Public Shared Sub MoveParagraphToPresentation(ByVal sourceFile As String, ByVal targetFile As String) - ' Open the source file as read/write. - Using sourceDoc As PresentationDocument = PresentationDocument.Open(sourceFile, True) - ' Open the target file as read/write. - Using targetDoc As PresentationDocument = PresentationDocument.Open(targetFile, True) - ' Get the first slide in the source presentation. - Dim slide1 As SlidePart = GetFirstSlide(sourceDoc) - - ' Get the first TextBody shape in it. - Dim textBody1 As TextBody = slide1.Slide.Descendants(Of TextBody)().First() - - ' Get the first paragraph in the TextBody shape. - ' Note: "Drawing" is the alias of namespace DocumentFormat.OpenXml.Drawing - Dim p1 As Drawing.Paragraph = textBody1.Elements(Of Drawing.Paragraph)().First() - - ' Get the first slide in the target presentation. - Dim slide2 As SlidePart = GetFirstSlide(targetDoc) - - ' Get the first TextBody shape in it. - Dim textBody2 As TextBody = slide2.Slide.Descendants(Of TextBody)().First() - - ' Clone the source paragraph and insert the cloned. paragraph into the target TextBody shape. - ' Passing "true" creates a deep clone, which creates a copy of the - ' Paragraph object and everything directly or indirectly referenced by that object. - textBody2.Append(p1.CloneNode(True)) - - ' Remove the source paragraph from the source file. - textBody1.RemoveChild(Of Drawing.Paragraph)(p1) - - ' Replace the removed paragraph with a placeholder. - textBody1.AppendChild(Of Drawing.Paragraph)(New Drawing.Paragraph()) - - ' Save the slide in the source file. - slide1.Slide.Save() - - ' Save the slide in the target file. - slide2.Slide.Save() - End Using - End Using - End Sub -``` +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/move_a_paragraph_from_one_presentation_to_another/vb/Program.vb#snippet2)] *** -The **GetFirstSlide** method takes the **PresentationDocument** object passed in, gets its +The `GetFirstSlide` method takes the `PresentationDocument` object passed in, gets its presentation part, and then gets the ID of the first slide in its slide list. It then gets the relationship ID of the slide, gets the slide part from the relationship ID, and returns the slide part to the calling method. -### [C#](#tab/cs-2) -```csharp - // Get the slide part of the first slide in the presentation document. - public static SlidePart GetFirstSlide(PresentationDocument presentationDocument) - { - // Get relationship ID of the first slide - PresentationPart part = presentationDocument.PresentationPart; - SlideId slideId = part.Presentation.SlideIdList.GetFirstChild(); - string relId = slideId.RelationshipId; - - // Get the slide part by the relationship ID. - SlidePart slidePart = (SlidePart)part.GetPartById(relId); - - return slidePart; - } -``` - -### [Visual Basic](#tab/vb-2) -```vb - ' Get the slide part of the first slide in the presentation document. - Public Shared Function GetFirstSlide(ByVal presentationDocument As PresentationDocument) As SlidePart - ' Get relationship ID of the first slide - Dim part As PresentationPart = presentationDocument.PresentationPart - Dim slideId As SlideId = part.Presentation.SlideIdList.GetFirstChild(Of SlideId)() - Dim relId As String = slideId.RelationshipId - - ' Get the slide part by the relationship ID. - Dim slidePart As SlidePart = CType(part.GetPartById(relId), SlidePart) - - Return slidePart - End Function -``` -*** - - -## Sample Code - -By using this sample code, you can move a paragraph from one -presentation to another. In your program, you can use the following call -to the **MoveParagraphToPresentation** method -to move the first paragraph from the presentation file "Myppt4.pptx" to -the presentation file "Myppt12.pptx". - ### [C#](#tab/cs-3) -```csharp - string sourceFile = @"C:\Users\Public\Documents\Myppt4.pptx"; - string targetFile = @"C:\Users\Public\Documents\Myppt12.pptx"; - MoveParagraphToPresentation(sourceFile, targetFile); -``` +[!code-csharp[](../../samples/presentation/move_a_paragraph_from_one_presentation_to_another/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-3) -```vb - Dim sourceFile As String = "C:\Users\Public\Documents\Myppt4.pptx" - Dim targetFile As String = "C:\Users\Public\Documents\Myppt12.pptx" - MoveParagraphToPresentation(sourceFile, targetFile) -``` +[!code-vb[](../../samples/presentation/move_a_paragraph_from_one_presentation_to_another/vb/Program.vb#snippet3)] *** -After you run the program take a look on the content of both the source -and the target files to see the moved paragraph. +## Sample Code The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/move_a_paragraph_from_one_presentation_to_another/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/move_a_paragraph_from_one_presentation_to_another/cs/Program.cs#snippet)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/move_a_paragraph_from_one_presentation_to_another/vb/Program.vb)] +[!code-vb[](../../samples/presentation/move_a_paragraph_from_one_presentation_to_another/vb/Program.vb#snippet)] +*** ## See also - - - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) diff --git a/docs/presentation/how-to-move-a-slide-to-a-new-position-in-a-presentation.md b/docs/presentation/how-to-move-a-slide-to-a-new-position-in-a-presentation.md index e8bf6e84..d8c70637 100644 --- a/docs/presentation/how-to-move-a-slide-to-a-new-position-in-a-presentation.md +++ b/docs/presentation/how-to-move-a-slide-to-a-new-position-in-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/02/2024 ms.localizationpriority: medium --- # Move a slide to a new position in a presentation @@ -24,46 +24,31 @@ programmatically. -------------------------------------------------------------------------------- ## Getting a Presentation Object -In the Open XML SDK, the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class represents a + +In the Open XML SDK, the class represents a presentation document package. To work with a presentation document, -first create an instance of the **PresentationDocument** class, and then work with +first create an instance of the `PresentationDocument` class, and then work with that instance. To create the class instance from the document call the -[Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) method that uses a + method that uses a file path, and a Boolean value as the second parameter to specify whether a document is editable. In order to count the number of slides in a presentation, it is best to open the file for read-only access in order to avoid accidental writing to the file. To do that, specify the -value **false** for the Boolean parameter as -shown in the following **using** statement. In -this code, the **presentationFile** parameter +value `false` for the Boolean parameter as +shown in the following `using` statement. In +this code, the `presentationFile` parameter is a string that represents the path for the file from which you want to open the document. ### [C#](#tab/cs-0) -```csharp - // Open the presentation as read-only. - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false)) - { - // Insert other code here. - } -``` +[!code-csharp[](../../samples/presentation/move_a_slide_to_a_new_position/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - ' Open the presentation as read-only. - Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, False) - ' Insert other code here. - End Using -``` +[!code-vb[](../../samples/presentation/move_a_slide_to_a_new_position/vb/Program.vb#snippet1)] *** -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 **presentationDocument**. +[!include[Using Statement](../includes/presentation/using-statement.md)] `presentationDocument`. -------------------------------------------------------------------------------- @@ -71,6 +56,7 @@ object that is created or named in the **using** statement, in this case **prese [!include[Structure](../includes/presentation/structure.md)] ## How the Sample Code Works + In order to move a specific slide in a presentation file to a new position, you need to know first the number of slides in the presentation. Therefore, the code in this topic is divided into two @@ -79,300 +65,118 @@ moving a slide to a new position. -------------------------------------------------------------------------------- + ## Counting the Number of Slides + The sample code for counting the number of slides consists of two -overloads of the method **CountSlides**. The -first overload uses a **string** parameter and -the second overload uses a **PresentationDocument** parameter. In the first -**CountSlides** method, the sample code opens -the presentation document in the **using** -statement. Then it passes the **PresentationDocument** object to the second **CountSlides** method, which returns an integer +overloads of the method `CountSlides`. The +first overload uses a `string` parameter and +the second overload uses a `PresentationDocument` parameter. In the first +`CountSlides` method, the sample code opens +the presentation document in the `using` +statement. Then it passes the `PresentationDocument` object to the second `CountSlides` method, which returns an integer number that represents the number of slides in the presentation. ### [C#](#tab/cs-1) -```csharp - // Pass the presentation to the next CountSlides method - // and return the slide count. - return CountSlides(presentationDocument); -``` +[!code-csharp[](../../samples/presentation/move_a_slide_to_a_new_position/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - ' Pass the presentation to the next CountSlides method - ' and return the slide count. - Return CountSlides(presentationDocument) -``` +[!code-vb[](../../samples/presentation/move_a_slide_to_a_new_position/vb/Program.vb#snippet2)] *** -In the second **CountSlides** method, the code -verifies that the **PresentationDocument** -object passed in is not **null**, and if it is -not, it gets a **PresentationPart** object from -the **PresentationDocument** object. By using -the **SlideParts** the code gets the **slideCount** and returns it. +In the second `CountSlides` method, the code +verifies that the `PresentationDocument` +object passed in is not `null`, and if it is +not, it gets a `PresentationPart` object from +the `PresentationDocument` object. By using +the `SlideParts` the code gets the `slideCount` and returns it. ### [C#](#tab/cs-2) -```csharp - // Check for a null document object. - if (presentationDocument == null) - { - throw new ArgumentNullException("presentationDocument"); - } - - int slidesCount = 0; - - // Get the presentation part of document. - PresentationPart presentationPart = presentationDocument.PresentationPart; - - // Get the slide count from the SlideParts. - if (presentationPart != null) - { - slidesCount = presentationPart.SlideParts.Count(); - } - // Return the slide count to the previous method. - return slidesCount; -``` +[!code-csharp[](../../samples/presentation/move_a_slide_to_a_new_position/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - ' Check for a null document object. - If presentationDocument Is Nothing Then - Throw New ArgumentNullException("presentationDocument") - End If - - Dim slidesCount As Integer = 0 - - ' Get the presentation part of document. - Dim presentationPart As PresentationPart = presentationDocument.PresentationPart - - ' Get the slide count from the SlideParts. - If presentationPart IsNot Nothing Then - slidesCount = presentationPart.SlideParts.Count() - End If - ' Return the slide count to the previous method. - Return slidesCount -``` +[!code-vb[](../../samples/presentation/move_a_slide_to_a_new_position/vb/Program.vb#snippet3)] *** -------------------------------------------------------------------------------- + ## Moving a Slide from one Position to Another + Moving a slide to a new position requires opening the file for -read/write access by specifying the value **true** to the Boolean parameter as shown in the -following **using** statement. The code for -moving a slide consists of two overloads of the **MoveSlide** method. The first overloaded **MoveSlide** method takes three parameters: a string +read/write access by specifying the value `true` to the Boolean parameter as shown in the +following `using` statement. The code for +moving a slide consists of two overloads of the `MoveSlide` method. The first overloaded `MoveSlide` method takes three parameters: a string that represents the presentation file name and path and two integers that represent the current index position of the slide and the index position to which to move the slide respectively. It opens the -presentation file, gets a **PresentationDocument** object, and then passes that -object and the two integers, *from* and *to*, to the second overloaded -**MoveSlide** method, which performs the actual +presentation file, gets a `PresentationDocument` object, and then passes that +object and the two integers, `from` and `to`, to the second overloaded +`MoveSlide` method, which performs the actual move. ### [C#](#tab/cs-3) -```csharp - // Move a slide to a different position in the slide order in the presentation. - public static void MoveSlide(string presentationFile, int from, int to) - { - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true)) - { - MoveSlide(presentationDocument, from, to); - } - } -``` +[!code-csharp[](../../samples/presentation/move_a_slide_to_a_new_position/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - ' Move a slide to a different position in the slide order in the presentation. - Public Shared Sub MoveSlide(ByVal presentationFile As String, ByVal [from] As Integer, ByVal [to] As Integer) - Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, True) - MoveSlide(presentationDocument, From, [to]) - End Using - End Sub -``` +[!code-vb[](../../samples/presentation/move_a_slide_to_a_new_position/vb/Program.vb#snippet4)] *** -In the second overloaded **MoveSlide** method, -the **CountSlides** method is called to get the +In the second overloaded `MoveSlide` method, +the `CountSlides` method is called to get the number of slides in the presentation. The code then checks if the -zero-based indexes, *from* and *to*, are within the range and different +zero-based indexes, `from` and `to`, are within the range and different from one another. ### [C#](#tab/cs-4) -```csharp - public static void MoveSlide(PresentationDocument presentationDocument, int from, int to) - { - if (presentationDocument == null) - { - throw new ArgumentNullException("presentationDocument"); - } - - // Call the CountSlides method to get the number of slides in the presentation. - int slidesCount = CountSlides(presentationDocument); - - // Verify that both from and to positions are within range and different from one another. - if (from < 0 || from >= slidesCount) - { - throw new ArgumentOutOfRangeException("from"); - } - - if (to < 0 || from >= slidesCount || to == from) - { - throw new ArgumentOutOfRangeException("to"); - } -``` +[!code-csharp[](../../samples/presentation/move_a_slide_to_a_new_position/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - Public Shared Sub MoveSlide(ByVal presentationDocument As PresentationDocument, ByVal [from] As Integer, ByVal [to] As Integer) - If presentationDocument Is Nothing Then - Throw New ArgumentNullException("presentationDocument") - End If - - ' Call the CountSlides method to get the number of slides in the presentation. - Dim slidesCount As Integer = CountSlides(presentationDocument) - - ' Verify that both from and to positions are within range and different from one another. - If - From < 0 OrElse - From >= slidesCount Then - Throw New ArgumentOutOfRangeException("from") - End If - - If [to] < 0 OrElse - From >= slidesCount OrElse [to] = - From Then - Throw New ArgumentOutOfRangeException("to") - End If -``` +[!code-vb[](../../samples/presentation/move_a_slide_to_a_new_position/vb/Program.vb#snippet5)] *** -A **PresentationPart** object is declared and -set equal to the presentation part of the **PresentationDocument** object passed in. The **PresentationPart** object is used to create a **Presentation** object, and then create a **SlideIdList** object that represents the list of -slides in the presentation from the **Presentation** object. A slide ID of the source +A `PresentationPart` object is declared and +set equal to the presentation part of the `PresentationDocument` object passed in. The `PresentationPart` object is used to create a `Presentation` object, and then create a `SlideIdList` object that represents the list of +slides in the presentation from the `Presentation` object. A slide ID of the source slide (the slide to move) is obtained, and then the position of the target slide (the slide after which in the slide order to move the source slide) is identified. ### [C#](#tab/cs-5) -```csharp - // Get the presentation part from the presentation document. - PresentationPart presentationPart = presentationDocument.PresentationPart; - - // The slide count is not zero, so the presentation must contain slides. - Presentation presentation = presentationPart.Presentation; - SlideIdList slideIdList = presentation.SlideIdList; - - // Get the slide ID of the source slide. - SlideId sourceSlide = slideIdList.ChildElements[from] as SlideId; - - SlideId targetSlide = null; - - // Identify the position of the target slide after which to move the source slide. - if (to == 0) - { - targetSlide = null; - } - else if (from < to) - { - targetSlide = slideIdList.ChildElements[to] as SlideId; - } - else - { - targetSlide = slideIdList.ChildElements[to - 1] as SlideId; - } -``` +[!code-csharp[](../../samples/presentation/move_a_slide_to_a_new_position/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-5) -```vb - ' Get the presentation part from the presentation document. - Dim presentationPart As PresentationPart = presentationDocument.PresentationPart - - ' The slide count is not zero, so the presentation must contain slides. - Dim presentation As Presentation = presentationPart.Presentation - Dim slideIdList As SlideIdList = presentation.SlideIdList - - ' Get the slide ID of the source slide. - Dim sourceSlide As SlideId = TryCast(slideIdList.ChildElements(From), SlideId) - - Dim targetSlide As SlideId = Nothing - - ' Identify the position of the target slide after which to move the source slide. - If to = 0 Then - targetSlide = Nothing - ElseIf From < to Then - targetSlide = TryCast(slideIdList.ChildElements(to), SlideId) - Else - targetSlide = TryCast(slideIdList.ChildElements(to - 1), SlideId) - End If -``` +[!code-vb[](../../samples/presentation/move_a_slide_to_a_new_position/vb/Program.vb#snippet6)] *** -The **Remove** method of the **SlideID** object is used to remove the source slide -from its current position, and then the **InsertAfter** method of the **SlideIdList** object is used to insert the source +The `Remove` method of the `SlideID` object is used to remove the source slide +from its current position, and then the `InsertAfter` method of the `SlideIdList` object is used to insert the source slide in the index position after the target slide. Finally, the modified presentation is saved. ### [C#](#tab/cs-6) -```csharp - // Remove the source slide from its current position. - sourceSlide.Remove(); - - // Insert the source slide at its new position after the target slide. - slideIdList.InsertAfter(sourceSlide, targetSlide); - - // Save the modified presentation. - presentation.Save(); -``` +[!code-csharp[](../../samples/presentation/move_a_slide_to_a_new_position/cs/Program.cs#snippet7)] ### [Visual Basic](#tab/vb-6) -```vb - ' Remove the source slide from its current position. - sourceSlide.Remove() - - ' Insert the source slide at its new position after the target slide. - slideIdList.InsertAfter(sourceSlide, targetSlide) - - ' Save the modified presentation. - presentation.Save() -``` +[!code-vb[](../../samples/presentation/move_a_slide_to_a_new_position/vb/Program.vb#snippet7)] *** -------------------------------------------------------------------------------- ## Sample Code Following is the complete sample code that you can use to move a slide -from one position to another in the same presentation file. For -instance, you can use the following call in your program to move a slide -from position 0 to position 1 in a presentation file named -"Myppt11.pptx". - -### [C#](#tab/cs-7) -```csharp - MoveSlide(@"C:\Users\Public\Documents\Myppt11.pptx", 0, 1); -``` - -### [Visual Basic](#tab/vb-7) -```vb - MoveSlide("C:\Users\Public\Documents\Myppt11.pptx", 0, 1) -``` -*** - - -After you run the program, check your presentation file to see the new -positions of the slides. - -Following is the complete sample code in both C\# and Visual Basic. +from one position to another in the same presentation file in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/move_a_slide_to_a_new_position/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/move_a_slide_to_a_new_position/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/move_a_slide_to_a_new_position/vb/Program.vb)] +[!code-vb[](../../samples/presentation/move_a_slide_to_a_new_position/vb/Program.vb#snippet0)] +*** -------------------------------------------------------------------------------- ## See also diff --git a/docs/presentation/how-to-open-a-presentation-document-for-read-only-access.md b/docs/presentation/how-to-open-a-presentation-document-for-read-only-access.md index cf9211df..7c75d558 100644 --- a/docs/presentation/how-to-open-a-presentation-document-for-read-only-access.md +++ b/docs/presentation/how-to-open-a-presentation-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: 11/27/2024 ms.localizationpriority: medium --- # Open a presentation document for read-only access @@ -35,37 +35,37 @@ document. ## Create an Instance of the PresentationDocument Class -In the Open XML SDK, the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class represents a +In the Open XML SDK, the class represents a presentation document package. To work with a presentation document, -first create an instance of the **PresentationDocument** class, and then work with +first create an instance of the `PresentationDocument` class, and then work with that instance. To create the class instance from the document call one -of the [Open](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) methods. Several Open methods are +of the methods. Several Open methods are provided, each with a different signature. The following table contains -a subset of the overloads for the **Open** +a subset of the overloads for the `Open` method that you can use to open the package. | Name | Description | |---|---| -| [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) | Create a new instance of the **PresentationDocument** class from the specified file. | -| [Open(Stream, Boolean)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) | Create a new instance of the **PresentationDocument** class from the I/O stream. | -| [Open(Package)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) | Create a new instance of the **PresentationDocument** class from the specified package. | +| | Create a new instance of the `PresentationDocument` class from the specified file. | +| | Create a new instance of the `PresentationDocument` class from the I/O stream. | +| | Create a new instance of the `PresentationDocument` class from the specified package. | -The previous table includes two **Open** +The previous table includes two `Open` methods that accept a Boolean value as the second parameter to specify whether a document is editable. To open a document for read-only access, -specify the value **false** for this parameter. +specify the value `false` for this parameter. For example, you can open the presentation file as read-only and assign -it to a [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) object as shown in the -following **using** statement. In this code, -the **presentationFile** parameter is a string +it to a object as shown in the +following `using` statement. In this code, +the `presentationFile` parameter is a string that represents the path of the file from which you want to open the document. ### [C#](#tab/cs-0) ```csharp - using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false)) + using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFilePath, false)) { // Insert other code here. } @@ -73,15 +73,15 @@ document. ### [Visual Basic](#tab/vb-0) ```vb - Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, False) + Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFilePath, False) ' Insert other code here. End Using ``` *** -You can also use the second overload of the **Open** method, in the table above, to create an -instance of the **PresentationDocument** class +You can also use the second overload of the `Open` method, in the table above, to create an +instance of the `PresentationDocument` class based on an I/O stream. You might use this approach if you have a Microsoft SharePoint Foundation 2010 application that uses stream I/O and you want to use the Open XML SDK to work with a document. The @@ -90,8 +90,7 @@ following code segment opens a document based on a stream. ### [C#](#tab/cs-1) ```csharp Stream stream = File.Open(strDoc, FileMode.Open); - using (PresentationDocument presentationDocument = - PresentationDocument.Open(stream, false)) + using (PresentationDocument presentationDocument = PresentationDocument.Open(stream, false)) { // Place other code here. } @@ -108,21 +107,20 @@ following code segment opens a document based on a stream. Suppose you have an application that employs the Open XML support in the -**System.IO.Packaging** namespace of the .NET +`System.IO.Packaging` namespace of the .NET Framework Class Library, and you want to use the Open XML SDK to work with a package read-only. The Open XML SDK includes a method -overload that accepts a **Package** as the only +overload that accepts a `Package` as the only parameter. There is no Boolean parameter to indicate whether the document should be opened for editing. The recommended approach is to open the package as read-only prior to creating the instance of the -**PresentationDocument** class. The following +`PresentationDocument` class. The following code segment performs this operation. ### [C#](#tab/cs-2) ```csharp Package presentationPackage = Package.Open(filepath, FileMode.Open, FileAccess.Read); - using (PresentationDocument presentationDocument = - PresentationDocument.Open(presentationPackage)) + using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationPackage)) { // Other code goes here. } @@ -143,68 +141,29 @@ code segment performs this operation. ## How the Sample Code Works In the sample code, after you open the presentation document in the -**using** statement for read-only access, -instantiate the **PresentationPart**, and open +`using` statement for read-only access, +instantiate the `PresentationPart`, and open the slide list. Then you get the relationship ID of the first slide. ### [C#](#tab/cs-3) -```csharp - // Get the relationship ID of the first slide. - PresentationPart part = ppt.PresentationPart; - OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; - string relId = (slideIds[index] as SlideId).RelationshipId; -``` - +[!code-csharp[](../../samples/presentation/open_for_read_only_access/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-3) -```vb - ' Get the relationship ID of the first slide. - Dim part As PresentationPart = ppt.PresentationPart - Dim slideIds As OpenXmlElementList = part.Presentation.SlideIdList.ChildElements - Dim relId As String = (TryCast(slideIds(index), SlideId)).RelationshipId -``` +[!code-vb[](../../samples/presentation/open_for_read_only_access/vb/Program.vb#snippet2)] *** -From the relationship ID, **relId**, you get the +From the relationship ID, `relId`, you get the slide part, and then the inner text of the slide by building a text -string using **StringBuilder**. +string using `StringBuilder`. ### [C#](#tab/cs-4) -```csharp - // Get the slide part from the relationship ID. - SlidePart slide = (SlidePart)part.GetPartById(relId); - - // Build a StringBuilder object. - StringBuilder paragraphText = new StringBuilder(); - - // Get the inner text of the slide. - IEnumerable texts = slide.Slide.Descendants(); - foreach (A.Text text in texts) - { - paragraphText.Append(text.Text); - } - sldText = paragraphText.ToString(); -``` - +[!code-csharp[](../../samples/presentation/open_for_read_only_access/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-4) -```vb - ' Get the slide part from the relationship ID. - Dim slide As SlidePart = CType(part.GetPartById(relId), SlidePart) - - ' Build a StringBuilder object. - Dim paragraphText As New StringBuilder() - - ' Get the inner text of the slide. - Dim texts As IEnumerable(Of A.Text) = slide.Slide.Descendants(Of A.Text)() - For Each text As A.Text In texts - paragraphText.Append(text.Text) - Next text - sldText = paragraphText.ToString() -``` +[!code-vb[](../../samples/presentation/open_for_read_only_access/vb/Program.vb#snippet3)] *** -The inner text of the slide, which is an **out** parameter of the **GetSlideIdAndText** method, is passed back to the +The inner text of the slide, which is an `out` parameter of the `GetSlideIdAndText` method, is passed back to the main method to be displayed. > [!IMPORTANT] @@ -214,54 +173,30 @@ main method to be displayed. ## Sample Code The following example opens a presentation file for read-only access and -gets the inner text of a slide at a specified index. To call the method **GetSlideIdAndText** pass in the full path of the -presentation document. Also pass in the **out** -parameter **sldText**, which will be assigned a +gets the inner text of a slide at a specified index. To call the method `GetSlideIdAndText` pass in the full path of the +presentation document. Also pass in the `out` +parameter `sldText`, which will be assigned a value in the method itself, and then you can display its value in the -main program. For example, the following call to the **GetSlideIdAndText** method gets the inner text in -the second slide in a presentation file named "Myppt13.pptx". +main program. For example, the following call to the `GetSlideIdAndText` method gets the inner text in a presentation file +from the index and file path passed to the application as arguments. > [!TIP] -> The most expected exception in this program is the **ArgumentOutOfRangeException** exception. It could be thrown if, for example, you have a file with two slides, and you wanted to display the text in slide number 4. Therefore, it is best to use a **try** block when you call the **GetSlideIdAndText** method as shown in the following example. +> The most expected exception in this program is the `ArgumentOutOfRangeException` exception. It could be thrown if, for example, you have a file with two slides, and you wanted to display the text in slide number 4. Therefore, it is best to use a `try` block when you call the `GetSlideIdAndText` method as shown in the following example. ### [C#](#tab/cs-5) -```csharp - string file = @"C:\Users\Public\Documents\Myppt13.pptx"; - string slideText; - int index = 1; - try - { - GetSlideIdAndText(out slideText, file, index); - Console.WriteLine("The text in the slide #{0} is: {1}", index + 1, slideText); - } - catch (ArgumentOutOfRangeException exp) - { - Console.WriteLine(exp.Message); - } -``` - +[!code-csharp[](../../samples/presentation/open_for_read_only_access/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-5) -```vb - Dim file As String = "C:\Users\Public\Documents\Myppt13.pptx" - Dim slideText As String = Nothing - Dim index As Integer = 1 - Try - GetSlideIdAndText(slideText, file, index) - Console.WriteLine("The text in the slide #{0} is: {1}", index + 1, slideText) - Catch exp As ArgumentOutOfRangeException - Console.WriteLine(exp.Message) - End Try -``` +[!code-vb[](../../samples/presentation/open_for_read_only_access/vb/Program.vb#snippet4)] *** The following is the complete code listing in C\# and Visual Basic. -### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/open_for_read_only_access/cs/Program.cs)] +### [C#](#tab/cs-6) +[!code-csharp[](../../samples/presentation/open_for_read_only_access/cs/Program.cs#snippet0)] -### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/open_for_read_only_access/vb/Program.vb)] +### [Visual Basic](#tab/vb-6) +[!code-vb[](../../samples/presentation/open_for_read_only_access/vb/Program.vb#snippet0)] ## See also diff --git a/docs/presentation/how-to-reply-to-a-comment-in-a-presentation.md b/docs/presentation/how-to-reply-to-a-comment-in-a-presentation.md new file mode 100644 index 00000000..9813f31e --- /dev/null +++ b/docs/presentation/how-to-reply-to-a-comment-in-a-presentation.md @@ -0,0 +1,91 @@ +--- + +api_name: +- Microsoft.Office.DocumentFormat.OpenXML.Packaging +api_type: +- schema +ms.assetid: 9774217d-1f71-494a-9ab9-a711661f8e83 +title: 'How to: Reply to a comment in a presentation' +ms.suite: office + +ms.author: o365devx +author: o365devx +ms.topic: conceptual +ms.date: 08/12/2025 +ms.localizationpriority: medium +--- + +# Reply to a comment in a presentation + +This topic shows how to use the classes in the Open XML SDK for +Office to reply to existing comments in a presentation +programmatically. + + +[!include[Structure](../includes/presentation/structure.md)] + +[!include[description of a comment](../includes/presentation/modern-comment-description.md)] + +## How the Sample Code Works + +The sample code opens the presentation document in the using statement. Then it gets or creates the CommentAuthorsPart, and verifies that there is an existing comment authors part. If there is not, it adds one. + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/reply_to_comment/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/reply_to_comment/vb/Program.vb#snippet1)] +*** + +Next the code determines if the author that is passed in is on the list of existing authors; if so, it assigns the existing author ID. If not, it adds a new author to the list of authors and assigns an author ID and the parameter values. + +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/reply_to_comment/cs/Program.cs#snippet2)] + +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/reply_to_comment/vb/Program.vb#snippet2)] +*** + +Next the code gets the first slide part and verifies that it exists, then checks if there are any comment parts associated with the slide. + +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/presentation/reply_to_comment/cs/Program.cs#snippet3)] + +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/presentation/reply_to_comment/vb/Program.vb#snippet3)] +*** + +The code then retrieves the comment list and then iterates through each comment in the comment list, displays the comment text to the user, and prompts whether they want to reply to each comment. + +### [C#](#tab/cs-5) +[!code-csharp[](../../samples/presentation/reply_to_comment/cs/Program.cs#snippet4)] + +### [Visual Basic](#tab/vb-5) +[!code-vb[](../../samples/presentation/reply_to_comment/vb/Program.vb#snippet4)] +*** + +When the user chooses to reply to a comment, the code prompts for the reply text, then gets or creates a `CommentReplyList` for the comment and adds the new reply with the appropriate author information and timestamp. + +### [C#](#tab/cs-6) +[!code-csharp[](../../samples/presentation/reply_to_comment/cs/Program.cs#snippet5)] + +### [Visual Basic](#tab/vb-6) +[!code-vb[](../../samples/presentation/reply_to_comment/vb/Program.vb#snippet5)] +*** + +## Sample Code + +Following is the complete code sample showing how to reply to existing comments +in a presentation slide with modern PowerPoint comments. + +### [C#](#tab/cs) +[!code-csharp[](../../samples/presentation/reply_to_comment/cs/Program.cs#snippet0)] + +### [Visual Basic](#tab/vb) +[!code-vb[](../../samples/presentation/reply_to_comment/vb/Program.vb#snippet0)] +*** + +## See also + + +- [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) diff --git a/docs/presentation/how-to-retrieve-the-number-of-slides-in-a-presentation-document.md b/docs/presentation/how-to-retrieve-the-number-of-slides-in-a-presentation-document.md index 1808f843..04333fb2 100644 --- a/docs/presentation/how-to-retrieve-the-number-of-slides-in-a-presentation-document.md +++ b/docs/presentation/how-to-retrieve-the-number-of-slides-in-a-presentation-document.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/2024 ms.localizationpriority: medium --- # Retrieve the number of slides in a presentation document @@ -21,7 +21,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to programmatically retrieve the number of slides in a presentation document, either including hidden slides or not, without loading the document into Microsoft PowerPoint. It contains an example -**RetrieveNumberOfSlides** method to illustrate +`RetrieveNumberOfSlides` method to illustrate this task. @@ -30,24 +30,18 @@ this task. ## RetrieveNumberOfSlides Method -You can use the **RetrieveNumberOfSlides** +You can use the `RetrieveNumberOfSlides` method to get the number of slides in a presentation document, -optionally including the hidden slides. The **RetrieveNumberOfSlides** method accepts two +optionally including the hidden slides. The `RetrieveNumberOfSlides` method accepts two parameters: a string that indicates the path of the file that you want to examine, and an optional Boolean value that indicates whether to include hidden slides in the count. ### [C#](#tab/cs-0) -```csharp - public static int RetrieveNumberOfSlides(string fileName, - bool includeHidden = true) -``` +[!code-csharp[](../../samples/presentation/retrieve_the_number_of_slides/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Function RetrieveNumberOfSlides(ByVal fileName As String, - Optional ByVal includeHidden As Boolean = True) As Integer -``` +[!code-vb[](../../samples/presentation/retrieve_the_number_of_slides/vb/Program.vb#snippet1)] *** @@ -60,118 +54,66 @@ second parameter value. To call the method, pass all the parameter values, as shown in the following code. ### [C#](#tab/cs-1) -```csharp - // Retrieve the number of slides, excluding the hidden slides. - Console.WriteLine(RetrieveNumberOfSlides(DEMOPATH, false)); - // Retrieve the number of slides, including the hidden slides. - Console.WriteLine(RetrieveNumberOfSlides(DEMOPATH)); -``` +[!code-csharp[](../../samples/presentation/retrieve_the_number_of_slides/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - ' Retrieve the number of slides, excluding the hidden slides. - Console.WriteLine(RetrieveNumberOfSlides(DEMOPATH, False)) - ' Retrieve the number of slides, including the hidden slides. - Console.WriteLine(RetrieveNumberOfSlides(DEMOPATH)) -``` +[!code-vb[](../../samples/presentation/retrieve_the_number_of_slides/vb/Program.vb#snippet2)] *** + --------------------------------------------------------------------------------- ## How the Code Works -The code starts by creating an integer variable, **slidesCount**, to hold the number of slides. The code then opens the specified presentation by using the [PresentationDocument.Open](/dotnet/api/documentformat.openxml.packaging.presentationdocument.open) method and indicating that the document should be open for read-only access (the -final **false** parameter value). Given the open presentation, the code uses the [PresentationPart](/dotnet/api/documentformat.openxml.packaging.presentationdocument.presentationpart) property to navigate to the main presentation part, storing the reference in a variable named **presentationPart**. +The code starts by creating an integer variable, `slidesCount`, to hold the number of slides. The code then opens the specified presentation by using the method and indicating that the document should be open for read-only access (the +final `false` parameter value). Given the open presentation, the code uses the property to navigate to the main presentation part, storing the reference in a variable named `presentationPart`. -### [C#](#tab/cs-2) -```csharp - using (PresentationDocument doc = - PresentationDocument.Open(fileName, false)) - { - // Get the presentation part of the document. - PresentationPart presentationPart = doc.PresentationPart; - // Code removed here… - } - Return slidesCount; -``` +### [C#](#tab/cs) +[!code-csharp[](../../samples/presentation/retrieve_the_number_of_slides/cs/Program.cs#snippet3)] -### [Visual Basic](#tab/vb-2) -```vb - Using doc As PresentationDocument = - PresentationDocument.Open(fileName, False) - ' Get the presentation part of the document. - Dim presentationPart As PresentationPart = doc.PresentationPart - ' Code removed here… - End Using - Return slidesCount -``` +### [Visual Basic](#tab/vb) +[!code-vb[](../../samples/presentation/retrieve_the_number_of_slides/vb/Program.vb#snippet3)] *** + --------------------------------------------------------------------------------- ## Retrieving the Count of All Slides -If the presentation part reference is not null (and it will not be, for any valid presentation that loads correctly into PowerPoint), the code next calls the **Count** method on the value of the [SlideParts](/dotnet/api/documentformat.openxml.packaging.presentationpart.slideparts) property of the presentation part. If you requested all slides, including hidden slides, that is all there is to do. There is slightly more work to be done if you want to exclude hidden slides, as shown in the following code. - -### [C#](#tab/cs-3) -```csharp - if (includeHidden) - { - slidesCount = presentationPart.SlideParts.Count(); - } - else - { - // Code removed here… - } -``` - -### [Visual Basic](#tab/vb-3) -```vb - If includeHidden Then - slidesCount = presentationPart.SlideParts.Count() - Else - ' Code removed here… - End If -``` +If the presentation part reference is not null (and it will not be, for any valid presentation that loads correctly into PowerPoint), the code next calls the `Count` method on the value of the property of the presentation part. If you requested all slides, including hidden slides, that is all there is to do. There is slightly more work to be done if you want to exclude hidden slides, as shown in the following code. + +### [C#](#tab/cs) +[!code-csharp[](../../samples/presentation/retrieve_the_number_of_slides/cs/Program.cs#snippet4)] + +### [Visual Basic](#tab/vb) +[!code-vb[](../../samples/presentation/retrieve_the_number_of_slides/vb/Program.vb#snippet4)] *** + --------------------------------------------------------------------------------- ## Retrieving the Count of Visible Slides If you requested that the code should limit the return value to include only visible slides, the code must filter its collection of slides to -include only those slides that have a [Show](/dotnet/api/documentformat.openxml.presentation.slide.show) property that contains a value, and -the value is **true**. If the **Show** property is null, that also indicates that -the slide is visible. This is the most likely scenario—PowerPoint does +include only those slides that have a property that contains a value, and +the value is `true`. If the `Show` property is null, that also indicates that +the slide is visible. This is the most likely scenario. PowerPoint does not set the value of this property, in general, unless the slide is to -be hidden. The only way the **Show** property -would exist and have a value of **true** would +be hidden. The only way the `Show` property +would exist and have a value of `true` would be if you had hidden and then unhidden the slide. The following code -uses the [Where](/dotnet/api/system.linq.enumerable.where)** +uses the function with a lambda expression to do the work. -### [C#](#tab/cs-4) -```csharp - var slides = presentationPart.SlideParts.Where( - (s) => (s.Slide != null) && - ((s.Slide.Show == null) || (s.Slide.Show.HasValue && - s.Slide.Show.Value))); - slidesCount = slides.Count(); -``` - -### [Visual Basic](#tab/vb-4) -```vb - Dim slides = presentationPart.SlideParts. - Where(Function(s) (s.Slide IsNot Nothing) AndAlso - ((s.Slide.Show Is Nothing) OrElse - (s.Slide.Show.HasValue AndAlso - s.Slide.Show.Value))) - slidesCount = slides.Count() -``` +### [C#](#tab/cs) +[!code-csharp[](../../samples/presentation/retrieve_the_number_of_slides/cs/Program.cs#snippet5)] + +### [Visual Basic](#tab/vb) +[!code-vb[](../../samples/presentation/retrieve_the_number_of_slides/vb/Program.vb#snippet5)] *** @@ -179,14 +121,14 @@ function with a lambda expression to do the work. ## Sample Code -The following is the complete **RetrieveNumberOfSlides** code sample in C\# and +The following is the complete `RetrieveNumberOfSlides` code sample in C\# and Visual Basic. -### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/retrieve_the_number_of_slides/cs/Program.cs)] +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/retrieve_the_number_of_slides/cs/Program.cs#snippet0)] -### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/retrieve_the_number_of_slides/vb/Program.vb)] +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/retrieve_the_number_of_slides/vb/Program.vb#snippet0)] --------------------------------------------------------------------------------- diff --git a/docs/presentation/overview.md b/docs/presentation/overview.md index f2dbeb7e..6e33d779 100644 --- a/docs/presentation/overview.md +++ b/docs/presentation/overview.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 08/12/2025 ms.localizationpriority: high --- # Presentations @@ -20,55 +20,62 @@ This section provides how-to topics for working with presentation documents usin ## In this section -- [Structure of a PresentationML document](structure-of-a-presentationml-document.md) - -- [Add a comment to a slide in a presentation](how-to-add-a-comment-to-a-slide-in-a-presentation.md) +- [Structure of a PresentationML document](structure-of-a-presentationml-document.md) -- [Apply a theme to a presentation](how-to-apply-a-theme-to-a-presentation.md) -- [Change the fill color of a shape in a presentation](how-to-change-the-fill-color-of-a-shape-in-a-presentation.md) +- [Add an audio file to a slide in a presentation](how-to-add-an-audio-to-a-slide-in-a-presentation.md) -- [Create a presentation document by providing a file name](how-to-create-a-presentation-document-by-providing-a-file-name.md) +- [Add a comment to a slide in a presentation](how-to-add-a-comment-to-a-slide-in-a-presentation.md) -- [Delete all the comments by an author from all the slides in a presentation](how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentatio.md) +- [Reply to a comment in a presentation](how-to-reply-to-a-comment-in-a-presentation.md) -- [Delete a slide from a presentation](how-to-delete-a-slide-from-a-presentation.md) +- [Apply a theme to a presentation](how-to-apply-a-theme-to-a-presentation.md) -- [Get all the external hyperlinks in a presentation](how-to-get-all-the-external-hyperlinks-in-a-presentation.md) +- [Change the fill color of a shape in a presentation](how-to-change-the-fill-color-of-a-shape-in-a-presentation.md) -- [Get all the text in a slide in a presentation](how-to-get-all-the-text-in-a-slide-in-a-presentation.md) +- [Create a presentation document by providing a file name](how-to-create-a-presentation-document-by-providing-a-file-name.md) -- [Get all the text in all slides in a presentation](how-to-get-all-the-text-in-all-slides-in-a-presentation.md) +- [Delete all the comments by an author from all the slides in a presentation](how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentation.md) -- [Get the titles of all the slides in a presentation](how-to-get-the-titles-of-all-the-slides-in-a-presentation.md) +- [Delete a slide from a presentation](how-to-delete-a-slide-from-a-presentation.md) -- [Insert a new slide into a presentation](how-to-insert-a-new-slide-into-a-presentation.md) +- [Get all the external hyperlinks in a presentation](how-to-get-all-the-external-hyperlinks-in-a-presentation.md) -- [Move a slide to a new position in a presentation](how-to-move-a-slide-to-a-new-position-in-a-presentation.md) +- [Get all the text in a slide in a presentation](how-to-get-all-the-text-in-a-slide-in-a-presentation.md) -- [Move a paragraph from one presentation to another](how-to-move-a-paragraph-from-one-presentation-to-another.md) +- [Get all the text in all slides in a presentation](how-to-get-all-the-text-in-all-slides-in-a-presentation.md) -- [Open a presentation document for read-only access](how-to-open-a-presentation-document-for-read-only-access.md) +- [Get the titles of all the slides in a presentation](how-to-get-the-titles-of-all-the-slides-in-a-presentation.md) -- [Retrieve the number of slides in a presentation document](how-to-retrieve-the-number-of-slides-in-a-presentation-document.md) +- [Insert a new slide into a presentation](how-to-insert-a-new-slide-into-a-presentation.md) -- [Working with animation](working-with-animation.md) +- [Move a slide to a new position in a presentation](how-to-move-a-slide-to-a-new-position-in-a-presentation.md) -- [Working with comments](working-with-comments.md) +- [Move a paragraph from one presentation to another](how-to-move-a-paragraph-from-one-presentation-to-another.md) -- [Working with handout master slides](working-with-handout-master-slides.md) +- [Open a presentation document for read-only access](how-to-open-a-presentation-document-for-read-only-access.md) -- [Working with notes slides](working-with-notes-slides.md) +- [Retrieve the number of slides in a presentation document](how-to-retrieve-the-number-of-slides-in-a-presentation-document.md) -- [Working with presentations](working-with-presentations.md) +- [Add a transition to a slides in a presentation](how-to-add-transitions-between-slides-in-a-presentation.md) -- [Working with presentation slides](working-with-presentation-slides.md) +- [Working with animation](working-with-animation.md) -- [Working with slide layouts](working-with-slide-layouts.md) +- [Working with comments](working-with-comments.md) -- [Working with slide masters](working-with-slide-masters.md) +- [Working with handout master slides](working-with-handout-master-slides.md) +- [Working with notes slides](working-with-notes-slides.md) -## Related sections +- [Working with presentations](working-with-presentations.md) -- [Getting started with the Open XML SDK for Office](../getting-started.md) +- [Working with presentation slides](working-with-presentation-slides.md) + +- [Working with slide layouts](working-with-slide-layouts.md) + +- [Working with slide masters](working-with-slide-masters.md) + + +## Related sections + +- [Getting started with the Open XML SDK for Office](../getting-started.md) diff --git a/docs/presentation/structure-of-a-presentationml-document.md b/docs/presentation/structure-of-a-presentationml-document.md index 760a57a8..afff4570 100644 --- a/docs/presentation/structure-of-a-presentationml-document.md +++ b/docs/presentation/structure-of-a-presentationml-document.md @@ -9,15 +9,15 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 09/16/2021 +ms.date: 11/26/2024 ms.localizationpriority: high --- # Structure of a PresentationML document -The document structure of a PresentationML document consists of the \ (Presentation) element that contains \ (Slide Master), \ (Slide Layout), \ (Slide), and \ (Theme) elements that reference the slides in the presentation. (The Theme element is the root element of the DrawingMLTheme part.) These elements are the minimum elements required for a valid presentation document. +The document structure of a PresentationML document consists of the `` (Presentation) element that contains `` (Slide Master), `` (Slide Layout), `` (Slide), and `` (Theme) elements that reference the slides in the presentation. (The Theme element is the root element of the DrawingMLTheme part.) These elements are the minimum elements required for a valid presentation document. -In addition, a presentation document might contain \ (Notes Slide), \ (Handout Master), \ (Shape), \ (Picture), \ (Table), and other slide-related elements. (Table elements are defined in the DrawingML schema.) +In addition, a presentation document might contain `` (Notes Slide), `` (Handout Master), `` (Shape), `` (Picture), `` (Table), and other slide-related elements. (Table elements are defined in the DrawingML schema.) Other features that a PresentationML document can contain include the following: animation, audio, video, and transitions between slides. @@ -25,31 +25,31 @@ A PresentationML document is not stored as one large body in a single part. Inst ## Important Presentation Parts -Using the Open XML SDK, you can create document structure and content that uses strongly-typed classes that correspond to PresentationML elements. You can find these classes in the **[DocumentFormat.OpenXml.Presentation](/dotnet/api/documentformat.openxml.presentation)** namespace. The following table lists the class names of the classes that correspond to some of the important presentation elements. +Using the Open XML SDK, you can create document structure and content that uses strongly-typed classes that correspond to PresentationML elements. You can find these classes in the namespace. The following table lists the class names of the classes that correspond to some of the important presentation elements. | **Package Part** | **Top Level PresentationML Element** | **Open XML SDK Class** | **Description**\* | |-------------------------|--------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| Presentation | \ | [Presentation](/dotnet/api/documentformat.openxml.presentation.presentation) | The root element for the Presentation part. This element specifies within it fundamental presentation-wide properties. | -| Presentation Properties | \ | [PresentationProperties](/dotnet/api/documentformat.openxml.presentation.presentationproperties) | The root element for the Presentation Properties part. This element functions as a parent element within which additional presentation-wide document properties are contained. | -| Slide Master | \ | [SlideMaster](/dotnet/api/documentformat.openxml.presentation.slidemaster) | The root element for the Slide Master part. Within a slide master slide are contained all elements that describe the objects and their corresponding formatting for within a presentation slide. For more information, see [Working with slide masters](working-with-slide-masters.md). | -| Slide Layout | \ | [SlideLayout](/dotnet/api/documentformat.openxml.presentation.slidelayout) | The root element for the Slide Layout part. This element specifies the relationship information for each slide layout that is used within the slide master. For more information, see [Working with slide layouts](working-with-slide-layouts.md). | -| Theme | \ | [Theme](/dotnet/api/documentformat.openxml.drawing.theme) | The root element for the Theme part. This element holds all the different formatting options available to a document through a theme and defines the overall look and feel of the document when themed objects are used within the document. | -| Slide | \ | [Slide](/dotnet/api/documentformat.openxml.presentation.slide) | The root element for the Slide part. This element specifies a slide within a slide list. For more information, see [Working with presentation slides](working-with-presentation-slides.md). | -| Notes Master | \ | [NotesMaster](/dotnet/api/documentformat.openxml.presentation.notesmaster) | The root element for the Notes Master part. Within a notes master slide are contained all elements that describe the objects and their corresponding formatting for within a notes slide. | -| Notes Slide | \ | [NotesSlide](/dotnet/api/documentformat.openxml.presentation.notesslide) | The root element of the Notes Slide part. This element specifies the existence of a notes slide along with its corresponding data. Contained within a notes slide are all the common slide elements along with addition properties that are specific to the notes element. For more information, see [Working with notes slides](working-with-notes-slides.md). | -| Handout Master | \ | [HandoutMaster](/dotnet/api/documentformat.openxml.presentation.handoutmaster) | The root element of the Handout Master part. Within a handout master slide are contained all elements that describe the objects and their corresponding formatting for within a handout slide. For more information, see [Working with handout master slides](working-with-handout-master-slides.md). | -| Comments | \ | [CommentList](/dotnet/api/documentformat.openxml.presentation.commentlist) | The root element of the Comments part. This element specifies a list of comments for a particular slide. For more information, see [Working with comments](working-with-comments.md). | -| Comments Author | \ | [CommentAuthorList](/dotnet/api/documentformat.openxml.presentation.commentauthorlist) | The root element of the Comments Author part. This element specifies a list of authors with comments in the current document. For more information, see [Working with comments](working-with-comments.md). | - -*Descriptions adapted from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification, © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +| Presentation | `` | | The root element for the Presentation part. This element specifies within it fundamental presentation-wide properties. | +| Presentation Properties | `` | | The root element for the Presentation Properties part. This element functions as a parent element within which additional presentation-wide document properties are contained. | +| Slide Master | `` | | The root element for the Slide Master part. Within a slide master slide are contained all elements that describe the objects and their corresponding formatting for within a presentation slide. For more information, see [Working with slide masters](working-with-slide-masters.md). | +| Slide Layout | `` | | The root element for the Slide Layout part. This element specifies the relationship information for each slide layout that is used within the slide master. For more information, see [Working with slide layouts](working-with-slide-layouts.md). | +| Theme | `` | | The root element for the Theme part. This element holds all the different formatting options available to a document through a theme and defines the overall look and feel of the document when themed objects are used within the document. | +| Slide | `` | | The root element for the Slide part. This element specifies a slide within a slide list. For more information, see [Working with presentation slides](working-with-presentation-slides.md). | +| Notes Master | `` | | The root element for the Notes Master part. Within a notes master slide are contained all elements that describe the objects and their corresponding formatting for within a notes slide. | +| Notes Slide | `` | | The root element of the Notes Slide part. This element specifies the existence of a notes slide along with its corresponding data. Contained within a notes slide are all the common slide elements along with addition properties that are specific to the notes element. For more information, see [Working with notes slides](working-with-notes-slides.md). | +| Handout Master | `` | | The root element of the Handout Master part. Within a handout master slide are contained all elements that describe the objects and their corresponding formatting for within a handout slide. For more information, see [Working with handout master slides](working-with-handout-master-slides.md). | +| Comments | `` | | The root element of the Comments part. This element specifies a list of comments for a particular slide. For more information, see [Working with comments](working-with-comments.md). | +| Comments Author | `` | | The root element of the Comments Author part. This element specifies a list of authors with comments in the current document. For more information, see [Working with comments](working-with-comments.md). | + +*Descriptions adapted from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification, © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Presentation Part -A PresentationML package's main part starts with a \ root element. That element contains a presentation, which, in turn, refers to a slide list, a slide master list, a notes master list, and a handout master list. The slide list refers to all of the slides in the presentation. The slide master list refers to the entire set of slide masters used in the presentation. The notes master contains information about the formatting of notes pages. The handout master describes how a handout looks. (A handout is a printed set of slides that can be handed out to an audience for future reference.) +A PresentationML package's main part starts with a `` root element. That element contains a presentation, which, in turn, refers to a slide list, a slide master list, a notes master list, and a handout master list. The slide list refers to all of the slides in the presentation. The slide master list refers to the entire set of slide masters used in the presentation. The notes master contains information about the formatting of notes pages. The handout master describes how a handout looks. (A handout is a printed set of slides that can be handed out to an audience for future reference.) ### Presentation Properties Part -The root element of the Presentation Properties part is the \ element. +The root element of the Presentation Properties part is the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Presentation Properties part as follows: @@ -81,11 +81,11 @@ A Presentation Properties part shall be located within the package containing th A Presentation Properties part shall not have implicit or explicit relationships to any other part defined by ISO/IEC 29500. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Slide Master Part -The root element of the Slide Master part is the \ element. +The root element of the Slide Master part is the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Slide Master part as follows: @@ -141,11 +141,11 @@ following parts defined by ISO/IEC 29500: A Slide Master part shall not have implicit or explicit relationships to any other part defined by ISO/IEC 29500. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Slide Layout Part -The root element of the Slide Layout part is the \ element. +The root element of the Slide Layout part is the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Slide Layout part as follows: @@ -153,7 +153,7 @@ An instance of this part type contains the definition for a slide layout templat A package shall contain one or more Slide Layout parts, and each of those parts shall be the target of an explicit relationship in the Slide Master (§13.3.10) part, as well as an implicit relationship from each of the Slide (§13.3.8) parts associated with this slide layout. -Example: The following Slide Master part-relationship item contains relationships to several Slide Layout parts, which are stored in the ZIP items ../slideLayouts/slideLayoutN.xml: +Example: The following Slide Master part-relationship item contains relationships to several Slide Layout parts, which are stored in the ZIP items `../slideLayouts/slideLayoutN.xml`: ```xml @@ -207,11 +207,11 @@ A Slide Layout part is permitted to have explicit relationships to the following A Slide Layout part shall not have implicit or explicit relationships to any other part defined by ISO/IEC 29500. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Slide Part -The root element of the Slide part is the \ element. +The root element of the Slide part is the `` element. As well as text and graphics, each slide can contain comments and notes, can have a layout, and can be part of one or more custom presentations. A comment is an annotation intended for the person maintaining the presentation slide deck. A note is a reminder or piece of text intended for the presenter or the audience. @@ -221,7 +221,7 @@ A Slide part contains the contents of a single slide. A package shall contain one Slide part per slide, and each of those parts shall be the target of an explicit relationship from the Presentation (§13.3.6) part. -Example: Consider a PresentationML document having two slides. The corresponding Presentation part relationship item contains two relationships to Slide parts, which are stored in the ZIP items slides/slide1.xml and slides/slide2.xml: +Example: Consider a PresentationML document having two slides. The corresponding Presentation part relationship item contains two relationships to Slide parts, which are stored in the ZIP items `slides/slide1.xml and slides/slide2.xml`: ```xml @@ -232,9 +232,9 @@ Example: Consider a PresentationML document having two slides. The corresponding ``` -The root element for a part of this content type shall be sld. +The root element for a part of this content type shall be ``. -Example: slides/slide1.xml contains: +Example: `slides/slide1.xml` contains: ```xml @@ -285,19 +285,19 @@ A Slide part is permitted to have explicit relationships to the following parts A Slide part shall not have implicit or explicit relationships to any other part defined by ISO/IEC 29500. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Theme Part -The root element of the Theme part is the \ element. +The root element of the Theme part is the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML DrawingML Theme part as follows: -An instance of this part type contains information about a document's theme, which is a combination of color scheme, font scheme, and format scheme (the latter also being referred to as effects). For a WordprocessingML document, the choice of theme affects the color and style of headings, among other things. For a SpreadsheetML document, the choice of theme affects the color and style of cell contents and charts, among other things. For a PresentationML document, the choice of theme affects the formatting of slides, handouts, and notes via the associated master, among other things. +An instance of this part type contains information about a document's theme, which is a combination of color scheme, font scheme, and format scheme (the latter also being referred to as effects). For a WordprocessingML document, the choice of theme affects the color and style of headings, among other things. For a SpreadsheetML document, the choice of theme affects the color and style of cell contents and charts, among other things. For a PresentationML document, the choice of theme affects the formatting of slides, handouts, and notes via the associated master, in addition to other things. A WordprocessingML or SpreadsheetML package shall contain zero or one Theme part, which shall be the target of an implicit relationship in a Main Document (§11.3.10) or Workbook (§12.3.23) part. A PresentationML package shall contain zero or one Theme part per Handout Master (§13.3.3), Notes Master (§13.3.4), Slide Master (§13.3.10) or Presentation (§13.3.6) part via an implicit relationship. -Example: The following WordprocessingML Main Document part-relationship item contains a relationship to the Theme part, which is stored in the ZIP item theme/theme1.xml: +Example: The following WordprocessingML Main Document part-relationship item contains a relationship to the Theme part, which is stored in the ZIP item `theme/theme1.xml`: ```xml @@ -335,11 +335,11 @@ A Theme part is permitted to contain explicit relationships to the following par A Theme part shall not have any implicit or explicit relationships to other parts defined by ISO/IEC 29500. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Notes Master Part -The root element of the Notes Master part is the \ element. +The root element of the Notes Master part is the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Notes Master part as follows: @@ -393,11 +393,11 @@ A Notes Master part is permitted to have explicit relationships to the following The Notes Master part shall not have implicit or explicit relationships to any other part defined by ISO/IEC 29500. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Notes Slide Part -The root element of the Notes Slide part is the \ element. +The root element of the Notes Slide part is the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Notes Slide part as follows: @@ -405,7 +405,7 @@ An instance of this part type contains the notes for a single slide. A package shall contain one Notes Slide part for each slide that contains notes. If they exist, those parts shall each be the target of an implicit relationship from the Slide (§13.3.8) part. -Example: The following Slide part-relationship item contains a relationship to a Notes Slide part, which is stored in the ZIP item ../notesSlides/notesSlide1.xml: +Example: The following Slide part-relationship item contains a relationship to a Notes Slide part, which is stored in the ZIP item `../notesSlides/notesSlide1.xml`: ```xml @@ -454,11 +454,11 @@ A Notes Slide part is permitted to have explicit relationships to the following The Notes Slide part shall not have implicit or explicit relationships to any other part defined by ISO/IEC 29500. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Handout Master Part -The root element of the Handout Master part is the \ element. +The root element of the Handout Master part is the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Handout Master part as follows: @@ -467,7 +467,7 @@ An instance of this part type contains the look, position, and size of the slide A package shall contain at most one Handout Master part, and it shall be the target of an explicit relationship from the Presentation (§13.3.6) part. Example: The following Presentation part-relationship item contains a relationship to the Handout Master part, which is stored in the ZIP item -handoutMasters/handoutMaster1.xml: +`handoutMasters/handoutMaster1.xml`: ```xml @@ -513,11 +513,11 @@ A Handout Master part is permitted to have explicit relationships to the followi A Handout Master part shall not have implicit or explicit relationships to any other part defined by ISO/IEC 29500. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Comments Part -The root element of the Comments part is the \ element. +The root element of the Comments part is the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Comments part as follows: @@ -526,7 +526,7 @@ An instance of this part type contains the comments for a single slide. Each com A package shall contain one Comments part for each slide containing one or more comments, and each of those parts shall be the target of an implicit relationship from its corresponding Slide (§13.3.8) part. -Example: The following Slide part-relationship item contains a relationship to a Comments part, which is stored in the ZIP item ../comments/comment2.xml: +Example: The following Slide part-relationship item contains a relationship to a Comments part, which is stored in the ZIP item `../comments/comment2.xml`: ```xml @@ -536,7 +536,7 @@ Example: The following Slide part-relationship item contains a relationship to a ``` -The root element for a part of this content type shall be cmLst. +The root element for a part of this content type shall be ``. Example: The Comments part contains three comments, two created by one author, and one created by another, all at the dates and times shown. The index numbers are assigned on a per-author basis, starting at 1 for an author's first comment: @@ -561,11 +561,11 @@ A Comments part shall be located within the package containing the relationships A Comments part shall not have implicit or explicit relationships to any other part defined by ISO/IEC 29500. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Comments Author Part -The root element of the Comments Author part is the \ +The root element of the Comments Author part is the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML Comments Author part as follows: @@ -574,7 +574,7 @@ An instance of this part type contains information about each author who has add A package shall contain at most one Comment Authors part. If it exists, that part shall be the target of an implicit relationship from the Presentation (§13.3.6) part. -Example: The following Presentation part relationship item contains a relationship to the Comment Authors part, which is stored in the ZIP item commentAuthors.xml: +Example: The following Presentation part relationship item contains a relationship to the Comment Authors part, which is stored in the ZIP item `commentAuthors.xml`: ```xml @@ -583,7 +583,7 @@ Example: The following Presentation part relationship item contains a relationsh ``` -The root element for a part of this content type shall be cmAuthorLst. +The root element for a part of this content type shall be ``. Example: Two people have authored comments in this document: Mary Smith and Peter Jones. Her initials are "mas", her author-ID is 0, and her comments' display color index is 0. Since Mary's last-comment-index-used value is 3, the next comment-index to be used for her is 4. His initials are "pjj", his author-ID is 1, and his comments' display color index is 1. Since Peter's last-comment-index-used value is 1, the next comment-index to be used for him is 2: @@ -600,7 +600,7 @@ A Comment Authors part shall be located within the package containing the relati A Comment Authors part shall not have implicit or explicit relationships to any other part defined by ISO/IEC 29500. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ## The Structure of a Minimum Presentation File @@ -612,15 +612,15 @@ The packaging structure of a presentation document contains several references b ## Generated PresentationML XML Code -After you run the Open XML SDK code to generate a presentation, you can explore the contents of the .zip package to view the PresentationML XML code. To view the .zip package, rename the extension on the minimum presentation from **.pptx** to **.zip**. Inside the .zip package, there are several parts that make up the minimum presentation. +After you run the Open XML SDK code to generate a presentation, you can explore the contents of the .zip package to view the PresentationML XML code. To view the .zip package, rename the extension on the minimum presentation from `.pptx` to `.zip`. Inside the .zip package, there are several parts that make up the minimum presentation. -Figure 1 shows the structure under the **ppt** folder of the .zip package for a minimum presentation that contains a single slide. +Figure 1 shows the structure under the `ppt` folder of the zip package for a minimum presentation that contains a single slide. Figure 1. Minimum presentation folder structure ![Minimum presentation folder structure](../media/odc_oxml_ppt_documentstructure_fig01.jpg) -The presentation.xml file contains \ (Slide) elements that reference the slides in the presentation. Each slide is associated to the presentation by means of a slide ID and a relationship ID. The **slideID** is the identifier (ID) used within the package to identify a slide and must be unique within the presentation. The **id** attribute is the relationship ID that identifies the slide part definition associated with a slide. For more information about the slide part, see [Working with presentation slides](working-with-presentation-slides.md). +The presentation.xml file contains `` (Slide) elements that reference the slides in the presentation. Each slide is associated to the presentation by means of a slide ID and a relationship ID. The `slideID` is the identifier (ID) used within the package to identify a slide and must be unique within the presentation. The `id` attribute is the relationship ID that identifies the slide part definition associated with a slide. For more information about the slide part, see [Working with presentation slides](working-with-presentation-slides.md). The following XML code is the PresentationML that represents the presentation part of a presentation document that contains a single slide. This code is generated when you run the Open XML SDK code to create a minimum presentation. @@ -710,7 +710,7 @@ The following XML code is the PresentationML that represents the slide part of t ## Typical Presentation Scenario -A typical presentation does not have a minimum configuration. A typical presentation might contain several slides, each of which references slide layouts and slide masters, and which might contain comments. In addition, a presentation might contain handouts and notes slides, each of which is represented by separate parts. These additional parts are contained within the .zip package of the presentation document. +A typical presentation does not have a minimum configuration. A typical presentation might contain several slides, each of which references slide layouts and slide masters, and which might contain comments. In addition, a presentation might contain handouts and notes slides, each of which is represented by separate parts. These additional parts are contained within the zip package of the presentation document. Figure 2 shows most of the elements that you would find in a typical presentation. diff --git a/docs/presentation/working-with-animation.md b/docs/presentation/working-with-animation.md index 8f9d298c..18ce5c48 100644 --- a/docs/presentation/working-with-animation.md +++ b/docs/presentation/working-with-animation.md @@ -11,19 +11,19 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 11/26/2024 ms.localizationpriority: medium --- # Working with animation -This topic discusses the Open XML SDK for Office **Animate** class and how it relates to the Open XML File Format PresentationML schema. For more information about the overall structure of the parts and elements that make up a PresentationML document, see [Structure of a PresentationML Document](structure-of-a-presentationml-document.md). +This topic discusses the Open XML SDK for Office `Animate` class and how it relates to the Open XML File Format PresentationML schema. For more information about the overall structure of the parts and elements that make up a PresentationML document, see [Structure of a PresentationML Document](structure-of-a-presentationml-document.md). ## Animation in PresentationML The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Animation section of the Open XML PresentationML framework as follows: -The Animation section of the PresentationML framework stores the movement and related information of objects. This schema is loosely based on the syntax and concepts from the Synchronized Multimedia Integration Language (SMIL), a W3C Recommendation for describing multimedia presentations using XML. The schema describes all the animations effects that reside on a slide and also the animation that occurs when going from slide to slide (slide transition). Animations on a slide are inherently time-based and consist of an animation effects on an object or text. Slide transitions however do not follow this concept and always appear before any animation on a slide. All elements described in this schema are contained within the slide XML file. More specifically they are in the \ and the \ element as shown below: +The Animation section of the PresentationML framework stores the movement and related information of objects. This schema is loosely based on the syntax and concepts from the Synchronized Multimedia Integration Language (SMIL), a W3C Recommendation for describing multimedia presentations using XML. The schema describes all the animations effects that reside on a slide and also the animation that occurs when going from slide to slide (slide transition). Animations on a slide are inherently time-based and consist of an animation effects on an object or text. Slide transitions however do not follow this concept and always appear before any animation on a slide. All elements described in this schema are contained within the slide XML file. More specifically they are in the `` and the `` element as shown below: ```xml @@ -34,9 +34,9 @@ The Animation section of the PresentationML framework stores the movement and re ``` -Animation consists of several behaviors, the most basic of which is the Animate behavior, represented by the \ element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML \ element used to represent basic animation behavior in a PresentationML document as follows: +Animation consists of several behaviors, the most basic of which is the Animate behavior, represented by the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML `` element used to represent basic animation behavior in a PresentationML document as follows: -This element is a generic animation element that requires little or no semantic understanding of the attribute being animated. It can animate text within a shape or even the shape itself.[Example: Consider trying to emphasize text within a shape by changing the size of its font by 150%. The \ element should be used as follows: +This element is a generic animation element that requires little or no semantic understanding of the attribute being animated. It can animate text within a shape or even the shape itself.[Example: Consider trying to emphasize text within a shape by changing the size of its font by 150%. The `` element should be used as follows: ```xml @@ -56,14 +56,14 @@ This element is a generic animation element that requires little or no semantic ``` -The following table lists the child elements of the \ element used when working with animation and the Open XML SDK classes that correspond to them. +The following table lists the child elements of the `` element used when working with animation and the Open XML SDK classes that correspond to them. | **PresentationML Element** | **Open XML SDK Class** | |:---------------------------|:----------------------------| -| \ | CommonBehavior | -| \ | TimeAnimateValueList | +| `` | | +| `` | | -The following table from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the attributes of the \ element. +The following table from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the attributes of the `` element. | **Attributes** | **Description** | |:---------------|:-----------------------------------------------------------------| @@ -75,18 +75,18 @@ The following table from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29 ## Open XML SDK Animate Class -The OXML SDK **Animate** class represents the \ element defined in the Open XML File Format schema for PresentationML documents. Use the **Animate** -class to manipulate individual \ elements in a PresentationML document. +The OXML SDK `Animate` class represents the `` element defined in the Open XML File Format schema for PresentationML documents. Use the `Animate` +class to manipulate individual `` elements in a PresentationML document. -Classes that represent child elements of the \ element and that are therefore commonly associated with the **Animate** class are shown in the following list. +Classes that represent child elements of the `` element and that are therefore commonly associated with the `Animate` class are shown in the following list. ### CommonBehavior Class -The **CommonBehavior** class corresponds to the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \element: +The `CommonBehavior` class corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the ``element: This element describes the common behaviors of animations. -Consider trying to emphasize text within a shape by changing the size of its font. The \ element should be used as follows: +Consider trying to emphasize text within a shape by changing the size of its font. The `` element should be used as follows: ```xml @@ -108,11 +108,11 @@ Consider trying to emphasize text within a shape by changing the size of its fon ### TimeAnimateValueList Class -The **TimeAnimateValueList** class corresponds to the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: +The `TimeAnimateValueList` class corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `` element: This element specifies a list of time animated value elements. -Example: Consider a shape with a "fly-in" animation. The \ element should be used as follows: +Example: Consider a shape with a "fly-in" animation. The `` element should be used as follows: ```xml @@ -134,7 +134,7 @@ Example: Consider a shape with a "fly-in" animation. The \ element should ## Working with the Animate Class -The **Animate** class, which represents the \ element, is therefore also associated with other classes that represent the child elements of the \ element, including the **CommonBehavior** class, which describes common animation behaviors, and the **TimeAnimateValueList** class, which specifies a list of time-animated value elements, as shown in the previous XML code. Other classes associated with the **Animate** class are the **Timing** class, which specifies timing information for all the animations on the slide, and the **TargetElement** class, which specifies the target child elements to which the animation effects are applied. +The `Animate` class, which represents the `` element, is therefore also associated with other classes that represent the child elements of the `` element, including the `CommonBehavior` class, which describes common animation behaviors, and the `TimeAnimateValueList` class, which specifies a list of time-animated value elements, as shown in the previous XML code. Other classes associated with the `Animate` class are the class, which specifies timing information for all the animations on the slide, and the class, which specifies the target child elements to which the animation effects are applied. ## See also diff --git a/docs/presentation/working-with-comments.md b/docs/presentation/working-with-comments.md index c436fcb2..9b8b0409 100644 --- a/docs/presentation/working-with-comments.md +++ b/docs/presentation/working-with-comments.md @@ -11,14 +11,13 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 11/26/2024 ms.localizationpriority: medium --- # Working with comments -This topic discusses the Open XML SDK for Office [Comment](/dotnet/api/documentformat.openxml.presentation.comment) class and how it relates to the -Open XML File Format PresentationML schema. For more information about the overall structure of the parts and elements that make up a PresentationML document, see [Structure of a PresentationML -Document](structure-of-a-presentationml-document.md). +This topic discusses the Open XML SDK for Office class and how it relates to the +Open XML File Format PresentationML schema. For more information about the overall structure of the parts and elements that make up a PresentationML document, see [Structure of a PresentationML Document](structure-of-a-presentationml-document.md). ## Comments in PresentationML @@ -33,7 +32,7 @@ presentation, but do not appear when a slide show is given. The displaying application decides when to display comments and determines their visual appearance. -The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML \ element used to represent comments in a PresentationML document as follows: +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML `` element used to represent comments in a PresentationML document as follows: This element specifies a single comment attached to a slide. It contains the text of the comment, its position on the slide, and attributes @@ -48,46 +47,46 @@ Example: ``` -The following table lists the child elements of the \ element used when working with comments and the Open XML SDK classes that correspond to them. +The following table lists the child elements of the `` element used when working with comments and the Open XML SDK classes that correspond to them. | **PresentationML Element** | **Open XML SDK Class** | |----------------------------|------------------------------------------------------------------------------------------------------------------------------------------| -| \ | [ExtensionListWithModification](/dotnet/api/documentformat.openxml.presentation.extensionlistwithmodification) | -| \ | [Position](/dotnet/api/documentformat.openxml.presentation.position) | -| \ | [Text](/dotnet/api/documentformat.openxml.presentation.text) | +| `` | | +| `` | | +| `` | | The following table from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the attributes of the \ element. +specification describes the attributes of the `` element. | **Attributes** | **Description** | |----------------|--------------------| -| authorId | This attribute specifies the author of the comment.It refers to the ID of an author in the comment author list for the document.
The possible values for this attribute are defined by the W3C XML Schema **unsignedInt** datatype. | -| dt | This attribute specifies the date and time this comment was last modified.
The possible values for this attribute are defined by the W3C XML Schema **datetime** datatype. | +| authorId | This attribute specifies the author of the comment.It refers to the ID of an author in the comment author list for the document.
The possible values for this attribute are defined by the W3C XML Schema `unsignedInt` datatype. | +| dt | This attribute specifies the date and time this comment was last modified.
The possible values for this attribute are defined by the W3C XML Schema `datetime` datatype. | | idx | This attribute specifies an identifier for this comment that is unique within a list of all comments by this author in this document. An author's first comment in a document has index 1.
Note: Because the index is unique only for the comment author, a document can contain multiple comments with the same index created by different authors.
The possible values for this attribute are defined by the ST_Index simple type (§19.7.3). | ## Open XML SDK Comment Class -The OXML SDK **Comment** class represents the \ element defined in the Open XML File Format schema for PresentationML documents. Use the **Comment** -class to manipulate individual \ elements in a PresentationML document. +The OXML SDK `Comment` class represents the `` element defined in the Open XML File Format schema for PresentationML documents. Use the `Comment` +class to manipulate individual `` elements in a PresentationML document. -Classes that represent child elements of the \ element and that are -therefore commonly associated with the **Comment** class are shown in the following list. +Classes that represent child elements of the `` element and that are +therefore commonly associated with the `Comment` class are shown in the following list. ### ExtensionListWithModification Class -The **ExtensionListWithModification** class corresponds to the \element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `ExtensionListWithModification` class corresponds to the ``element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: -This element specifies the extension list with modification ability within which all future extensions of element type \ are defined. The extension list along with corresponding future extensions is used to extend the storage capabilities of the PresentationML framework. This allows for various new kinds of data to be stored natively within the framework. +This element specifies the extension list with modification ability within which all future extensions of element type `` are defined. The extension list along with corresponding future extensions is used to extend the storage capabilities of the PresentationML framework. This allows for various new kinds of data to be stored natively within the framework. > [!NOTE] -> Using this extLst element allows the generating application to store whether this extension property has been modified. end note +> Using this `extLst` element allows the generating application to store whether this extension property has been modified. end note ### Position Class -The **Position** class corresponds to the -\element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `Position` class corresponds to the +``element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: This element specifies the positioning information for the placement of a comment on a slide surface. In LTR versions of the generating @@ -109,15 +108,15 @@ application chooses to display comments. end note] ### Text class -The **Text** class corresponds to the -\element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `Text` class corresponds to the +`` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: This element specifies the content of a comment. This is the text with which the author has annotated the slide. The possible values for this element are defined by the W3C XML Schema -**string** datatype. +`string` datatype. ## Working with the Comment Class @@ -131,111 +130,29 @@ displaying application decides when to display comments and determines their visual appearance. As shown in the Open XML SDK code sample that follows, every instance of -the **Comment** class is associated with an -instance of the [SlideCommentsPart](/dotnet/api/documentformat.openxml.packaging.slidecommentspart) class, which represents a +the `Comment` class is associated with an +instance of the class, which represents a slide comments part, one of the parts of a PresentationML presentation file package, and a part that is required for each slide in a -presentation file that contains comments. Each **Comment** class instance is also associated with an -instance of the [CommentAuthor](/dotnet/api/documentformat.openxml.presentation.commentauthor) class, which is in turn +presentation file that contains comments. Each `Comment` class instance is also associated with an +instance of the class, which is in turn associated with a similarly named presentation part, represented by the -[CommentAuthorsPart](/dotnet/api/documentformat.openxml.packaging.commentauthorspart) class. Comment authors + class. Comment authors for a presentation are specified in a comment author list, represented -by the [CommentAuthorList](/dotnet/api/documentformat.openxml.presentation.commentauthorlist) class, while comments for +by the class, while comments for each slide are listed in a comments list for that slide, represented by -the [CommentList](/dotnet/api/documentformat.openxml.presentation.commentlist) class. +the class. -The **Comment** class, which represents the \ element, is therefore also associated with other classes that represent the child elements of the \ element. Among these classes, as shown in the following code sample, are the **Position** class, which specifies the position of the comment relative to the slide, and the **Text** class, which specifies the text content of the comment. +The `Comment` class, which represents the `` element, is therefore also associated with other classes that represent the child elements of the `` element. Among these classes, as shown in the following code sample, are the `Position` class, which specifies the position of the comment relative to the slide, and the `Text` class, which specifies the text content of the comment. ## Open XML SDK Code Example -The following code segment from the article [How to: Add a comment to a slide in a presentation](how-to-add-a-comment-to-a-slide-in-a-presentation.md) adds a new comments part to an existing slide in a presentation (if the slide does not already contain comments) and creates an instance of an Open XML SDK **Comment** class in the slide comments part. It also adds a comment list to the comments part by creating an instance of the **CommentList** class, if one does not already exist; assigns an ID to the comment; and then adds a comment to the comment list by creating an instance of the **Comment** class, assigning the required attribute values. In addition, it creates instances of the **Position** and **Text** classes associated with the new **Comment** class instance. For the complete code sample, see the aforementioned article. +The following code segment from the article [How to: Add a comment to a slide in a presentation](how-to-add-a-comment-to-a-slide-in-a-presentation.md) adds a new comments part to an existing slide in a presentation (if the slide does not already contain comments) and creates an instance of an Open XML SDK `Comment` class in the slide comments part. It also adds a comment list to the comments part by creating an instance of the `CommentList` class, if one does not already exist; assigns an ID to the comment; and then adds a comment to the comment list by creating an instance of the `Comment` class, assigning the required attribute values. In addition, it creates instances of the `Position` and `Text` classes associated with the new `Comment` class instance. For the complete code sample, see the aforementioned article. ### [C#](#tab/cs) -```csharp -// Declare a comments part. -SlideCommentsPart commentsPart; - -// Verify that there is a comments part in the first slide part. -if (slidePart1.GetPartsOfType().Count() == 0) -{ - // If not, add a new comments part. - commentsPart = slidePart1.AddNewPart(); -} -else -{ - // Else, use the first comments part in the slide part. - commentsPart = slidePart1.GetPartsOfType().First(); -} - -// If the comment list does not exist. -if (commentsPart.CommentList is null) -{ - // Add a new comments list. - commentsPart.CommentList = new CommentList(); -} - -// Get the new comment ID. -uint commentIdx = author.LastIndex is null ? 1 : author.LastIndex + 1; -author.LastIndex = commentIdx; - -// Add a new comment. -Comment comment = commentsPart.CommentList.AppendChild( - new Comment() - { - AuthorId = authorId, - Index = commentIdx, - DateTime = DateTime.Now - }); - -// Add the position child node to the comment element. -comment.Append( - new Position() { X = 100, Y = 200 }, - new Text() { Text = text }); -``` - +[!code-csharp[](../../samples/presentation/add_comment/cs/Program.cs#extsnippet1)] ### [Visual Basic](#tab/vb) -```vb -' Declare a comments part. -Dim commentsPart As SlideCommentsPart - -' Verify that there is a comments part in the first slide part. -If slidePart1.GetPartsOfType(Of SlideCommentsPart)().Count() = 0 Then - - ' If not, add a new comments part. - commentsPart = slidePart1.AddNewPart(Of SlideCommentsPart)() -Else - - ' Else, use the first comments part in the slide part. - commentsPart = -slidePart1.GetPartsOfType(Of SlideCommentsPart)().First() -End If - -' If the comment list does not exist. -If (commentsPart.CommentList Is Nothing) Then - - ' Add a new comments list. - commentsPart.CommentList = New CommentList() -End If - -' Get the new comment ID. -Dim commentIdx As UInteger -If author.LastIndex Is Nothing Then - commentIdx = 1 -Else - commentIdx = CType(author.LastIndex, UInteger) + 1 -End If - -author.LastIndex = commentIdx - -' Add a new comment. -Dim comment As Comment = -(commentsPart.CommentList.AppendChild(Of Comment)(New Comment() _ -With {.AuthorId = authorId, .Index = commentIdx, .DateTime = DateTime.Now})) - -' Add the position child node to the comment element. -comment.Append(New Position() With - {.X = 100, .Y = 200}, New Text() With {.Text = text}) -``` +[!code-vb[](../../samples/presentation/add_comment/vb/Program.vb#extsnippet1)] ## Generated PresentationML @@ -276,4 +193,4 @@ article. [About the Open XML SDK for Office](../about-the-open-xml-sdk.md) [How to: Create a Presentation by Providing a File Name](how-to-create-a-presentation-document-by-providing-a-file-name.md) [How to: Add a comment to a slide in a presentation](how-to-add-a-comment-to-a-slide-in-a-presentation.md) -[How to: Delete all the comments by an author from all the slides in a presentation](how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentatio.md) +[How to: Delete all the comments by an author from all the slides in a presentation](how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentation.md) diff --git a/docs/presentation/working-with-handout-master-slides.md b/docs/presentation/working-with-handout-master-slides.md index cf068982..e06ad630 100644 --- a/docs/presentation/working-with-handout-master-slides.md +++ b/docs/presentation/working-with-handout-master-slides.md @@ -11,15 +11,15 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/21/2025 ms.localizationpriority: medium --- # Working with handout master slides -This topic discusses the Open XML SDK for Office [HandoutMaster](/dotnet/api/documentformat.openxml.presentation.handoutmaster) class and how it relates to the Open XML File Format PresentationML schema. For more information about the overall structure of the parts and elements that make up a PresentationML document, see [Structure of a PresentationML document](structure-of-a-presentationml-document.md). +This topic discusses the Open XML SDK for Office class and how it relates to the Open XML File Format PresentationML schema. For more information about the overall structure of the parts and elements that make up a PresentationML document, see [Structure of a PresentationML document](structure-of-a-presentationml-document.md). ## Handout Master Slides in PresentationML -The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML \ +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML `` element used to represent a handout master slide in a PresentationML document as follows: This element specifies an instance of a handout master slide. Within a @@ -30,29 +30,29 @@ slide elements such as shapes and their attached text bodies. There are other properties within a handout master slide but cSld encompasses the majority of the intended purpose for a handoutMaster slide. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -The following table lists the child elements of the \ +The following table lists the child elements of the `` element used when working with handout master slides and the Open XML SDK classes that correspond to them. -| **PresentationML Element** | **Open XML SDK Class** | -|----------------------------|--------------------------------------------------------------------------------------------------------------------------------------------| -| \ | [ColorMap](/dotnet/api/documentformat.openxml.presentation.colormap) | -| \ | [CommonSlideData](/dotnet/api/documentformat.openxml.presentation.commonslidedata) | -| \ | [ExtensionListWithModification](/dotnet/api/documentformat.openxml.presentation.extensionlistwithmodification) | -| \ | [HeaderFooter](/dotnet/api/documentformat.openxml.presentation.headerfooter) | +| **PresentationML Element** | **Open XML SDK Class** | +|----------------------------|--------------------------------------------------------------------------------------| +| `` | | +| `` | | +| `` | | +| `` | | ## Open XML SDK HandoutMaster Class -The Open XML SDK **HandoutMaster** class represents the \ element defined in the Open XML File Format schema for PresentationML documents. Use the **HandoutMaster** class to manipulate individual \ elements in a PresentationML document. +The Open XML SDK `HandoutMaster` class represents the `` element defined in the Open XML File Format schema for PresentationML documents. Use the `HandoutMaster` class to manipulate individual `` elements in a PresentationML document. -Classes commonly associated with the **HandoutMaster** class are shown in the following sections. +Classes commonly associated with the `HandoutMaster` class are shown in the following sections. ### ColorMap Class -The **ColorMap** class corresponds to the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: +The `ColorMap` class corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `` element: This element specifies the mapping layer that transforms one color scheme definition to another. Each attribute represents a color name @@ -71,30 +71,30 @@ accent6="accent6" hlink="hlink" folHlink="folHlink"/> ### CommonSlideData Class -The **CommonSlideData** class corresponds to -the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `CommonSlideData` class corresponds to +the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: This element specifies a container for the type of slide information that is relevant to all of the slide types. All slides share a common set of properties that is independent of the slide type; the description of these properties for any particular slide is stored within the -slide's \ container. Slide data specific to the slide type +slide's `` container. Slide data specific to the slide type indicated by the parent element is stored elsewhere. -The actual data in \ describe only the particular parent slide; +The actual data in `` describe only the particular parent slide; it is only the type of information stored that is common across all slides. ### ExtensionListWithModification Class -The **ExtensionListWithModification** class -corresponds to the \element. The following information from the +The `ExtensionListWithModification` class +corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +specification introduces the `` element: This element specifies the extension list with modification ability -within which all future extensions of element type \ are defined. +within which all future extensions of element type `` are defined. The extension list along with corresponding future extensions is used to extend the storage capabilities of the PresentationML framework. This allows for various new kinds of data to be stored natively within the @@ -106,9 +106,9 @@ store whether this extension property has been modified. ### HeaderFooter Class -The **HeaderFooter** class corresponds to the -\ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `HeaderFooter` class corresponds to the +`` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: This element specifies the header and footer information for a slide. Headers and footers consist of placeholders for text that should be @@ -119,37 +119,37 @@ slide numbering, and custom header and footer text. ## Working with the HandoutMaster Class As shown in the Open XML SDK code sample that follows, every instance of -the **HandoutMaster** class is associated with -an instance of the [HandoutMasterPart](/dotnet/api/documentformat.openxml.packaging.handoutmasterpart) class, which represents a +the `HandoutMaster` class is associated with +an instance of the class, which represents a handout master part, one of the parts of a PresentationML presentation file package, and a part that is required for a presentation file that contains handouts. -The **HandoutMaster** class, which represents -the \ element, is therefore also associated with a +The `HandoutMaster` class, which represents +the `` element, is therefore also associated with a series of other classes that represent the child elements of the -\ element. Among these classes, as shown in the -following code sample, are the **CommonSlideData** class, the **ColorMap** class, the [ShapeTree](/dotnet/api/documentformat.openxml.presentation.shapetree) class, and the [Shape](/dotnet/api/documentformat.openxml.presentation.shape) class. +`` element. Among these classes, as shown in the +following code sample, are the `CommonSlideData` class, the `ColorMap` class, the class, and the class. ## Open XML SDK Code Example The following method adds a new handout master part to an existing -presentation and creates an instance of an Open XML SDK**HandoutMaster** class in the new handout master -part. The **HandoutMaster** class constructor -creates instances of the **CommonSlideData** -class and the **ColorMap** class. The **CommonSlideData** class constructor creates an -instance of the [ShapeTree](/dotnet/api/documentformat.openxml.presentation.shapetree) class, whose constructor, in -turn, creates additional class instances: an instance of the [NonVisualGroupShapeProperties](/dotnet/api/documentformat.openxml.presentation.nonvisualgroupshapeproperties) class, an -instance of the [GroupShapeProperties](/dotnet/api/documentformat.openxml.presentation.groupshapeproperties) class, and an instance -of the [Shape](/dotnet/api/documentformat.openxml.presentation.shape) class. - -The namespace represented by the letter *P* in the code is the [DocumentFormat.OpenXml.Presentation](/dotnet/api/documentformat.openxml.presentation) +presentation and creates an instance of an Open XML SDK `HandoutMaster` class in the new handout master +part. The `HandoutMaster` class constructor +creates instances of the `CommonSlideData` +class and the `ColorMap` class. The `CommonSlideData` class constructor creates an +instance of the class, whose constructor, in +turn, creates additional class instances: an instance of the class, an +instance of the class, and an instance +of the class. + +The namespace represented by the letter `P` in the code is the namespace. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/working_with_handout_master_slides/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/working_with_handout_master_slides/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/working_with_handout_master_slides/vb/Program.vb)] +[!code-vb[](../../samples/presentation/working_with_handout_master_slides/vb/Program.vb#snippet0)] ## Generated PresentationML @@ -157,55 +157,41 @@ When the Open XML SDK code is run, the following XML is written to the PresentationML document referenced in the code. ```xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ``` ## See also diff --git a/docs/presentation/working-with-notes-slides.md b/docs/presentation/working-with-notes-slides.md index 1b7dfbd1..99f8c2d9 100644 --- a/docs/presentation/working-with-notes-slides.md +++ b/docs/presentation/working-with-notes-slides.md @@ -11,19 +11,21 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/16/2025 ms.localizationpriority: medium --- # Working with notes slides -This topic discusses the Open XML SDK for Office [NotesSlide](/dotnet/api/documentformat.openxml.presentation.notesslide) class and how it relates to the +This topic discusses the Open XML SDK for Office class and how it relates to the Open XML File Format PresentationML schema. -------------------------------------------------------------------------------- + ## Notes Slides in PresentationML + The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the Open XML PresentationML \ element +specification describes the Open XML PresentationML `` element used to represent notes slides in a PresentationML document as follows: This element specifies the existence of a notes slide along with its @@ -34,11 +36,11 @@ notes element. **Example**: Consider the following PresentationML notes slide: ```xml - - - … - - … + + + … + + … ``` @@ -47,199 +49,230 @@ slide with all of its parts. Notice the cSld element, which specifies the common elements that can appear on any slide type and then any elements specify additional non-common properties for this notes slide. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -The \ element is the root element of the PresentationML Notes +The `` element is the root element of the PresentationML Notes Slide part. For more information about the overall structure of the parts and elements that make up a PresentationML document, see [Structure of a PresentationML Document](structure-of-a-presentationml-document.md). -The following table lists the child elements of the \ element +The following table lists the child elements of the `` element used when working with notes slides and the Open XML SDK classes that correspond to them. -| **PresentationML Element** | **Open XML SDK Class** | -|----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------| -| \ | [ColorMapOverride](/dotnet/api/documentformat.openxml.presentation.colormapoverride) | -| \ | [CommonSlideData](/dotnet/api/documentformat.openxml.presentation.commonslidedata) | -| \ | [ExtensionListWithModification](/dotnet/api/documentformat.openxml.presentation.extensionlistwithmodification) | +| **PresentationML Element** | **Open XML SDK Class** | +|----------------------------|-------------------------------------| +| `` | | +| `` | | +| `` | | The following table from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the attributes of the \ element. +specification describes the attributes of the `` element. -| **Attributes** | **Description** | -|-------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| showMasterPhAnim (Show Master Placeholder Animations) | Specifies whether or not to display animations on placeholders from the master slide.
The possible values for this attribute are defined by the W3C XML Schema **boolean** datatype. | -| showMasterSp (Show Master Shapes) | Specifies if shapes on the master slide should be shown on slides or not.
The possible values for this attribute are defined by the W3C XML Schema **boolean** datatype. | +| **Attributes** | **Description** | +|-------------------------------------------------------|---------------------| +| `showMasterPhAnim` (Show Master Placeholder Animations) | Specifies whether or not to display animations on placeholders from the master slide.

The possible values for this attribute are defined by the W3C XML Schema `boolean` datatype. | +| `showMasterSp` (Show Master Shapes) | Specifies if shapes on the master slide should be shown on slides or not.

The possible values for this attribute are defined by the W3C XML Schema `boolean` datatype. | -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] --------------------------------------------------------------------------------- + ## Open XML SDK NotesSlide Class -The OXML SDK **NotesSlide** class represents -the \ element defined in the Open XML File Format schema for -PresentationML documents. Use the **NotesSlide** class to manipulate individual -\ elements in a PresentationML document. -Classes that represent child elements of the \ element and that -are therefore commonly associated with the **NotesSlide** class are shown in the following list. +The OXML SDK `NotesSlide` class represents +the `` element defined in the Open XML File Format schema for +PresentationML documents. Use the `NotesSlide` class to manipulate individual +`` elements in a PresentationML document. -### ColorMapOverride Class +Classes that represent child elements of the `` element and that +are therefore commonly associated with the `NotesSlide` class are shown in the following list. -The **ColorMapOverride** class corresponds to -the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +- ### ColorMapOverride Class -This element provides a mechanism with which to override the color -schemes listed within the \ element. If the -\ child element is present, the color scheme defined -by the master is used. If the \ child element is -present, it defines a new color scheme specific to the parent notes -slide, presentation slide, or slide layout. + The `ColorMapOverride` class corresponds to + the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] + specification introduces the `` element: -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] + This element provides a mechanism with which to override the color + schemes listed within the `` element. If the + `` child element is present, the color scheme defined + by the master is used. If the `` child element is + present, it defines a new color scheme specific to the parent notes + slide, presentation slide, or slide layout. -### CommonSlideData Class +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -The **CommonSlideData** class corresponds to -the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +- ### CommonSlideData Class -This element specifies a container for the type of slide information -that is relevant to all of the slide types. All slides share a common -set of properties that is independent of the slide type; the description -of these properties for any particular slide is stored within the -slide's \ container. Slide data specific to the slide type -indicated by the parent element is stored elsewhere. + The `CommonSlideData` class corresponds to + the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] + specification introduces the `` element: -The actual data in \ describe only the particular parent slide; -it is only the type of information stored that is common across all -slides. + This element specifies a container for the type of slide information + that is relevant to all of the slide types. All slides share a common + set of properties that is independent of the slide type; the description + of these properties for any particular slide is stored within the + slide's `` container. Slide data specific to the slide type + indicated by the parent element is stored elsewhere. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] + The actual data in `` describe only the particular parent slide; + it is only the type of information stored that is common across all + slides. -### ExtensionListWithModification Class + © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -The **ExtensionListWithModification** class -corresponds to the \element. The following information from the -[!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +- ### ExtensionListWithModification Class -This element specifies the extension list with modification ability -within which all future extensions of element type \ are defined. -The extension list along with corresponding future extensions is used to -extend the storage capabilities of the PresentationML framework. This -allows for various new kinds of data to be stored natively within the -framework. + The `ExtensionListWithModification` class + corresponds to the ``element. The following information from the + [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `` element: -[Note: Using this extLst element allows the generating application to -store whether this extension property has been modified. end note] + This element specifies the extension list with modification ability + within which all future extensions of element type `` are defined. + The extension list along with corresponding future extensions is used to + extend the storage capabilities of the PresentationML framework. This + allows for various new kinds of data to be stored natively within the + framework. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] + [Note: Using this extLst element allows the generating application to + store whether this extension property has been modified. end note] + + © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] --------------------------------------------------------------------------------- ## Working with the NotesSlide Class + As shown in the Open XML SDK code sample that follows, every instance of -the **NotesSlide** class is associated with an -instance of the [NotesSlidePart](/dotnet/api/documentformat.openxml.packaging.notesslidepart) class, which represents a +the `NotesSlide` class is associated with an +instance of the class, which represents a notes slide part, one of the parts of a PresentationML presentation file package, and a part that is required for each notes slide in a -presentation file. Each **NotesSlide** class -instance may also be associated with an instance of the [NotesMaster](/dotnet/api/documentformat.openxml.presentation.notesmaster) class, which in turn is +presentation file. Each `NotesSlide` class +instance may also be associated with an instance of the class, which in turn is associated with a similarly named presentation part, represented by the -[NotesMasterPart](/dotnet/api/documentformat.openxml.packaging.notesmasterpart) class. + class. -The **NotesSlide** class, which represents the -\ element, is therefore also associated with a series of other -classes that represent the child elements of the \ element. +The `NotesSlide` class, which represents the +`` element, is therefore also associated with a series of other +classes that represent the child elements of the `` element. Among these classes, as shown in the following code sample, are the -**CommonSlideData** class and the **ColorMapOverride** class. The [ShapeTree](/dotnet/api/documentformat.openxml.presentation.shapetree) class and the [Shape](/dotnet/api/documentformat.openxml.presentation.shape) classes are in turn associated with -the **CommonSlideData** class. +`CommonSlideData` class and the `ColorMapOverride` class. The class and the classes are in turn associated with +the `CommonSlideData` class. -------------------------------------------------------------------------------- ## Open XML SDK Code Example -The following method adds a new notes slide part to an existing -presentation and creates an instance of an Open XML SDK**NotesSlide** class in the new notes slide part. The -**NotesSlide** class constructor creates -instances of the **CommonSlideData** class and -the **ColorMap** class. The **CommonSlideData** class constructor creates an -instance of the [ShapeTree](/dotnet/api/documentformat.openxml.presentation.shapetree) class, whose constructor in turn -creates additional class instances: an instance of the [NonVisualGroupShapeProperties](/dotnet/api/documentformat.openxml.presentation.nonvisualgroupshapeproperties) class, an -instance of the [GroupShapeProperties](/dotnet/api/documentformat.openxml.presentation.groupshapeproperties) class, and an instance -of the [Shape](/dotnet/api/documentformat.openxml.presentation.shape) class. -The namespace represented by the letter *P* in the code is the [DocumentFormat.OpenXml.Presentation](/dotnet/api/documentformat.openxml.presentation) -namespace. +> In the following code snippets `P` represents the namespace and `D` represents the namespace. -### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/working_with_notes_slides/cs/Program.cs)] +In the snippet below, a presentation is opened with `Presentation.Open` and the first +is retrieved or added if the presentation does not already have a `SlidePart`. -### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/working_with_notes_slides/vb/Program.vb)] +### [C#](#tab/cs-0) +[!code-csharp[](../../samples/presentation/working_with_notes_slides/cs/Program.cs#snippet1)] +### [Visual Basic](#tab/vb-0) +[!code-vb[](../../samples/presentation/working_with_notes_slides/vb/Program.vb#snippet1)] +*** ---------------------------------------------------------------------------------- -## Generated PresentationML -When the Open XML SDK code is run, the following XML is written to -the PresentationML document referenced in the code. + +In this snippet the a `NoteSlide` is added to the `NoteSlidePart` if one does not already exist. +The `NotesSlide` class constructor creates instances of the `CommonSlideData` class. +The `CommonSlideData` class constructor creates an instance of the class, whose constructor in turn +creates additional class instances: an instance of the class, an +instance of the class, and an instance +of the class. + + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/presentation/working_with_notes_slides/cs/Program.cs#snippet2)] +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/presentation/working_with_notes_slides/vb/Program.vb#snippet2)] +*** + +The `Shape` constructor creates an instance of , , and classes along with their required child elements. The `TextBody` +contains the , that has a , which contains the text of the note. The slide part is then added to the notes slide part. + +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/presentation/working_with_notes_slides/cs/Program.cs#snippet3)] +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/presentation/working_with_notes_slides/vb/Program.vb#snippet3)] +*** + +The notes slide part created with the code above contains the following XML ```xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is a test note! + + + + + + + ``` + +The following snippets add the required and if they are missing. + +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/presentation/working_with_notes_slides/cs/Program.cs#snippet4)] +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/presentation/working_with_notes_slides/vb/Program.vb#snippet4)] +*** + +## Sample code + +The following is the complete code sample in both C\# and Visual Basic. + +### [C#](#tab/cs-4) +[!code-csharp[](../../samples/presentation/working_with_notes_slides/cs/Program.cs#snippet0)] +### [Visual Basic](#tab/vb-4) +[!code-vb[](../../samples/presentation/working_with_notes_slides/vb/Program.vb#snippet0)] +*** + -------------------------------------------------------------------------------- ## See also -[About the Open XML SDK for Office](../about-the-open-xml-sdk.md) +[About the Open XML SDK for Office](../about-the-open-xml-sdk.md) -[How to: Create a Presentation by Providing a File Name](how-to-create-a-presentation-document-by-providing-a-file-name.md) +[How to: Create a Presentation by Providing a File Name](how-to-create-a-presentation-document-by-providing-a-file-name.md) -[How to: Insert a new slide into a presentation](how-to-insert-a-new-slide-into-a-presentation.md) +[How to: Insert a new slide into a presentation](how-to-insert-a-new-slide-into-a-presentation.md) -[How to: Delete a slide from a presentation](how-to-delete-a-slide-from-a-presentation.md) +[How to: Delete a slide from a presentation](how-to-delete-a-slide-from-a-presentation.md) -[How to: Apply a theme to a presentation](how-to-apply-a-theme-to-a-presentation.md) +[How to: Apply a theme to a presentation](how-to-apply-a-theme-to-a-presentation.md) diff --git a/docs/presentation/working-with-presentation-slides.md b/docs/presentation/working-with-presentation-slides.md index 1275b7b7..ef029869 100644 --- a/docs/presentation/working-with-presentation-slides.md +++ b/docs/presentation/working-with-presentation-slides.md @@ -11,22 +11,21 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 09/20/2024 ms.localizationpriority: high --- # Working with presentation slides -This topic discusses the Open XML SDK for Office [Slide](/dotnet/api/documentformat.openxml.presentation.slide) class and how it relates to the Open +This topic discusses the Open XML SDK for Office  class and how it relates to the Open XML File Format PresentationML schema. For more information about the overall structure of the parts and elements that make up a -PresentationML document, see [Structure of a -PresentationML document](structure-of-a-presentationml-document.md)**. +PresentationML document, see [Structure of a PresentationML document](structure-of-a-presentationml-document.md). --------------------------------------------------------------------------------- ## Presentation Slides in PresentationML The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the Open XML PresentationML \ element used +specification describes the Open XML PresentationML `` element used to represent a presentation slide in a PresentationML document as follows: @@ -52,233 +51,169 @@ In the above example the order specified to present the slides is slide 4, then 3, 2, and finally 5. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -The \ element is the root element of the PresentationML Slide +The `` element is the root element of the PresentationML Slide part. For more information about the overall structure of the parts and elements that make up a PresentationML document, see [Structure of a PresentationML Document](structure-of-a-presentationml-document.md). -The following table lists the child elements of the \ element used +The following table lists the child elements of the `` element used when working with presentation slides and the Open XML SDK classes that correspond to them. | **PresentationML Element** | **Open XML SDK Class** | -|----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------| -| \ | [ColorMapOverride](/dotnet/api/documentformat.openxml.presentation.colormapoverride) | -| \ | [CommonSlideData](/dotnet/api/documentformat.openxml.presentation.commonslidedata) | -| \ | [ExtensionListWithModification](/dotnet/api/documentformat.openxml.presentation.extensionlistwithmodification) | -| \ | [Timing](/dotnet/api/documentformat.openxml.presentation.timing) | -| \ | [Transition](/dotnet/api/documentformat.openxml.presentation.transition) | +|----------------------------|--------------------------------------------------------| +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | -------------------------------------------------------------------------------- ## Open XML SDK Slide Class -The Open XML SDK**Slide** class represents the \ element +The Open XML SDK `Slide` class represents the `` element defined in the Open XML File Format schema for PresentationML documents. -Use the **Slide** object to manipulate -individual \ elements in a PresentationML document. +Use the `Slide` object to manipulate +individual `` elements in a PresentationML document. -Classes commonly associated with the **Slide** +Classes commonly associated with the `Slide` class are shown in the following sections. ### ColorMapOverride Class -The **ColorMapOverride** class corresponds to -the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `ColorMapOverride` class corresponds to +the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: This element provides a mechanism with which to override the color -schemes listed within the \ element. If the -\ child element is present, the color scheme defined -by the master is used. If the \ child element is +schemes listed within the `` element. If the +`` child element is present, the color scheme defined +by the master is used. If the `` child element is present, it defines a new color scheme specific to the parent notes slide, presentation slide, or slide layout. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### CommonSlideData Class -The **CommonSlideData** class corresponds to -the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `CommonSlideData` class corresponds to +the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: This element specifies a container for the type of slide information that is relevant to all of the slide types. All slides share a common set of properties that is independent of the slide type; the description of these properties for any particular slide is stored within the -slide's \ container. Slide data specific to the slide type +slide's `` container. Slide data specific to the slide type indicated by the parent element is stored elsewhere. -The actual data in \ describe only the particular parent slide; +The actual data in `` describe only the particular parent slide; it is only the type of information stored that is common across all slides. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### ExtensionListWithModification Class -The **ExtensionListWithModification** class -corresponds to the \element. The following information from the +The `ExtensionListWithModification` class +corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +specification introduces the `` element: This element specifies the extension list with modification ability -within which all future extensions of element type \ are defined. +within which all future extensions of element type `` are defined. The extension list along with corresponding future extensions is used to extend the storage capabilities of the PresentationML framework. This allows for various new kinds of data to be stored natively within the framework. -[Note: Using this extLst element allows the generating application to +[Note: Using this `extLst` element allows the generating application to store whether this extension property has been modified. end note] -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Timing Class -The **Timing** class corresponds to the -\ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `Timing` class corresponds to the +`` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: This element specifies the timing information for handling all animations and timed events within the corresponding slide. This -information is tracked via time nodes within the \ element. +information is tracked via time nodes within the `` element. More information on the specifics of these time nodes and how they are to be defined can be found within the Animation section of the PresentationML framework. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Transition Class -The **Transition** class corresponds to the -\ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `Transition` class corresponds to the +`` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: This element specifies the kind of slide transition that should be used to transition to the current slide from the previous slide. That is, the transition information is stored on the slide that appears after the transition is complete. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -------------------------------------------------------------------------------- ## Working with the Slide Class + As shown in the Open XML SDK code example that follows, every instance -of the **Slide** class is associated with an -instance of the [SlidePart](/dotnet/api/documentformat.openxml.packaging.slidepart) class, which represents a slide +of the `Slide` class is associated with an +instance of the class, which represents a slide part, one of the required parts of a PresentationML presentation file -package. Each instance of the **Slide** class -must also be associated with instances of the [SlideLayout](/dotnet/api/documentformat.openxml.presentation.slidelayout) and [SlideMaster](/dotnet/api/documentformat.openxml.presentation.slidemaster) classes, which are in turn +package. Each instance of the `Slide` class +must also be associated with instances of the and classes, which are in turn associated with similarly named required presentation parts, represented -by the [SlideLayoutPart](/dotnet/api/documentformat.openxml.packaging.slidelayoutpart) and [SlideMasterPart](/dotnet/api/documentformat.openxml.packaging.slidemasterpart) classes. +by the and classes. -The **Slide** class, which represents the -\ element, is therefore also associated with a series of other -classes that represent the child elements of the \ element. Among -these classes, as shown in the following code example, are the **CommonSlideData** class, the **ColorMapOverride** class, the [ShapeTree](/dotnet/api/documentformat.openxml.presentation.shapetree) class, and the [Shape](/dotnet/api/documentformat.openxml.presentation.shape) class. +The `Slide` class, which represents the +`` element, is therefore also associated with a series of other +classes that represent the child elements of the `` element. Among +these classes, as shown in the following code example, are the `CommonSlideData` class, the `ColorMapOverride` class, the class, and the class. -------------------------------------------------------------------------------- ## Open XML SDK Code Example -The following method from the article [How to: Create a presentation document by providing a file name](how-to-create-a-presentation-document-by-providing-a-file-name.md)** adds a new slide +The following method from the article [How to: Create a presentation document by providing a file name](how-to-create-a-presentation-document-by-providing-a-file-name.md) adds a new slide part to an existing presentation and creates an instance of the Open XML -SDK **Slide** class in the new slide part. -The **Slide** class constructor creates -instances of the **CommonSlideData** and **ColorMapOverride** classes. The **CommonSlideData** class constructor creates an -instance of the **ShapeTree** class, whose +SDK `Slide` class in the new slide part. +The `Slide` class constructor creates +instances of the `CommonSlideData` and `ColorMapOverride` classes. The `CommonSlideData` class constructor creates an +instance of the `ShapeTree` class, whose constructor, in turn, creates additional class instances: an instance of -the [NonVisualGroupShapeProperties](/dotnet/api/documentformat.openxml.presentation.nonvisualgroupshapeproperties) class, the [GroupShapeProperties](/dotnet/api/documentformat.openxml.presentation.groupshapeproperties) class, and the **Shape** class. +the class, the class, and the `Shape` class. All of these class instances and instances of the classes that represent -the child elements of the \ element are required to create the +the child elements of the `` element are required to create the minimum number of XML elements necessary to represent a new slide. -The namespace represented by the letter *P* in the code is the [DocumentFormat.OpenXml.Presentation](/dotnet/api/documentformat.openxml.presentation) +The namespace represented by the letter *P* in the code is the namespace. ### [C#](#tab/cs-0) -```csharp - private static SlidePart CreateSlidePart(PresentationPart presentationPart) - { - SlidePart slidePart1 = presentationPart.AddNewPart("rId2"); - slidePart1.Slide = new Slide( - new CommonSlideData( - new ShapeTree( - new P.NonVisualGroupShapeProperties( - new P.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "" }, - new P.NonVisualGroupShapeDrawingProperties(), - new ApplicationNonVisualDrawingProperties()), - new GroupShapeProperties(new TransformGroup()), - new P.Shape( - new P.NonVisualShapeProperties( - new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title 1" }, - new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }), - new ApplicationNonVisualDrawingProperties(new PlaceholderShape())), - new P.ShapeProperties(), - new P.TextBody( - new BodyProperties(), - new ListStyle(), - new Paragraph(new EndParagraphRunProperties() { Language = "en-US" }))))), - new ColorMapOverride(new MasterColorMapping())); - return slidePart1; - } -``` - +[!code-csharp[](../../samples/presentation/create_by_providing_a_file_name/cs/Program.cs#snippet102)] ### [Visual Basic](#tab/vb-0) -```vb - Private Shared Function CreateSlidePart(ByVal presentationPart As PresentationPart) As SlidePart - Dim slidePart1 As SlidePart = presentationPart.AddNewPart(Of SlidePart)("rId2") - slidePart1.Slide = New Slide(New CommonSlideData(New ShapeTree(New P.NonVisualGroupShapeProperties(New P.NonVisualDrawingProperties() With { _ - .Id = CType(1UI, UInt32Value), _ - .Name = "" _ - }, New P.NonVisualGroupShapeDrawingProperties(), New ApplicationNonVisualDrawingProperties()), New GroupShapeProperties(New TransformGroup()), _ - New P.Shape(New P.NonVisualShapeProperties(New P.NonVisualDrawingProperties() With { _ - .Id = CType(2UI, UInt32Value), _ - .Name = "Title 1" _ - }, New P.NonVisualShapeDrawingProperties(New ShapeLocks() With { _ - .NoGrouping = True _ - }), New ApplicationNonVisualDrawingProperties(New PlaceholderShape())), New P.ShapeProperties(), New P.TextBody(New BodyProperties(), _ - New ListStyle(), New Paragraph(New EndParagraphRunProperties() With { _ - .Language = "en-US" _ - }))))), New ColorMapOverride(New MasterColorMapping())) - Return slidePart1 - End Function -``` +[!code-vb[](../../samples/presentation/create_by_providing_a_file_name/vb/Program.vb#snippet102)] *** To add another shape to the shape tree and, hence, to the slide, -instantiate a second **Shape** object by +instantiate a second `Shape` object by passing an additional parameter that contains the following code to the -**ShapeTree** constructor. +`ShapeTree` constructor. ### [C#](#tab/cs-1) -```csharp - new P.Shape( - new P.NonVisualShapeProperties( - new P.NonVisualDrawingProperties() { Id = (UInt32Value)2U, Name = "Title 1" }, - new P.NonVisualShapeDrawingProperties(new ShapeLocks() { NoGrouping = true }), - new ApplicationNonVisualDrawingProperties(new PlaceholderShape())), - new P.ShapeProperties(), - new P.TextBody( - new BodyProperties(), - new ListStyle(), - new Paragraph(new EndParagraphRunProperties() { Language = "en-US" }))) -``` - +[!code-csharp[](../../samples/presentation/create_by_providing_a_file_name/cs/Program.cs#snippet103)] ### [Visual Basic](#tab/vb-1) -```vb - New P.Shape(New P.NonVisualShapeProperties(New P.NonVisualDrawingProperties() With { _ - .Id = CType(2UI, UInt32Value), _ - .Name = "Title 1" _ - }, New P.NonVisualShapeDrawingProperties(New ShapeLocks() With { _ - .NoGrouping = True _ - }), New ApplicationNonVisualDrawingProperties(New PlaceholderShape())), New P.ShapeProperties(), New P.TextBody(New BodyProperties(), _ - New ListStyle(), New Paragraph(New EndParagraphRunProperties() With { _ - .Language = "en-US" }))) -``` +[!code-vb[](../../samples/presentation/create_by_providing_a_file_name/vb/Program.vb#snippet103)] *** diff --git a/docs/presentation/working-with-presentations.md b/docs/presentation/working-with-presentations.md index 2f0708a6..973c4111 100644 --- a/docs/presentation/working-with-presentations.md +++ b/docs/presentation/working-with-presentations.md @@ -11,22 +11,21 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 09/19/2024 ms.localizationpriority: medium --- # Working with presentations -This topic discusses the Open XML SDK for Office [Presentation](/dotnet/api/documentformat.openxml.presentation.presentation) class and how it relates to +This topic discusses the Open XML SDK for Office  class and how it relates to the Open XML File Format PresentationML schema. For more information about the overall structure of the parts and elements that make up a -PresentationML document, see [Structure of a -PresentationML document](structure-of-a-presentationml-document.md). +PresentationML document, see [Structure of a PresentationML document](structure-of-a-presentationml-document.md). --------------------------------------------------------------------------------- ## Presentations in PresentationML The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the Open XML PresentationML \ +specification describes the Open XML PresentationML `` element used to represent a presentation in a PresentationML document as follows: @@ -55,53 +54,53 @@ size and default text styles. ``` -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -The \ element typically contains child elements that list +The `` element typically contains child elements that list slide masters, slides, and custom slide shows contained within the presentation. In addition, it also commonly contains elements that specify other properties of the presentation, such as slide size, notes size, and default text styles. -The \ element is the root element of the PresentationML +The `` element is the root element of the PresentationML Presentation part. For more information about the overall structure of the parts and elements that make up a PresentationML document, see [Structure of a PresentationML Document](structure-of-a-presentationml-document.md). The following table lists some of the most common child elements of the -\ element used when working with presentations and the +`` element used when working with presentations and the Open XML SDK classes that correspond to them. | **PresentationML Element** | **Open XML SDK Class** | |----------------------------|-------------------------------------------------------------------------------------------------------------------------------------| -| \ | [SlideMasterIdList](/dotnet/api/documentformat.openxml.presentation.slidemasteridlist) | -| \ | [SlideMasterId](/dotnet/api/documentformat.openxml.presentation.slidemasterid) | -| \ | [SlideIdList](/dotnet/api/documentformat.openxml.presentation.slideidlist) | -| \ | [SlideId](/dotnet/api/documentformat.openxml.presentation.slideid) | -| \ | [NotesMasterIdList](/dotnet/api/documentformat.openxml.presentation.notesmasteridlist) | -| \ | [HandoutMasterIdList](/dotnet/api/documentformat.openxml.presentation.handoutmasteridlist) | -| \ | [CustomShowList](/dotnet/api/documentformat.openxml.presentation.customshowlist) | -| \ | [SlideSize](/dotnet/api/documentformat.openxml.presentation.slidesize) | -| \ | [NotesSize](/dotnet/api/documentformat.openxml.presentation.notessize) | -| \ | [DefaultTextStyle](/dotnet/api/documentformat.openxml.presentation.defaulttextstyle) | +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | -------------------------------------------------------------------------------- ## Open XML SDK Presentation Class -The Open XML SDK**Presentation** class -represents the \ element defined in the Open XML File -Format schema for PresentationML documents. Use the **Presentation** class to manipulate an individual -\ element in a PresentationML document. +The Open XML SDK `Presentation` class +represents the `` element defined in the Open XML File +Format schema for PresentationML documents. Use the `Presentation` class to manipulate an individual +`` element in a PresentationML document. -Classes commonly associated with the **Presentation** class are shown in the following +Classes commonly associated with the `Presentation` class are shown in the following sections. ### SlideMasterIdList Class All slides that share the same master inherit the same layout from that -master. The **SlideMasterIdList** class -corresponds to the \ element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the Open XML PresentationML \ +master. The `SlideMasterIdList` class +corresponds to the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification describes the Open XML PresentationML `` element used to represent a slide master ID list in a PresentationML document as follows: @@ -110,13 +109,13 @@ slide master slides that are available within the corresponding presentation. A slide master is a slide that is specifically designed to be a template for all related child layout slides. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### SlideMasterId Class -The **SlideMasterId** class corresponds to the -\ element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the Open XML PresentationML \ +The `SlideMasterId` class corresponds to the +`` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification describes the Open XML PresentationML `` element used to represent a slide master ID in a PresentationML document as follows: @@ -139,13 +138,13 @@ embedTrueTypeFonts="1"> ``` -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### SlideIdList Class -The **SlideIdList** class corresponds to the -\ element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the Open XML PresentationML \ element +The `SlideIdList` class corresponds to the +`` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification describes the Open XML PresentationML `` element used to represent a slide ID list in a PresentationML document as follows: @@ -154,13 +153,13 @@ slides that are available within the corresponding presentation. A slide contains the information that is specific to a single slide such as slide-specific shape and text information. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### SlideId Class -The **SlideId** class corresponds to the -\ element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the Open XML PresentationML \ element +The `SlideId` class corresponds to the +`` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification describes the Open XML PresentationML `` element used to represent a slide ID in a PresentationML document as follows: This element specifies a presentation slide that is available within the @@ -172,8 +171,7 @@ information. a presentation ```xml - + @@ -186,13 +184,13 @@ embedTrueTypeFonts="1"> ``` -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### NotesMasterIdList Class -The **NotesMasterIdList** class corresponds to -the \ element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the Open XML PresentationML \ +The `NotesMasterIdList` class corresponds to +the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification describes the Open XML PresentationML `` element used to represent a notes master ID list in a PresentationML document as follows: @@ -201,14 +199,14 @@ notes master slides that are available within the corresponding presentation. A notes master is a slide that is specifically designed for the printing of the slide along with any attached notes. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### HandoutMasterIdList Class -The **HandoutMasterIdList** class corresponds -to the \ element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +The `HandoutMasterIdList` class corresponds +to the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML -\ element used to represent a handout master ID +`` element used to represent a handout master ID list in a PresentationML document as follows: This element specifies a list of identification information for the @@ -216,13 +214,13 @@ handout master slides that are available within the corresponding presentation. A handout master is a slide that is specifically designed for printing as a handout. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### CustomShowList Class -The **CustomShowList** class corresponds to the -\ element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the Open XML PresentationML \ +The `CustomShowList` class corresponds to the +`` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification describes the Open XML PresentationML `` element used to represent a custom show list in a PresentationML document as follows: @@ -231,13 +229,13 @@ within the corresponding presentation. A custom show is a defined slide sequence that allows for the displaying of the slides with the presentation in any arbitrary order. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### SlideSize Class -The **SlideSize** class corresponds to the -\ element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the Open XML PresentationML \ element +The `SlideSize` class corresponds to the +`` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification describes the Open XML PresentationML `` element used to represent presentation slide size in a PresentationML document as follows: @@ -258,13 +256,13 @@ embedTrueTypeFonts="1"> ``` -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### NotesSize Class -The **NotesSize** class corresponds to the -\ element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the Open XML PresentationML \ element +The `NotesSize` class corresponds to the +`` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification describes the Open XML PresentationML `` element used to represent notes slide size in a PresentationML document as follows: @@ -288,13 +286,13 @@ embedTrueTypeFonts="1"> ``` -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### DefaultTextStyle Class -The DefaultTextStyle class corresponds to the \ +The `DefaultTextStyle` class corresponds to the `` element. The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the Open XML PresentationML \ +specification describes the Open XML PresentationML `` element used to represent default text style in a PresentationML document as follows: @@ -304,47 +302,49 @@ when inserting a new slide if that slide is not associated with a master slide or if no styling information has been otherwise specified for the text within the presentation slide. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -------------------------------------------------------------------------------- ## Working with the Presentation Class + As shown in the Open XML SDK code example that follows, every instance -of the **Presentation** class is associated -with an instance of the [PresentationPart](/dotnet/api/documentformat.openxml.packaging.presentationpart) class, which represents a +of the `Presentation` class is associated +with an instance of the class, which represents a presentation part, one of the required parts of a PresentationML presentation file package. -The **Presentation** class, which represents -the \ element, is therefore also associated with a series +The `Presentation` class, which represents +the `` element, is therefore also associated with a series of other classes that represent the child elements of the -\ element. Among these classes, as shown in the following -code example, are the **SlideMasterIdList**, -**SlideIdList**, **SlideSize**, **NotesSize**, and **DefaultTextStyle** classes. +`` element. Among these classes, as shown in the following +code example, are the `SlideMasterIdList`, +`SlideIdList`, `SlideSize`, `NotesSize`, and `DefaultTextStyle` classes. -------------------------------------------------------------------------------- ## Open XML SDK Code Example -The following code example from the article [How to: Create a presentation document by providing a file name](how-to-create-a-presentation-document-by-providing-a-file-name.md) uses the [Create(String, PresentationDocumentType)](/dotnet/api/documentformat.openxml.packaging.presentationdocument.create) -method of the [PresentationDocument](/dotnet/api/documentformat.openxml.packaging.presentationdocument) class of the Open XML + +The following code example from the article [How to: Create a presentation document by providing a file name](how-to-create-a-presentation-document-by-providing-a-file-name.md) uses the +method of the class of the Open XML SDK to create an instance of that same class that has the specified -name and file path. Then it uses the [AddPresentationPart()](/dotnet/api/documentformat.openxml.packaging.presentationdocument.addpresentationpart) method to add an -instance of the [PresentationPart](/dotnet/api/documentformat.openxml.packaging.presentationpart) class to the document -file. Next, it creates an instance of the [Presentation](/dotnet/api/documentformat.openxml.presentation.presentation) class that represents the -presentation. It passes a reference to the **PresentationPart** class instance to the -**CreatePresentationParts** procedure, which creates the other required -parts of the presentation file. The **CreatePresentation** procedure -cleans up by closing the **PresentationDocument** class instance that it +name and file path. Then it uses the method to add an +instance of the class to the document +file. Next, it creates an instance of the class that represents the +presentation. It passes a reference to the `PresentationPart` class instance to the +`CreatePresentationParts` procedure, which creates the other required +parts of the presentation file. The `CreatePresentation` procedure +cleans up by closing the `PresentationDocument` class instance that it opened previously. -The **CreatePresentationParts** procedure creates instances of the **SlideMasterIdList**, **SlideIdList**, **SlideSize**, **NotesSize**, and **DefaultTextStyle** classes and appends them to the +The `CreatePresentationParts` procedure creates instances of the `SlideMasterIdList`, `SlideIdList`, `SlideSize`, `NotesSize`, and `DefaultTextStyle` classes and appends them to the presentation. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/working_with_presentations/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/create_by_providing_a_file_name/cs/Program.cs#snippet101)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/working_with_presentations/vb/Program.vb)] +[!code-vb[](../../samples/presentation/create_by_providing_a_file_name/vb/Program.vb#snippet101)] --------------------------------------------------------------------------------- ## Resulting PresentationML diff --git a/docs/presentation/working-with-slide-layouts.md b/docs/presentation/working-with-slide-layouts.md index 9f0a062d..2b8d96ec 100644 --- a/docs/presentation/working-with-slide-layouts.md +++ b/docs/presentation/working-with-slide-layouts.md @@ -11,104 +11,104 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 09/18/2024 ms.localizationpriority: medium --- # Working with slide layouts -This topic discusses the Open XML SDK for Office [SlideLayout](/dotnet/api/documentformat.openxml.presentation.slidelayout) class and how it relates to the Open XML File Format PresentationML schema. +This topic discusses the Open XML SDK for Office class and how it relates to the Open XML File Format PresentationML schema. ## Slide Layouts in PresentationML -The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML \ element used to represent slide layouts in a PresentationML document as follows: +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML `` element used to represent slide layouts in a PresentationML document as follows: This element specifies an instance of a slide layout. The slide layout contains in essence a template slide design that can be applied to any existing slide. When applied to an existing slide all corresponding content should be mapped to the new slide layout. -The \ element is the root element of the PresentationML +The `` element is the root element of the PresentationML Slide Layout part. For more information about the overall structure of the parts and elements that make up a PresentationML document, see [Structure of a PresentationML Document](structure-of-a-presentationml-document.md). -The following table lists the child elements of the \ +The following table lists the child elements of the `` element used when working with slide layouts and the Open XML SDK classes that correspond to them. -| **PresentationML Element** | **Open XML SDK Class** | -|----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------| -| \ | [ColorMapOverride](/dotnet/api/documentformat.openxml.presentation.colormapoverride) | -| \ | [CommonSlideData](/dotnet/api/documentformat.openxml.presentation.commonslidedata) | -| \ | [ExtensionListWithModification](/dotnet/api/documentformat.openxml.presentation.extensionlistwithmodification) | -| \ | [HeaderFooter](/dotnet/api/documentformat.openxml.presentation.headerfooter) | -| \ | [Timing](/dotnet/api/documentformat.openxml.presentation.timing) | -| \ | [Transition](/dotnet/api/documentformat.openxml.presentation.transition) | +| **PresentationML Element** | **Open XML SDK Class** | +|----------------------------|-------------------------------------| +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | The following table from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the attributes of the \ element. +specification describes the attributes of the `` element. -| **Attributes** | **Description** | -|-------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| matchingName (Matching Name) | Specifies a name to be used in place of the name attribute within the cSld element. This is used for layout matching in response to layout changes and template applications.
The possible values for this attribute are defined by the W3C XML Schema **string** datatype. | -| preserve (Preserve Slide Layout) | Specifies whether the corresponding slide layout is deleted when all the slides that follow that layout are deleted. If this attribute is not specified then a value of **false** should be assumed by the generating application. This would mean that the slide would in fact be deleted if no slides within the presentation were related to it.
The possible values for this attribute are defined by the W3C XML Schema **boolean** datatype. | -| showMasterPhAnim (Show Master Placeholder Animations) | Specifies whether or not to display animations on placeholders from the master slide.
The possible values for this attribute are defined by the W3C XML Schema **boolean** datatype. | -| showMasterSp (Show Master Shapes) | Specifies if shapes on the master slide should be shown on slides or not.
The possible values for this attribute are defined by the W3C XML Schema **boolean** datatype. | -| type (Slide Layout Type) | Specifies the slide layout type that is used by this slide.
The possible values for this attribute are defined by the ST_SlideLayoutType simple type (§19.7.15). | -| userDrawn (Is User Drawn) | Specifies if the corresponding object has been drawn by the user and should thus not be deleted. This allows for the flagging of slides that contain user drawn data.
The possible values for this attribute are defined by the W3C XML Schema **boolean** datatype. | +| **Attributes** | **Description** | +| -----------------|-------------------| +| matchingName (Matching Name) | Specifies a name to be used in place of the name attribute within the cSld element. This is used for layout matching in response to layout changes and template applications.

The possible values for this attribute are defined by the W3C XML Schema `string` datatype. | +| preserve (Preserve Slide Layout) | Specifies whether the corresponding slide layout is deleted when all the slides that follow that layout are deleted. If this attribute is not specified then a value of `false` should be assumed by the generating application. This would mean that the slide would in fact be deleted if no slides within the presentation were related to it.

The possible values for this attribute are defined by the W3C XML Schema `boolean` datatype. | +| showMasterPhAnim (Show Master Placeholder Animations) | Specifies whether or not to display animations on placeholders from the master slide.

The possible values for this attribute are defined by the W3C XML Schema `boolean` datatype. | +| showMasterSp (Show Master Shapes) | Specifies if shapes on the master slide should be shown on slides or not.

The possible values for this attribute are defined by the W3C XML Schema `boolean` datatype. | +| type (Slide Layout Type) | Specifies the slide layout type that is used by this slide.

The possible values for this attribute are defined by the ST_SlideLayoutType simple type (§19.7.15). | +| userDrawn (Is User Drawn) | Specifies if the corresponding object has been drawn by the user and should thus not be deleted. This allows for the flagging of slides that contain user drawn data.

The possible values for this attribute are defined by the W3C XML Schema `boolean` datatype. | ## The Open XML SDK SlideLayout Class -The OXML SDK **SlideLayout** class represents -the \ element defined in the Open XML File Format schema for -PresentationML documents. Use the **SlideLayout** class to manipulate individual -\ elements in a PresentationML document. +The OXML SDK `SlideLayout` class represents +the `` element defined in the Open XML File Format schema for +PresentationML documents. Use the `SlideLayout` class to manipulate individual +`` elements in a PresentationML document. -Classes that represent child elements of the \ element and -that are therefore commonly associated with the **SlideLayout** class are shown in the following +Classes that represent child elements of the `` element and +that are therefore commonly associated with the `SlideLayout` class are shown in the following list. ### ColorMapOverride Class -The **ColorMapOverride** class corresponds to -the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `ColorMapOverride` class corresponds to +the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: This element provides a mechanism with which to override the color -schemes listed within the \ element. If the -\ child element is present, the color scheme defined -by the master is used. If the \ child element is +schemes listed within the `` element. If the +`` child element is present, the color scheme defined +by the master is used. If the `` child element is present, it defines a new color scheme specific to the parent notes slide, presentation slide, or slide layout. ### CommonSlideData Class -The **CommonSlideData** class corresponds to -the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `CommonSlideData` class corresponds to +the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: This element specifies a container for the type of slide information that is relevant to all of the slide types. All slides share a common set of properties that is independent of the slide type; the description of these properties for any particular slide is stored within the -slide's \ container. Slide data specific to the slide type +slide's `` container. Slide data specific to the slide type indicated by the parent element is stored elsewhere. -The actual data in \ describe only the particular parent slide; +The actual data in `` describe only the particular parent slide; it is only the type of information stored that is common across all slides. ### ExtensionListWithModification Class -The **ExtensionListWithModification** class -corresponds to the \element. The following information from the +The `ExtensionListWithModification` class +corresponds to the ``element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +specification introduces the `` element: This element specifies the extension list with modification ability -within which all future extensions of element type \ are defined. +within which all future extensions of element type `` are defined. The extension list along with corresponding future extensions is used to extend the storage capabilities of the PresentationML framework. This allows for various new kinds of data to be stored natively within the @@ -119,9 +119,9 @@ framework. ### HeaderFooter Class -The **HeaderFooter** class corresponds to the -\ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `HeaderFooter` class corresponds to the +`` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: This element specifies the header and footer information for a slide. Headers and footers consist of placeholders for text that should be @@ -130,51 +130,52 @@ slide numbering, and custom header and footer text. ### Timing Class -The **Timing** class corresponds to the -\ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the \ element: +The `Timing` class corresponds to the +`` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] +specification introduces the `` element: This element specifies the timing information for handling all animations and timed events within the corresponding slide. This -information is tracked via time nodes within the \ element. +information is tracked via time nodes within the `` element. More information on the specifics of these time nodes and how they are to be defined can be found within the Animation section of the PresentationML framework. ### Transition Class -The **Transition** class corresponds to the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: +The `Transition` class corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `` element: This element specifies the kind of slide transition that should be used to transition to the current slide from the previous slide. That is, the transition information is stored on the slide that appears after the transition is complete. ## Working with the SlideLayout Class As shown in the Open XML SDK code sample that follows, every instance of -the **SlideLayout** class is associated with an -instance of the [SlideLayoutPart](/dotnet/api/documentformat.openxml.packaging.slidelayoutpart) class, which represents a +the `SlideLayout` class is associated with an +instance of the class, which represents a slide layout part, one of the required parts of a PresentationML -presentation file package. Each **SlideLayout** -class instance must also be associated with instances of the [SlideMaster](/dotnet/api/documentformat.openxml.presentation.slidemaster) and [Slide](/dotnet/api/documentformat.openxml.presentation.slide) classes, which are in turn associated +presentation file package. Each `SlideLayout` +class instance must also be associated with instances of the and classes, which are in turn associated with similarly named required presentation parts, represented by the -[SlideMasterPart](/dotnet/api/documentformat.openxml.packaging.slidemasterpart) and [SlidePart](/dotnet/api/documentformat.openxml.packaging.slidepart)classes. + and classes. -The **SlideLayout** class, which represents the -\ element, is therefore also associated with a series of -other classes that represent the child elements of the \ +The `SlideLayout` class, which represents the +`` element, is therefore also associated with a series of +other classes that represent the child elements of the `` element. Among these classes, as shown in the following code sample, are -the **CommonSlideData** class, the **ColorMapOverride** class, the [ShapeTree](/dotnet/api/documentformat.openxml.presentation.shapetree) class, and the [Shape](/dotnet/api/documentformat.openxml.presentation.shape) class. +the `CommonSlideData` class, the `ColorMapOverride` class, the class, and the class. ## Open XML SDK Code Example -The following method from the article [How to: Create a presentation document by providing a file name](how-to-create-a-presentation-document-by-providing-a-file-name.md) adds a new slide layout part to an existing presentation and creates an instance of an Open XML SDK**SlideLayout** class in the new slide layout part. The **SlideLayout** class constructor creates instances of the **CommonSlideData** class and the **ColorMapOverride** class. The **CommonSlideData** class constructor creates an instance of the [ShapeTree](/dotnet/api/documentformat.openxml.presentation.shapetree) class, whose constructor in turn creates additional class instances: an instance of the [NonVisualGroupShapeProperties (/dotnet/api/documentformat.openxml.presentation.nonvisualgroupshapeproperties) class, an instance of the [GroupShapeProperties](/dotnet/api/documentformat.openxml.presentation.groupshapeproperties) class, and an instance of the [Shape](/dotnet/api/documentformat.openxml.presentation.shape) class. +The following method from the article [How to: Create a presentation document by providing a file name](how-to-create-a-presentation-document-by-providing-a-file-name.md) adds a new slide layout part to an existing presentation and creates an instance of an Open XML SDK `SlideLayout` class in the new slide layout part. The `SlideLayout` class constructor creates instances of the `CommonSlideData` class and the `ColorMapOverride` class. The `CommonSlideData` class constructor creates an instance of the class, whose constructor in turn creates additional class instances: an instance of the class, an instance of the class, and an instance of the class. -The namespace represented by the letter *P* in the code is the [DocumentFormat.OpenXml.Presentation (/dotnet/api/documentformat.openxml.presentation) namespace. +The namespace represented by the letter *P* in the code is the namespace. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/working_with_slide_layouts/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/create_by_providing_a_file_name/cs/Program.cs#snippet100)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/working_with_slide_layouts/vb/Program.vb)] +[!code-vb[](../../samples/presentation/create_by_providing_a_file_name/vb/Program.vb#snippet100)] +*** ## Generated PresentationML @@ -226,5 +227,7 @@ When the Open XML SDK code is run, the following XML is written to the Presentat ## See also [About the Open XML SDK for Office](../about-the-open-xml-sdk.md) + [How to: Create a Presentation by Providing a File Name](how-to-create-a-presentation-document-by-providing-a-file-name.md) + [How to: Apply a theme to a presentation](how-to-apply-a-theme-to-a-presentation.md) diff --git a/docs/presentation/working-with-slide-masters.md b/docs/presentation/working-with-slide-masters.md index 8b624f60..b6e724ee 100644 --- a/docs/presentation/working-with-slide-masters.md +++ b/docs/presentation/working-with-slide-masters.md @@ -10,72 +10,72 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 09/17/2024 ms.localizationpriority: medium --- # Working with slide masters -This topic discusses the Open XML SDK for Office **[SlideMaster](/dotnet/api/documentformat.openxml.presentation.slidemaster)** class and how it relates to the Open XML File Format PresentationML schema. +This topic discusses the Open XML SDK for Office class and how it relates to the Open XML File Format PresentationML schema. ## Slide Masters in PresentationML -The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML \ element used to represent slide layouts in a PresentationML document as follows. +The [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification describes the Open XML PresentationML `` element used to represent slide layouts in a PresentationML document as follows. This element specifies an instance of a slide master slide. Within a slide master slide are contained all elements that describe the objects and their corresponding formatting for within a presentation slide. Within a slide master slide are two main elements. The cSld element specifies the common slide elements such as shapes and their attached text bodies. Then the txStyles element specifies the formatting for the text within each of these shapes. The other properties within a slide master slide specify other properties for within a presentation slide such as color information, headers and footers, as well as timing and transition information for all corresponding presentation slides. -The \ element is the root element of the PresentationML Slide Master part. For more information about the overall structure of the parts and elements that make up a PresentationML document, see [Structure of a PresentationML Document](structure-of-a-presentationml-document.md). +The `` element is the root element of the PresentationML Slide Master part. For more information about the overall structure of the parts and elements that make up a PresentationML document, see [Structure of a PresentationML Document](structure-of-a-presentationml-document.md). -The following table lists the child elements of the \ element used when working with slide masters and the Open XML SDK classes that correspond to them. +The following table lists the child elements of the `` element used when working with slide masters and the Open XML SDK classes that correspond to them. | **PresentationML Element** | **Open XML SDK Class** | |:---------------------------|:---------------------------------------------------------------------------------------------------------------------------| -| \ | [ColorMap](/dotnet/api/documentformat.openxml.presentation.colormap) | -| \ | [CommonSlideData](/dotnet/api/documentformat.openxml.presentation.commonslidedata) | -| \ | [ExtensionListWithModification](/dotnet/api/documentformat.openxml.presentation.extensionlistwithmodification) | -| \ | [HeaderFooter](/dotnet/api/documentformat.openxml.presentation.headerfooter) | -| \ | [SlideLayoutIdList](/dotnet/api/documentformat.openxml.presentation.slidelayoutidlist) | -| \ | [Timing](/dotnet/api/documentformat.openxml.presentation.timing) | -| \ | [Transition](/dotnet/api/documentformat.openxml.presentation.transition) | -| \ | [TextStyles](/dotnet/api/documentformat.openxml.presentation.textstyles) | +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | +| `` | | The following table from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification describes the attributes of the \ element. +specification describes the attributes of the `` element. | **Attributes** | **Description** | |----------------------------|----------------------------------------------------| -| preserve (Preserve Slide Master) | Specifies whether the corresponding slide layout is deleted when all the slides that follow that layout are deleted. If this attribute is not specified then a value of **false** should be assumed by the generating application. This would mean that the slide would in fact be deleted if no slides within the presentation were related to it.
The possible values for this attribute are defined by the W3C XML Schema **Boolean** data type. | +| preserve (Preserve Slide Master) | Specifies whether the corresponding slide layout is deleted when all the slides that follow that layout are deleted. If this attribute is not specified then a value of `false` should be assumed by the generating application. This would mean that the slide would in fact be deleted if no slides within the presentation were related to it.
The possible values for this attribute are defined by the W3C XML Schema `Boolean` data type. | ## Open XML SDK SlideMaster Class -The Open XML SDK**SlideMaster** class -represents the \ element defined in the Open XML File Format -schema for PresentationML documents. Use the **SlideMaster** class to manipulate individual -\ elements in a PresentationML document. +The Open XML SDK`SlideMaster` class +represents the `` element defined in the Open XML File Format +schema for PresentationML documents. Use the `SlideMaster` class to manipulate individual +`` elements in a PresentationML document. -Classes that represent child elements of the \ element and -that are therefore commonly associated with the **SlideMaster** class are shown in the following +Classes that represent child elements of the `` element and +that are therefore commonly associated with the `SlideMaster` class are shown in the following list. ### ColorMapOverride Class -The **ColorMapOverride** class corresponds to the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: +The `ColorMapOverride` class corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `` element: -This element provides a mechanism with which to override the color schemes listed within the \ element. If the \ child element is present, the color scheme defined by the master is used. If the \ child element is present, it defines a new color scheme specific to the parent notes slide, presentation slide, or slide layout. +This element provides a mechanism with which to override the color schemes listed within the `` element. If the `` child element is present, the color scheme defined by the master is used. If the `` child element is present, it defines a new color scheme specific to the parent notes slide, presentation slide, or slide layout. ### CommonSlideData Class -The **CommonSlideData** class corresponds to the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: +The `CommonSlideData` class corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `` element: -This element specifies a container for the type of slide information that is relevant to all of the slide types. All slides share a common set of properties that is independent of the slide type; the description of these properties for any particular slide is stored within the slide's \ container. Slide data specific to the slide type indicated by the parent element is stored elsewhere. +This element specifies a container for the type of slide information that is relevant to all of the slide types. All slides share a common set of properties that is independent of the slide type; the description of these properties for any particular slide is stored within the slide's `` container. Slide data specific to the slide type indicated by the parent element is stored elsewhere. -The actual data in \ describe only the particular parent slide; it is only the type of information stored that is common across all slides. +The actual data in `` describe only the particular parent slide; it is only the type of information stored that is common across all slides. ### ExtensionListWithModification Class -The **ExtensionListWithModification** class corresponds to the \element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: +The `ExtensionListWithModification` class corresponds to the ``element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `` element: -This element specifies the extension list with modification ability within which all future extensions of element type \ are defined. The extension list along with corresponding future extensions is used to extend the storage capabilities of the PresentationML framework. This allows for various new kinds of data to be stored natively within the +This element specifies the extension list with modification ability within which all future extensions of element type `` are defined. The extension list along with corresponding future extensions is used to extend the storage capabilities of the PresentationML framework. This allows for various new kinds of data to be stored natively within the framework. > [!NOTE] @@ -83,31 +83,31 @@ framework. ### HeaderFooter Class -The **HeaderFooter** class corresponds to the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: +The `HeaderFooter` class corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `` element: This element specifies the header and footer information for a slide. Headers and footers consist of placeholders for text that should be consistent across all slides and slide types, such as a date and time, slide numbering, and custom header and footer text. ### SlideLayoutIdList Class -The **SlideLayoutIdList** class corresponds to the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: +The `SlideLayoutIdList` class corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `` element: This element specifies the existence of the slide layout identification list. This list is contained within the slide master and is used to determine which layouts are being used within the slide master file. Each layout within the list of slide layouts has its own identification number and relationship identifier that uniquely identifies it within both the presentation document and the particular master slide within which it is used. ### Timing Class -The **Timing** class corresponds to the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: +The `Timing` class corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `` element: -This element specifies the timing information for handling all animations and timed events within the corresponding slide. This information is tracked via time nodes within the \ element. More information on the specifics of these time nodes and how they are to be defined can be found within the Animation section of the PresentationML framework. +This element specifies the timing information for handling all animations and timed events within the corresponding slide. This information is tracked via time nodes within the `` element. More information on the specifics of these time nodes and how they are to be defined can be found within the Animation section of the PresentationML framework. ### Transition Class -The **Transition** class corresponds to the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: +The `Transition` class corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `` element: This element specifies the kind of slide transition that should be used to transition to the current slide from the previous slide. That is, the transition information is stored on the slide that appears after the transition is complete. ### TextStyles Class -The **TextStyles** class corresponds to the \ element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the \ element: +The `TextStyles` class corresponds to the `` element. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `` element: This element specifies the text styles within a slide master. Within this element is the styling information for title text, the body text and other slide text as well. This element is only for use within the Slide Master and thus sets the text styles for the corresponding presentation slides. @@ -122,9 +122,9 @@ Consider the case where we would like to specify the title text for a master sli - vv + - + @@ -138,22 +138,22 @@ In the previous example the title text is set according to the above formatting ## Working with the SlideMaster Class -As shown in the Open XML SDK code sample that follows, every instance of the **SlideMaster** class is associated with an instance of the **[SlideMasterPart](/dotnet/api/documentformat.openxml.packaging.slidemasterpart)** class, which represents a slide master part, one of the required parts of a PresentationML presentation file package. Each **SlideMaster** class instance must also be associated with instances of the **[SlideLayout](/dotnet/api/documentformat.openxml.presentation.slidelayout)** and <**[Slide](/dotnet/api/documentformat.openxml.presentation.slide)** classes, which are in turn associated with similarly named required presentation parts, represented by the **[SlideLayoutPart](/dotnet/api/documentformat.openxml.packaging.slidelayoutpart)** and **[SlidePart](/dotnet/api/documentformat.openxml.packaging.slidepart)** classes. +As shown in the Open XML SDK code sample that follows, every instance of the `SlideMaster` class is associated with an instance of the class, which represents a slide master part, one of the required parts of a PresentationML presentation file package. Each `SlideMaster` class instance must also be associated with instances of the and classes, which are in turn associated with similarly named required presentation parts, represented by the and classes. -The **SlideMaster** class, which represents the \ element, is therefore also associated with a series of other classes that represent the child elements of the \ -element. Among these classes, as shown in the following code sample, are the **CommonSlideData** class, the **ColorMap** class, the **[ShapeTree](/dotnet/api/documentformat.openxml.presentation.shapetree)** class, and the **[Shape](/dotnet/api/documentformat.openxml.presentation.shape)** class. +The `SlideMaster` class, which represents the `` element, is therefore also associated with a series of other classes that represent the child elements of the `` +element. Among these classes, as shown in the following code sample, are the `CommonSlideData` class, the `ColorMap` class, the class, and the class. ## Open XML SDK Code Example -The following method from the article [How to: Create a presentation document by providing a file name](./how-to-create-a-presentation-document-by-providing-a-file-name.md) adds a new slidemaster part to an existing presentation and creates an instance of an Open XML SDK**SlideMaster** class in the new slide master part. The **SlideMaster** class constructor creates instances of the **CommonSlideData** class and the **ColorMap**, **SlideLayoutIdList**, and **TextStyles** classes. The **CommonSlideData** class constructor creates an instance of the **[ShapeTree](/dotnet/api/documentformat.openxml.presentation.shapetree)** class, whose constructor in turn creates additional class instances: an instance of the **[NonVisualGroupShapeProperties](/dotnet/api/documentformat.openxml.presentation.nonvisualgroupshapeproperties)** class, an instance of the **[GroupShapeProperties](/dotnet/api/documentformat.openxml.presentation.groupshapeproperties)** class, and an instance of the **[Shape](/dotnet/api/documentformat.openxml.presentation.shape)** class, among others. +The following method from the article [How to: Create a presentation document by providing a file name](./how-to-create-a-presentation-document-by-providing-a-file-name.md) adds a new slidemaster part to an existing presentation and creates an instance of an Open XML SDK `SlideMaster` class in the new slide master part. The `SlideMaster` class constructor creates instances of the `CommonSlideData` class and the `ColorMap`, `SlideLayoutIdList`, and `TextStyles` classes. The `CommonSlideData` class constructor creates an instance of the class, whose constructor in turn creates additional class instances: an instance of the class, an instance of the class, and an instance of the class, among others. -The namespace represented by the letter *P* in the code is the **[DocumentFormat.OpenXml.Presentation](/dotnet/api/documentformat.openxml.presentation)** namespace. +The namespace represented by the letter *P* in the code is the namespace. ### [C#](#tab/cs) -[!code-csharp[](../../samples/presentation/working_with_slide_masters/cs/Program.cs)] +[!code-csharp[](../../samples/presentation/create_by_providing_a_file_name/cs/Program.cs#snippet99)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/presentation/working_with_slide_masters/vb/Program.vb)] +[!code-vb[](../../samples/presentation/create_by_providing_a_file_name/vb/Program.vb#snippet99)] ## Generated PresentationML @@ -222,6 +222,9 @@ When the Open XML SDK code is run, the following XML is written to the Presentat ## See also [About the Open XML SDK for Office](../about-the-open-xml-sdk.md) + [How to: Create a Presentation by Providing a File Name](how-to-create-a-presentation-document-by-providing-a-file-name.md) + [How to: Insert a new slide into a presentation](how-to-insert-a-new-slide-into-a-presentation.md) + [How to: Delete a slide from a presentation](how-to-delete-a-slide-from-a-presentation.md) 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 cc152263..6a0b9776 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,13 +11,13 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 01/10/2024 +ms.date: 01/09/2025 ms.localizationpriority: high --- # Add custom UI to a spreadsheet document -This topic shows how to use the classes in the Open XML SDK for Office to programmatically add custom UI, modifying the ribbon, to a Microsoft Excel worksheet. It contains an example **AddCustomUI** method to illustrate +This topic shows how to use the classes in the Open XML SDK for Office to programmatically add custom UI, modifying the ribbon, to a Microsoft Excel worksheet. It contains an example `AddCustomUI` method to illustrate this task. @@ -25,7 +25,7 @@ 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 to create the customization for you. For more information about customizing the ribbon by using the Visual Studio Ribbon Designer, see [Ribbon Designer](/visualstudio/vsto/ribbon-designer) and [Walkthrough: Creating a Custom Tab by Using the Ribbon Designer](/visualstudio/vsto/walkthrough-creating-a-custom-tab-by-using-the-ribbon-designer). -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). The samples below are the xml strings used in 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. +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). The samples below are the xml strings used in 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. ### [C#](#tab/cs-xml) [!code-csharp[](../../samples/spreadsheet/add_custom_ui/cs/Program.cs#snippet4)] @@ -55,15 +55,15 @@ For this demonstration, the ribbon customization includes a button that attempts ## AddCustomUI Method -The **AddCustomUI** method accepts two parameters: +The `AddCustomUI` method accepts two parameters: - *filename* — A string that contains a file name that specifies the workbook to modify. -- customUIContent*—A string that contains the custom content (that is, the XML markup that describes the customization). +- *customUIContent* — A string that contains the custom content (that is, the XML markup that describes the customization). ## Interact with the Workbook -The sample method, **AddCustomUI**, starts by opening the requested workbook in read/write mode, as shown in the following code. +The sample method, `AddCustomUI`, starts by opening the requested workbook in read/write mode, as shown in the following code. ### [C#](#tab/cs-2) [!code-csharp[](../../samples/spreadsheet/add_custom_ui/cs/Program.cs#snippet1)] @@ -85,7 +85,7 @@ Next, as shown in the following code, the sample method attempts to retrieve a r ## Add the Customization -Given a reference to the ribbon extensibility part, the following code finishes by setting the part's **CustomUI** property to a new [CustomUI](/dotnet/api/documentformat.openxml.office.customui.customui) object that contains the supplied customization. Once the customization is in place, the code saves the custom UI. +Given a reference to the ribbon extensibility part, the following code finishes by setting the part's `CustomUI` property to a new object that contains the supplied customization. Once the customization is in place, the code saves the custom UI. ### [C#](#tab/cs-4) [!code-csharp[](../../samples/spreadsheet/add_custom_ui/cs/Program.cs#snippet3)] @@ -96,7 +96,7 @@ Given a reference to the ribbon extensibility part, the following code finishes ## Sample Code -The following is the complete **AddCustomUI** code sample in C\# and Visual Basic. The first argument passed to the **AddCustomUI** should be the absolute +The following is the complete `AddCustomUI` code sample in C\# and Visual Basic. The first argument passed to the `AddCustomUI` should be the absolute path to the AddCustomUI.xlsm file created from the instructions above. ### [C#](#tab/cs) @@ -104,6 +104,7 @@ path to the AddCustomUI.xlsm file created from the instructions above. ### [Visual Basic](#tab/vb) [!code-vb[](../../samples/spreadsheet/add_custom_ui/vb/Program.vb#snippet0)] +*** ## See also diff --git a/docs/spreadsheet/how-to-calculate-the-sum-of-a-range-of-cells-in-a-spreadsheet-document.md b/docs/spreadsheet/how-to-calculate-the-sum-of-a-range-of-cells-in-a-spreadsheet-document.md index efcdac7d..857cdaf1 100644 --- a/docs/spreadsheet/how-to-calculate-the-sum-of-a-range-of-cells-in-a-spreadsheet-document.md +++ b/docs/spreadsheet/how-to-calculate-the-sum-of-a-range-of-cells-in-a-spreadsheet-document.md @@ -9,7 +9,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 01/04/2024 +ms.date: 01/09/2025 ms.localizationpriority: high --- @@ -21,14 +21,14 @@ This topic shows how to use the classes in the Open XML SDK for Office to calcul ## How the Sample Code Works -The sample code starts by passing in to the method **CalculateSumOfCellRange** a parameter that represents the full path to the source **SpreadsheetML** file, a parameter that represents the name of the worksheet that contains the cells, a parameter that represents the name of the first cell in the contiguous range, a parameter that represent the name of the last cell in the contiguous range, and a parameter that represents the name of the cell where you want the result displayed. +The sample code starts by passing in to the method `CalculateSumOfCellRange` a parameter that represents the full path to the source `SpreadsheetML` file, a parameter that represents the name of the worksheet that contains the cells, a parameter that represents the name of the first cell in the contiguous range, a parameter that represent the name of the last cell in the contiguous range, and a parameter that represents the name of the cell where you want the result displayed. -The code then opens the file for editing as a **SpreadsheetDocument** document package for read/write access, the code gets the specified **Worksheet** object. It then gets the index of the row for the first and last cell in the contiguous range by calling the **GetRowIndex** method. It gets the name of the column for the first and last cell in the contiguous range by calling the **GetColumnName** method. +The code then opens the file for editing as a `SpreadsheetDocument` document package for read/write access, the code gets the specified `Worksheet` object. It then gets the index of the row for the first and last cell in the contiguous range by calling the `GetRowIndex` method. It gets the name of the column for the first and last cell in the contiguous range by calling the `GetColumnName` method. -For each **Row** object within the contiguous range, the code iterates through each **Cell** object and determines if the column of the cell is within the contiguous -range by calling the **CompareColumn** method. If the cell is within the contiguous range, the code adds the value of the cell to the sum. Then it gets the **SharedStringTablePart** object if it exists. If it does not exist, it creates one using the **[AddNewPart](/dotnet/api/documentformat.openxml.packaging.openxmlpartcontainer.addnewpart)** method. It inserts the result into the **SharedStringTablePart** object by calling the **InsertSharedStringItem** method. +For each `Row` object within the contiguous range, the code iterates through each `Cell` object and determines if the column of the cell is within the contiguous +range by calling the `CompareColumn` method. If the cell is within the contiguous range, the code adds the value of the cell to the sum. Then it gets the `SharedStringTablePart` object if it exists. If it does not exist, it creates one using the method. It inserts the result into the `SharedStringTablePart` object by calling the `InsertSharedStringItem` method. -The code inserts a new cell for the result into the worksheet by calling the **InsertCellInWorksheet** method and set the value of the cell. For more information, see [how to insert a cell in a spreadsheet](how-to-insert-text-into-a-cell-in-a-spreadsheet.md#how-the-sample-code-works), and then save the worksheet. +The code inserts a new cell for the result into the worksheet by calling the `InsertCellInWorksheet` method and sets the value of the cell. For more information, see [how to insert a cell in a spreadsheet](how-to-insert-text-into-a-cell-in-a-spreadsheet.md#how-the-sample-code-works). ### [C#](#tab/cs-1) [!code-csharp[](../../samples/spreadsheet/calculate_the_sum_of_a_range_of_cells/cs/Program.cs#snippet1)] @@ -37,7 +37,7 @@ The code inserts a new cell for the result into the worksheet by calling the **I *** To get the row index the code passes a parameter that represents the name of the cell, and creates a new regular expression to match the row -index portion of the cell name. For more information about regular expressions, see [Regular Expression Language Elements](/dotnet/standard/base-types/regular-expression-language-quick-reference). It gets the row index by calling the **[Regex.Match](/dotnet/api/system.text.regularexpressions.regex.match)** method, and then returns the row index. +index portion of the cell name. For more information about regular expressions, see [Regular Expression Language Elements](/dotnet/standard/base-types/regular-expression-language-quick-reference). It gets the row index by calling the method, and then returns the row index. ### [C#](#tab/cs-2) [!code-csharp[](../../samples/spreadsheet/calculate_the_sum_of_a_range_of_cells/cs/Program.cs#snippet2)] @@ -46,7 +46,7 @@ index portion of the cell name. For more information about regular expressions, *** -The code then gets the column name by passing a parameter that represents the name of the cell, and creates a new regular expression to match the column name portion of the cell name. This regular expression matches any combination of uppercase or lowercase letters. It gets the column name by calling the **[Regex.Match](/dotnet/api/system.text.regularexpressions.regex.match)** method, and then returns the column name. +The code then gets the column name by passing a parameter that represents the name of the cell, and creates a new regular expression to match the column name portion of the cell name. This regular expression matches any combination of uppercase or lowercase letters. It gets the column name by calling the method, and then returns the column name. ### [C#](#tab/cs-3) [!code-csharp[](../../samples/spreadsheet/calculate_the_sum_of_a_range_of_cells/cs/Program.cs#snippet3)] @@ -55,7 +55,7 @@ The code then gets the column name by passing a parameter that represents the na *** -To compare two columns the code passes in two parameters that represent the columns to compare. If the first column is longer than the second column, it returns 1. If the second column is longer than the first column, it returns -1. Otherwise, it compares the values of the columns using the **[Compare](/dotnet/api/system.string.compare)** and returns the result. +To compare two columns the code passes in two parameters that represent the columns to compare. If the first column is longer than the second column, it returns 1. If the second column is longer than the first column, it returns -1. Otherwise, it compares the values of the columns using the and returns the result. ### [C#](#tab/cs-4) [!code-csharp[](../../samples/spreadsheet/calculate_the_sum_of_a_range_of_cells/cs/Program.cs#snippet4)] @@ -64,7 +64,7 @@ To compare two columns the code passes in two parameters that represent the colu *** -To insert a **SharedStringItem**, the code passes in a parameter that represents the text to insert into the cell and a parameter that represents the **SharedStringTablePart** object for the spreadsheet. If the **ShareStringTablePart** object does not contain a **[SharedStringTable](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringtable)** object then it creates one. If the text already exists in the **ShareStringTable** object, then it returns the index for the **[SharedStringItem](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringitem)** object that represents the text. If the text does not exist, create a new **SharedStringItem** object that represents the text. It then returns the index for the **SharedStringItem** object that represents the text. +To insert a `SharedStringItem`, the code passes in a parameter that represents the text to insert into the cell and a parameter that represents the `SharedStringTablePart` object for the spreadsheet. If the `ShareStringTablePart` object does not contain a object then it creates one. If the text already exists in the `ShareStringTable` object, then it returns the index for the object that represents the text. If the text does not exist, create a new `SharedStringItem` object that represents the text. It then returns the index for the `SharedStringItem` object that represents the text. ### [C#](#tab/cs-5) [!code-csharp[](../../samples/spreadsheet/calculate_the_sum_of_a_range_of_cells/cs/Program.cs#snippet5)] @@ -73,7 +73,7 @@ To insert a **SharedStringItem**, the code passes in a parameter that represents *** -The final step is to insert a cell into the worksheet. The code does that by passing in parameters that represent the name of the column and the number of the row of the cell, and a parameter that represents the worksheet that contains the cell. If the specified row does not exist, it creates the row and append it to the worksheet. If the specified column exists, it finds the cell that matches the row in that column and returns the cell. If the specified column does not exist, it creates the column and inserts it into the worksheet. It then determines where to insert the new cell in the column by iterating through the row elements to find the cell that comes directly after the specified row, in sequential order. It saves this row in the **refCell** variable. It inserts the new cell before the cell referenced by **refCell** using the **[InsertBefore](/dotnet/api/documentformat.openxml.openxmlcompositeelement.insertbefore)** method. It then returns the new **Cell** object. +The final step is to insert a cell into the worksheet. The code does that by passing in parameters that represent the name of the column and the number of the row of the cell, and a parameter that represents the worksheet that contains the cell. If the specified row does not exist, it creates the row and append it to the worksheet. If the specified column exists, it finds the cell that matches the row in that column and returns the cell. If the specified column does not exist, it creates the column and inserts it into the worksheet. It then determines where to insert the new cell in the column by iterating through the row elements to find the cell that comes directly after the specified row, in sequential order. It saves this row in the `refCell` variable. It inserts the new cell before the cell referenced by `refCell` using the method. It then returns the new `Cell` object. ### [C#](#tab/cs-6) [!code-csharp[](../../samples/spreadsheet/calculate_the_sum_of_a_range_of_cells/cs/Program.cs#snippet6)] @@ -90,6 +90,7 @@ The following is the complete sample code in both C\# and Visual Basic. ### [Visual Basic](#tab/vb) [!code-vb[](../../samples/spreadsheet/calculate_the_sum_of_a_range_of_cells/vb/Program.vb#snippet0)] +*** ## See also diff --git a/docs/spreadsheet/how-to-copy-a-worksheet-with-sax.md b/docs/spreadsheet/how-to-copy-a-worksheet-with-sax.md new file mode 100644 index 00000000..e21192c8 --- /dev/null +++ b/docs/spreadsheet/how-to-copy-a-worksheet-with-sax.md @@ -0,0 +1,158 @@ +--- +api_name: +- Microsoft.Office.DocumentFormat.OpenXML.Packaging +api_type: +- schema +ms.assetid: 2ad4855c-1c83-4dab-b93f-2bae13fac644 +title: 'How to: Copy a Worksheet Using SAX (Simple API for XML)' +ms.suite: office + +ms.author: o365devx +author: o365devx +ms.topic: conceptual +ms.date: 04/01/2025 +ms.localizationpriority: high +--- +# Copy a Worksheet Using SAX (Simple API for XML) + +This topic shows how to use the the Open XML SDK for Office to programmatically copy a large worksheet +using SAX (Simple API for XML). For more information about the basic structure of a `SpreadsheetML` +document, see [Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md). + +------------------------------------ +## Why Use the SAX Approach? + +The Open XML SDK provides two ways to parse Office Open XML files: the Document Object Model (DOM) and +the Simple API for XML (SAX). The DOM approach is designed to make it easy to query and parse Open XML +files by using strongly-typed classes. However, the DOM approach requires loading entire Open XML parts into +memory, which can lead to slower processing and `Out of Memory` exceptions when working with very large parts. +The SAX approach reads in the XML in an Open XML part one element at a time without reading in the entire part +into memory giving noncached, forward-only access to XML data, which makes it a better choice when reading +very large parts, such as a with hundreds of thousands of rows. + +## Using the DOM Approach + +Using the DOM approach, we can take advantage of the Open XML SDK's strongly typed classes. The first step +is to access the package's `WorksheetPart` and make sure that it is not null. + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/spreadsheet/copy_worksheet_with_sax/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/spreadsheet/copy_worksheet_with_sax/vb/Program.vb#snippet1)] +*** + +Once it is determined that the `WorksheetPart` to be copied is not null, add a new `WorksheetPart` to copy it to. +Then clone the `WorksheetPart`'s and assign the cloned +`Worksheet` to the new `WorksheetPart`'s Worksheet property. + +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/spreadsheet/copy_worksheet_with_sax/cs/Program.cs#snippet2)] + +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/spreadsheet/copy_worksheet_with_sax/vb/Program.vb#snippet2)] +*** + +At this point, the new `WorksheetPart` has been added, but a new +element must be added to the `WorkbookPart`'s 's +child elements for it to display. To do this, first find the new `WorksheetPart`'s Id and +create a new sheet Id by incrementing the `Sheets` count by one then append a new `Sheet` +child to the `Sheets` element. With this, the copied Worksheet is added to the file. + +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/spreadsheet/copy_worksheet_with_sax/cs/Program.cs#snippet3)] + +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/spreadsheet/copy_worksheet_with_sax/vb/Program.vb#snippet3)] +*** + +## Using the SAX Approach + +The SAX approach works on parts, so using the SAX approach, the first step is the same. +Access the package's and make sure +that it is not null. + +### [C#](#tab/cs-4) +[!code-csharp[](../../samples/spreadsheet/copy_worksheet_with_sax/cs/Program.cs#snippet4)] + +### [Visual Basic](#tab/vb-4) +[!code-vb[](../../samples/spreadsheet/copy_worksheet_with_sax/vb/Program.vb#snippet4)] +*** + +With SAX, we don't have access to the +method. So instead, start by adding a new `WorksheetPart` to the `WorkbookPart`. + +### [C#](#tab/cs-5) +[!code-csharp[](../../samples/spreadsheet/copy_worksheet_with_sax/cs/Program.cs#snippet5)] + +### [Visual Basic](#tab/vb-5) +[!code-vb[](../../samples/spreadsheet/copy_worksheet_with_sax/vb/Program.vb#snippet5)] +*** + +Then create an instance of the with the +original worksheet part and an instance of the +with the newly created worksheet part. + +### [C#](#tab/cs-6) +[!code-csharp[](../../samples/spreadsheet/copy_worksheet_with_sax/cs/Program.cs#snippet6)] + +### [Visual Basic](#tab/vb-6) +[!code-vb[](../../samples/spreadsheet/copy_worksheet_with_sax/vb/Program.vb#snippet6)] +*** + +Then read the elements one by one with the +method. If the element is a the inner text +needs to be explicitly added using the +method to read the text, because the +does not write the inner text of an element. For other elements we only need to use the `WriteStartElement` +method, because we don't need the other element's inner text. + +### [C#](#tab/cs-7) +[!code-csharp[](../../samples/spreadsheet/copy_worksheet_with_sax/cs/Program.cs#snippet7)] + +### [Visual Basic](#tab/vb-7) +[!code-vb[](../../samples/spreadsheet/copy_worksheet_with_sax/vb/Program.vb#snippet7)] +*** + +At this point, the worksheet part has been copied to the newly added part, but as with the DOM +approach, we still need to add a `Sheet` to the `Workbook`'s `Sheets` element. Because +the SAX approach gives noncached, **forward-only** access to XML data, it is only possible to +prepend element children, which in this case would add the new worksheet to the beginning instead +of the end, changing the order of the worksheets. So the DOM approach is +necessary here, because we want to append not prepend the new `Sheet` and since the `WorkbookPart` is +not usually a large part, the performance gains would be minimal. + +### [C#](#tab/cs-8) +[!code-csharp[](../../samples/spreadsheet/copy_worksheet_with_sax/cs/Program.cs#snippet8)] + +### [Visual Basic](#tab/vb-8) +[!code-vb[](../../samples/spreadsheet/copy_worksheet_with_sax/vb/Program.vb#snippet8)] +*** + +## Sample Code + +Below is the sample code for both the DOM and SAX approaches to copying the data from one sheet +to a new one and adding it to the Spreadsheet document. While the DOM approach is simpler +and in many cases the preferred choice, with very large documents the SAX approach is better +given that it is faster and can prevent `Out of Memory` exceptions. To see the difference, +create a spreadsheet document with many (10,000+) rows and check the results of the + to check the difference in execution time. Increase the +number of rows to 100,000+ to see even more significant performance gains. + +### DOM Approach + +### [C#](#tab/cs-0) +[!code-csharp[](../../samples/spreadsheet/copy_worksheet_with_sax/cs/Program.cs#snippet0)] + +### [Visual Basic](#tab/vb-0) +[!code-vb[](../../samples/spreadsheet/copy_worksheet_with_sax/vb/Program.vb#snippet0)] +*** + +### SAX Approach + +### [C#](#tab/cs-99) +[!code-csharp[](../../samples/spreadsheet/copy_worksheet_with_sax/cs/Program.cs#snippet99)] + +### [Visual Basic](#tab/vb-99) +[!code-vb[](../../samples/spreadsheet/copy_worksheet_with_sax/vb/Program.vb#snippet99)] +*** \ No newline at end of file diff --git a/docs/spreadsheet/how-to-create-a-spreadsheet-document-by-providing-a-file-name.md b/docs/spreadsheet/how-to-create-a-spreadsheet-document-by-providing-a-file-name.md index 69e45658..d1078035 100644 --- a/docs/spreadsheet/how-to-create-a-spreadsheet-document-by-providing-a-file-name.md +++ b/docs/spreadsheet/how-to-create-a-spreadsheet-document-by-providing-a-file-name.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 01/04/2024 +ms.date: 01/09/2025 ms.localizationpriority: high --- # Create a spreadsheet document by providing a file name @@ -22,33 +22,33 @@ Office to programmatically create a spreadsheet document. -------------------------------------------------------------------------------- -## Creating a SpreadsheetDocument Object -In the Open XML SDK, the **[SpreadsheetDocument](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument)** class represents an +## Creating a SpreadsheetDocument Object + +In the Open XML SDK, the class represents an Excel document package. To create an Excel document, create an instance -of the **SpreadsheetDocument** class and +of the `SpreadsheetDocument` class and populate it with parts. At a minimum, the document must have a workbook part that serves as a container for the document, and at least one worksheet part. The text is represented in the package as XML using -**SpreadsheetML** markup. +`SpreadsheetML` markup. -To create the class instance, call the [Create(Package, SpreadsheetDocumentType)](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.create) -method. Several **Create** methods are +To create the class instance, call the +method. Several `Create` methods are provided, each with a different signature. The sample code in this topic -uses the **Create** method with a signature -that requires two parameters. The first parameter, **package**, takes a full +uses the `Create` method with a signature +that requires two parameters. The first parameter, `package`, takes a full path string that represents the document that you want to create. The -second parameter, *type*, is a member of the [SpreadsheetDocumentType](/dotnet/api/documentformat.openxml.spreadsheetdocumenttype) enumeration. This +second parameter, *type*, is a member of the enumeration. This parameter represents the document type. For example, there are different -members of the **SpreadsheetDocumentType** +members of the `SpreadsheetDocumentType` enumeration for add-ins, templates, workbooks, and macro-enabled templates and workbooks. > [!NOTE] -> Select the appropriate **SpreadsheetDocumentType** and ensure that the persisted file has the correct, matching file name extension. If the **SpreadsheetDocumentType** does not match the file name extension, an error occurs when you open the file in Excel. +> Select the appropriate `SpreadsheetDocumentType` and ensure that the persisted file has the correct, matching file name extension. If the `SpreadsheetDocumentType` does not match the file name extension, an error occurs when you open the file in Excel. -The following code example calls the **Create** -method. +The following code example calls the `Create` method. ### [C#](#tab/cs-0) [!code-csharp[](../../samples/spreadsheet/create_by_providing_a_file_name/cs/Program.cs#snippet1)] @@ -58,7 +58,8 @@ method. When you have created the Excel document package, you can add parts to -it. To add the workbook part you call the [AddWorkbookPart()](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.addworkbookpart) method of the **SpreadsheetDocument** class. +it. To add the workbook part you call the +method of the `SpreadsheetDocument` class. ### [C#](#tab/cs-100) [!code-csharp[](../../samples/spreadsheet/create_by_providing_a_file_name/cs/Program.cs#snippet2)] @@ -67,13 +68,14 @@ it. To add the workbook part you call the [AddWorkbookPart()](/dotnet/api/docume *** A workbook part must -have at least one worksheet. To add a worksheet, create a new **Sheet**. When you create a new **Sheet**, associate the **Sheet** with the [Workbook](/dotnet/api/documentformat.openxml.spreadsheet.workbook) by passing the **Id**, **SheetId** and **Name** parameters. Use the -[GetIdOfPart(OpenXmlPart)](/dotnet/api/documentformat.openxml.packaging.openxmlpartcontainer.getidofpart) method to get the -**Id** of the **Sheet**. Then add the new sheet to the **Sheet** collection by calling the [Append([])](/dotnet/api/documentformat.openxml.openxmlelement.append) method of the [Sheets](/dotnet/api/documentformat.openxml.spreadsheet.sheets) class. - -To create the basic document structure using the Open XML SDK, instantiate the **Workbook** class, assign it -to the [WorkbookPart](/dotnet/api/documentformat.openxml.spreadsheet.workbook.workbookpart) property of the main document -part, and then add instances of the [WorksheetPart](/dotnet/api/documentformat.openxml.spreadsheet.worksheet.worksheetpart), **Worksheet**, and **Sheet**. The following code example +have at least one worksheet. To add a worksheet, create a new `Sheet`. When you create a new `Sheet`, associate the `Sheet` with the by passing the `Id`, `SheetId` and `Name` parameters. Use the + method to get the +`Id` of the `Sheet`. Then add the new sheet to the `Sheet` collection by calling the + method of the class. + +To create the basic document structure using the Open XML SDK, instantiate the `Workbook` class, assign it +to the property of the main document +part, and then add instances of the , `Worksheet`, and `Sheet`. The following code example creates a new worksheet, associates the worksheet, and appends the worksheet to the workbook. @@ -85,7 +87,7 @@ worksheet to the workbook. -------------------------------------------------------------------------------- -## Sample Code +## Sample Code Following is the complete sample code in both C\# and Visual Basic. @@ -94,9 +96,10 @@ Following is the complete sample code in both C\# and Visual Basic. ### [Visual Basic](#tab/vb) [!code-vb[](../../samples/spreadsheet/create_by_providing_a_file_name/vb/Program.vb#snippet0)] +*** -------------------------------------------------------------------------------- -## See also +## See also - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) 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 7e864ecb..d9f74b33 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 @@ -10,7 +10,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 01/04/2024 +ms.date: 01/09/2025 ms.localizationpriority: high --- # Delete text from a cell in a spreadsheet document @@ -23,7 +23,7 @@ programmatically. ## How the sample code works -In the following code example, you delete text from a cell in a [SpreadsheetDocument](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument) document package. Then, you verify if other cells within the spreadsheet document still reference the text removed from the row, and if they do not, you remove the text from the [SharedStringTablePart](/dotnet/api/documentformat.openxml.packaging.sharedstringtablepart) object by using the [Remove](/dotnet/api/documentformat.openxml.openxmlelement.remove) method. Then you clean up the **SharedStringTablePart** object by calling the **RemoveSharedStringItem** method. +In the following code example, you delete text from a cell in a document package. Then, you verify if other cells within the spreadsheet document still reference the text removed from the row, and if they do not, you remove the text from the object by using the method. Then you clean up the `SharedStringTablePart` object by calling the `RemoveSharedStringItem` method. ### [C#](#tab/cs-1) [!code-csharp[](../../samples/spreadsheet/delete_text_from_a_cell/cs/Program.cs#snippet1)] @@ -32,7 +32,7 @@ In the following code example, you delete text from a cell in a [SpreadsheetDocu *** -In the following code example, you verify that the cell specified by the column name and row index exists. If so, the code returns the cell; otherwise, it returns **null**. +In the following code example, you verify that the cell specified by the column name and row index exists. If so, the code returns the cell; otherwise, it returns `null`. ### [C#](#tab/cs-2) [!code-csharp[](../../samples/spreadsheet/delete_text_from_a_cell/cs/Program.cs#snippet2)] @@ -42,20 +42,20 @@ In the following code example, you verify that the cell specified by the column In the following code example, you verify if other cells within the -spreadsheet document reference the text specified by the **shareStringId** parameter. If they do not reference -the text, you remove it from the **SharedStringTablePart** object. You do that by +spreadsheet document reference the text specified by the `shareStringId` parameter. If they do not reference +the text, you remove it from the `SharedStringTablePart` object. You do that by passing a parameter that represents the ID of the text to remove and a -parameter that represents the **SpreadsheetDocument** document package. Then you -iterate through each **Worksheet** object and -compare the contents of each **Cell** object to +parameter that represents the `SpreadsheetDocument` document package. Then you +iterate through each `Worksheet` object and +compare the contents of each `Cell` object to the shared string ID. If other cells within the spreadsheet document -still reference the [SharedStringItem](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringitem) object, you do not remove -the item from the **SharedStringTablePart** +still reference the object, you do not remove +the item from the `SharedStringTablePart` object. If other cells within the spreadsheet document no longer -reference the **SharedStringItem** object, you -remove the item from the **SharedStringTablePart** object. Then you iterate -through each **Worksheet** object and **Cell** object and refresh the shared string -references. Finally, you save the worksheet and the [SharedStringTable](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringtable) object. +reference the `SharedStringItem` object, you +remove the item from the `SharedStringTablePart` object. Then you iterate +through each `Worksheet` object and `Cell` object and refresh the shared string +references. ### [C#](#tab/cs-3) [!code-csharp[](../../samples/spreadsheet/delete_text_from_a_cell/cs/Program.cs#snippet3)] diff --git a/docs/spreadsheet/how-to-get-a-column-heading-in-a-spreadsheet.md b/docs/spreadsheet/how-to-get-a-column-heading-in-a-spreadsheet.md index b1b895b7..e754d738 100644 --- a/docs/spreadsheet/how-to-get-a-column-heading-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-get-a-column-heading-in-a-spreadsheet.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 01/03/2024 +ms.date: 01/09/2025 ms.localizationpriority: high --- # Get a column heading in a spreadsheet document @@ -25,10 +25,10 @@ programmatically. ## How the Sample Code Works The code in this how-to consists of three methods (functions in Visual -Basic): **GetColumnHeading**, **GetColumnName**, and **GetRowIndex**. The last two methods are called from -within the **GetColumnHeading** method. +Basic): `GetColumnHeading`, `GetColumnName`, and `GetRowIndex`. The last two methods are called from +within the `GetColumnHeading` method. -The **GetColumnName** method takes the cell +The `GetColumnName` method takes the cell name as a parameter. It parses the cell name to get the column name by creating a regular expression to match the column name portion of the cell name. For more information about regular expressions, see [Regular Expression Language Elements](/dotnet/standard/base-types/regular-expression-language-quick-reference). @@ -40,7 +40,7 @@ cell name. For more information about regular expressions, see [Regular Expressi *** -The **GetRowIndex** method takes the cell name +The `GetRowIndex` method takes the cell name as a parameter. It parses the cell name to get the row index by creating a regular expression to match the row index portion of the cell name. @@ -51,14 +51,14 @@ a regular expression to match the row index portion of the cell name. *** -The **GetColumnHeading** method uses three +The `GetColumnHeading` method uses three parameters, the full path to the source spreadsheet file, the name of the worksheet that contains the specified column, and the name of a cell in the column for which to get the heading. The code gets the name of the column of the specified cell by calling -the **GetColumnName** method. The code also -gets the cells in the column and orders them by row using the **GetRowIndex** method. +the `GetColumnName` method. The code also +gets the cells in the column and orders them by row using the `GetRowIndex` method. ### [C#](#tab/cs-3) [!code-csharp[](../../samples/spreadsheet/get_a_column_heading/cs/Program.cs#snippet3)] @@ -69,7 +69,7 @@ gets the cells in the column and orders them by row using the **GetRowIndex** me If the specified column exists, it gets the first cell in the column using the -[IEnumerable(T).First](/dotnet/api/system.linq.enumerable.first) + method. The first cell contains the heading. Otherwise the specified column does not exist and the method returns `null` / `Nothing` ### [C#](#tab/cs-4) @@ -79,11 +79,11 @@ method. The first cell contains the heading. Otherwise the specified column does *** -If the content of the cell is stored in the [SharedStringTablePart](/dotnet/api/documentformat.openxml.packaging.sharedstringtablepart) object, it gets the +If the content of the cell is stored in the object, it gets the shared string items and returns the content of the column heading using the -[M:System.Int32.Parse(System.String)](/dotnet/api/system.int32.parse) -method. If the content of the cell is not in the [SharedStringTable](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringtable) object, it returns the + +method. If the content of the cell is not in the object, it returns the content of the cell. ### [C#](#tab/cs-5) @@ -102,6 +102,7 @@ Following is the complete sample code in both C\# and Visual Basic. ### [Visual Basic](#tab/vb) [!code-vb[](../../samples/spreadsheet/get_a_column_heading/vb/Program.vb#snippet0)] +*** ## See also diff --git a/docs/spreadsheet/how-to-get-worksheet-information-from-a-package.md b/docs/spreadsheet/how-to-get-worksheet-information-from-a-package.md index 6bf1f4fb..c1fae0ee 100644 --- a/docs/spreadsheet/how-to-get-worksheet-information-from-a-package.md +++ b/docs/spreadsheet/how-to-get-worksheet-information-from-a-package.md @@ -9,7 +9,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 01/03/2024 +ms.date: 01/09/2025 ms.localizationpriority: high --- @@ -21,7 +21,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to progra ## How the Sample Code Works -After you have opened the file for read-only access, you instantiate the **Sheets** class. +After you have opened the file for read-only access, you instantiate the `Sheets` class. ### [C#](#tab/cs-1) [!code-csharp[](../../samples/spreadsheet/get_worksheetformation_from_a_package/cs/Program.cs#snippet1)] @@ -30,7 +30,8 @@ After you have opened the file for read-only access, you instantiate the **Sheet *** -You then you iterate through the **Sheets** collection and display **[OpenXmlElement](/dotnet/api/documentformat.openxml.openxmlelement)** and the **[OpenXmlAttribute](/dotnet/api/documentformat.openxml.openxmlattribute)** in each element. +You then you iterate through the `Sheets` collection and display and the + in each element. ### [C#](#tab/cs-2) [!code-csharp[](../../samples/spreadsheet/get_worksheetformation_from_a_package/cs/Program.cs#snippet2)] 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 f1d32132..01ad0096 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: 12/12/2023 +ms.date: 01/14/2025 ms.localizationpriority: high --- @@ -22,7 +22,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to insert In this how-to, you are going to deal with the row, cell, and cell value elements. Therefore it is useful to familiarize yourself with these elements. The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification -introduces row (\<**row**\>) element. +introduces row (``) element. > The row element expresses information about an entire row of a > worksheet, and contains all cell definitions for a particular row in @@ -46,7 +46,7 @@ introduces row (\<**row**\>) element. ``` -> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following XML Schema code example defines the contents of the row element. @@ -75,7 +75,7 @@ element. ## Cell element The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification -introduces cell (\<**c**\>) element. +introduces cell (``) element. > This collection represents a cell in the worksheet. Information about > the cell's location (reference), value, data type, formatting, and @@ -93,7 +93,7 @@ introduces cell (\<**c**\>) element. ``` -> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following XML Schema code example defines the contents of this element. @@ -118,7 +118,7 @@ element. ## Cell value element The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification -introduces Cell Value (\<**c**\>) element. +introduces Cell Value (``) element. > This element expresses the value contained in a cell. If the cell > contains a string, then this value is an index into the shared string @@ -128,10 +128,10 @@ introduces Cell Value (\<**c**\>) element. > element. > > For applications not wanting to implement the shared string table, an -> "inline string" may be expressed in an \<**is**\> element under \<**c**\> (instead of a \<**v**\> element under \<**c**\>), in the same way a string would be +> "inline string" may be expressed in an `` element under `` (instead of a `` element under ``), in the same way a string would be > expressed in the shared string table. > -> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +> © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] In the following example cell B4 contains the number 360. @@ -143,7 +143,7 @@ In the following example cell B4 contains the number 360. ## How the sample code works -After opening the spreadsheet file for read/write access, the code verifies if the specified worksheet exists. It then adds a new [DrawingsPart](/dotnet/api/documentformat.openxml.packaging.drawingspart) object using the [AddNewPart](/dotnet/api/documentformat.openxml.packaging.openxmlpartcontainer.addnewpart) method, appends it to the worksheet, and saves the worksheet part. The code then adds a new [ChartPart](/dotnet/api/documentformat.openxml.packaging.chartpart) object, appends a new [ChartSpace](/dotnet/api/documentformat.openxml.packaging.chartpart.chartspace) object to the **ChartPart** object, and then appends a new [EditingLanguage](/dotnet/api/documentformat.openxml.drawing.charts.chartspace.editinglanguage) object to the **ChartSpace*** object that specifies the language for the chart is English-US. +After opening the spreadsheet file for read/write access, the code verifies if the specified worksheet exists. It then adds a new object using the method, appends it to the worksheet, and saves the worksheet part. The code then adds a new object, appends a new object to the `ChartPart` object, and then appends a new object to the `ChartSpace` object that specifies the language for the chart is English-US. ### [C#](#tab/cs-1) [!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet1)] @@ -153,10 +153,11 @@ After opening the spreadsheet file for read/write access, the code verifies if t *** -The code creates a new clustered column chart by creating a new [BarChart](/dotnet/api/documentformat.openxml.drawing.charts.barchart) object with [BarDirectionValues](/dotnet/api/documentformat.openxml.drawing.charts.bardirectionvalues) object set to **Column** and [BarGroupingValues](/dotnet/api/documentformat.openxml.drawing.charts.bargroupingvalues) object set to **Clustered**. +The code creates a new clustered column chart by creating a new object with + object set to `Column` and object set to `Clustered`. -The code then iterates through each key in the **Dictionary** class. For each key, it appends a -[BarChartSeries](/dotnet/api/documentformat.openxml.drawing.charts.barchartseries) object to the **BarChart** object and sets the [SeriesText](/dotnet/api/documentformat.openxml.drawing.charts.seriestext) object of the **BarChartSeries** object to equal the key. For each key, it appends a [NumberLiteral](/dotnet/api/documentformat.openxml.drawing.charts.numberliteral) object to the **Values** collection of the **BarChartSeries** object and sets the **NumberLiteral** object to equal the **Dictionary** class value corresponding to the key. +The code then iterates through each key in the `Dictionary` class. For each key, it appends a + object to the `BarChart` object and sets the object of the `BarChartSeries` object to equal the key. For each key, it appends a 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) [!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet2)] @@ -166,7 +167,7 @@ The code then iterates through each key in the **Dictionary** class. For each ke *** -The code adds the [CategoryAxis](/dotnet/api/documentformat.openxml.drawing.charts.categoryaxis) object and [ValueAxis](/dotnet/api/documentformat.openxml.drawing.charts.valueaxis) object to the chart and sets the value of the following properties: [Scaling](/dotnet/api/documentformat.openxml.drawing.charts.scaling), [AxisPosition](/dotnet/api/documentformat.openxml.drawing.charts.axisposition), [TickLabelPosition](/dotnet/api/documentformat.openxml.drawing.charts.ticklabelposition), [CrossingAxis](/dotnet/api/documentformat.openxml.drawing.charts.crossingaxis), [Crosses](/dotnet/api/documentformat.openxml.drawing.charts.crosses), [AutoLabeled](/dotnet/api/documentformat.openxml.drawing.charts.autolabeled), [LabelAlignment](/dotnet/api/documentformat.openxml.drawing.charts.labelalignment), and [LabelOffset](/dotnet/api/documentformat.openxml.drawing.charts.labeloffset). It also adds the [Legend](/dotnet/api/documentformat.openxml.drawing.charts.chart.legend) object to the chart and saves the chart part. +The code adds the object and object to the chart and sets the value of the following properties: , , , , , , , and . It also adds the object to the chart and saves the chart part. ### [C#](#tab/cs-3) [!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet3)] @@ -176,7 +177,7 @@ The code adds the [CategoryAxis](/dotnet/api/documentformat.openxml.drawing.char *** -The code positions the chart on the worksheet by creating a [WorksheetDrawing](/dotnet/api/documentformat.openxml.packaging.drawingspart.worksheetdrawing) 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](/dotnet/api/documentformat.openxml.drawing.spreadsheet.frommarker) and [ToMarker](/dotnet/api/documentformat.openxml.drawing.spreadsheet.tomarker) anchors. The code then creates a [GraphicFrame](/dotnet/api/documentformat.openxml.drawing.spreadsheet.graphicframe) object to contain the chart and names the chart "Chart 1," and saves the worksheet drawing. +The code positions the chart on the worksheet by creating a 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 and anchors. The code then creates a object to contain the chart and names the chart "Chart 1". ### [C#](#tab/cs-4) [!code-csharp[](../../samples/spreadsheet/insert_a_chartto/cs/Program.cs#snippet4)] @@ -198,6 +199,7 @@ The following is the complete sample code in both C\# and Visual Basic. ### [Visual Basic](#tab/vb) [!code-vb[](../../samples/spreadsheet/insert_a_chartto/vb/Program.vb#snippet0)] +*** ## See also 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 3bb56571..ea02b433 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: 12/12/2023 +ms.date: 01/09/2025 ms.localizationpriority: high --- # Insert a new worksheet into a spreadsheet document @@ -20,25 +20,37 @@ This topic shows how to use the classes in the Open XML SDK for Office to insert a new worksheet into a spreadsheet document programmatically. +[!include[Open Spreadsheet](../includes/spreadsheet/open-spreadsheet.md)] +The code that calls the `Open` method is +shown in the following `using` statement. + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/spreadsheet/insert_a_new_worksheet/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/spreadsheet/insert_a_new_worksheet/vb/Program.vb#snippet1)] +*** + -------------------------------------------------------------------------------- [!include[Structure](../includes/spreadsheet/structure.md)] -------------------------------------------------------------------------------- -## Sample Code +## Sample Code Following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/insert_a_new_worksheet/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/insert_a_new_worksheet/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/insert_a_new_worksheet/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/insert_a_new_worksheet/vb/Program.vb#snippet0)] +*** -------------------------------------------------------------------------------- -## See also +## See also [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 724397f3..e054b10e 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: 12/12/2023 +ms.date: 01/10/2025 ms.localizationpriority: high --- # Insert text into a cell in a spreadsheet document @@ -25,9 +25,9 @@ document programmatically. [!include[Structure](../includes/spreadsheet/structure.md)] ## How the Sample Code Works -After opening the **SpreadsheetDocument** -document for editing, the code inserts a blank [Worksheet](/dotnet/api/documentformat.openxml.packaging.worksheetpart.worksheet) object into a [SpreadsheetDocument](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument) document package. Then, -inserts a new [Cell](/dotnet/api/documentformat.openxml.spreadsheet.cell) object into the new worksheet and +After opening the `SpreadsheetDocument` +document for editing, the code inserts a blank object into a document package. Then, +inserts a new object into the new worksheet and inserts the specified text into that cell. ### [C#](#tab/cs-1) @@ -39,14 +39,14 @@ inserts the specified text into that cell. The code passes in a parameter that represents the text to insert into -the cell and a parameter that represents the **SharedStringTablePart** object for the spreadsheet. -If the **ShareStringTablePart** object does not -contain a [SharedStringTable](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringtable) object, the code creates -one. If the text already exists in the **ShareStringTable** object, the code returns the -index for the [SharedStringItem](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringitem) object that represents the -text. Otherwise, it creates a new **SharedStringItem** object that represents the text. - -The following code verifies if the specified text exists in the **SharedStringTablePart** object and add the text if +the cell and a parameter that represents the `SharedStringTablePart` object for the spreadsheet. +If the `ShareStringTablePart` object does not +contain a object, the code creates +one. If the text already exists in the `ShareStringTable` object, the code returns the +index for the object that represents the +text. Otherwise, it creates a new `SharedStringItem` object that represents the text. + +The following code verifies if the specified text exists in the `SharedStringTablePart` object and add the text if it does not exist. ### [C#](#tab/cs-2) @@ -57,17 +57,17 @@ it does not exist. *** -The code adds a new **WorksheetPart** object to -the **WorkbookPart** object by using the [AddNewPart](/dotnet/api/documentformat.openxml.packaging.openxmlpartcontainer.addnewpart) method. It then adds a new **Worksheet** object to the **WorksheetPart** object, and gets a unique ID for -the new worksheet by selecting the maximum [SheetId](/dotnet/api/documentformat.openxml.spreadsheet.sheet.sheetid) object used within the spreadsheet +The code adds a new `WorksheetPart` object to +the `WorkbookPart` object by using the method. It then adds a new `Worksheet` object to the `WorksheetPart` object, and gets a unique ID for +the new worksheet by selecting the maximum object used within the spreadsheet document and adding one to create the new sheet ID. It gives the worksheet a name by concatenating the word "Sheet" with the sheet ID. It -then appends the new **Sheet** object to the -**Sheets** collection. +then appends the new `Sheet` object to the +`Sheets` collection. -The following code inserts a new **Worksheet** -object by adding a new **WorksheetPart** object -to the [WorkbookPart](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.workbookpart) object. +The following code inserts a new `Worksheet` +object by adding a new `WorksheetPart` object +to the object. ### [C#](#tab/cs-3) [!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet3)] @@ -80,12 +80,12 @@ to the [WorkbookPart](/dotnet/api/documentformat.openxml.packaging.spreadsheetdo To insert a cell into a worksheet, the code determines where to insert the new cell in the column by iterating through the row elements to find the cell that comes directly after the specified row, in sequential -order. It saves that row in the **refCell** +order. It saves that row in the `refCell` variable. It then inserts the new cell before the cell referenced by -**refCell** using the [InsertBefore](/dotnet/api/documentformat.openxml.openxmlcompositeelement.insertbefore) method. +`refCell` using the method. -In the following code, insert a new **Cell** -object into a **Worksheet** object. +In the following code, insert a new `Cell` +object into a `Worksheet` object. ### [C#](#tab/cs-4) [!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet4)] 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 1a15d501..be6e37c1 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: 12/12/2023 +ms.date: 01/10/2025 ms.localizationpriority: high --- # Merge two adjacent cells in a spreadsheet document @@ -22,13 +22,54 @@ programmatically. -------------------------------------------------------------------------------- +[!include[Open Spreadsheet](../includes/spreadsheet/open-spreadsheet.md)] + +------------------------------------------------------ + [!include[Structure](../includes/spreadsheet/structure.md)] -------------------------------------------------------------------------------- -## Sample Code -The following code merges two adjacent cells in a **[SpreadsheetDocument](/dotnet/api/documentformat.openxml.spreadsheet.row)** document package. When +## How the Sample Code Works + +After you have opened the spreadsheet file for editing, the code +verifies that the specified cells exist, and if they do not exist, it +creates them by calling the `CreateSpreadsheetCellIfNotExist` method and append +it to the appropriate object. + +### [C#](#tab/cs-1) +[!code-csharp[](../../samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs#snippet1)] + +### [Visual Basic](#tab/vb-1) +[!code-vb[](../../samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb#snippet1)] +*** + +In order to get a column name, the code creates a new regular expression +to match the column name portion of the cell name. This regular +expression matches any combination of uppercase or lowercase letters. +For more information about regular expressions, see [Regular Expression Language Elements](/dotnet/standard/base-types/regular-expressions). The +code gets the column name by calling the [Regex.Match](/dotnet/api/system.text.regularexpressions.regex.match#overloads). + +### [C#](#tab/cs-2) +[!code-csharp[](../../samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs#snippet2)] + +### [Visual Basic](#tab/vb-2) +[!code-vb[](../../samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb#snippet2)] +*** + +To get the row index, the code creates a new regular expression to match the row index portion of the cell name. This regular expression matches any combination of decimal digits. The following code creates a regular expression to match the row index portion of the cell name, comprised of decimal digits. + +### [C#](#tab/cs-3) +[!code-csharp[](../../samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs#snippet3)] + +### [Visual Basic](#tab/vb-3) +[!code-vb[](../../samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb#snippet3)] +*** + +## Sample Code + +The following code merges two adjacent cells in a document package. When 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 @@ -41,8 +82,9 @@ The following is the complete sample code in both C\# and Visual Basic. ### [Visual Basic](#tab/vb) [!code-vb[](../../samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb#snippet0)] +*** -------------------------------------------------------------------------------- -## See also +## See also - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) 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 53950479..8fb782c2 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: 12/12/2023 +ms.date: 01/10/2025 ms.localizationpriority: high --- # Open a spreadsheet document for read-only access @@ -24,50 +24,54 @@ programmatically. --------------------------------------------------------------------------------- ## When to Open a Document for Read-Only Access + Sometimes you want to open a document to inspect or retrieve some information, and you want to do this in a way that ensures the document remains unchanged. In these instances, you want to open the document for read-only access. This How To topic discusses several ways to programmatically open a read-only spreadsheet document. +-------------------------------------------------------------------------------- +[!include[Spreadsheet Object](../includes/spreadsheet/spreadsheet-object.md)] -------------------------------------------------------------------------------- ## Getting a SpreadsheetDocument Object -In the Open XML SDK, the [SpreadsheetDocument](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument) class represents an + +In the Open XML SDK, the class represents an Excel document package. To create an Excel document, you create an -instance of the **SpreadsheetDocument** class +instance of the `SpreadsheetDocument` class and populate it with parts. At a minimum, the document must have a workbook part that serves as a container for the document, and at least one worksheet part. The text 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()](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open) overload methods. Several **Open** methods are provided, each with a different + overload methods. Several `Open` methods are provided, each with a different signature. The methods that let you specify whether a document is editable are listed in the following table. |Open|Class Library Reference Topic|Description| --|--|-- -Open(String, Boolean)|[Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open)|Create an instance of the SpreadsheetDocument class from the specified file. -Open(Stream, Boolean)|[Open(Stream, Boolean](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open)|Create an instance of the SpreadsheetDocument class from the specified IO stream. -Open(String, Boolean, OpenSettings)|[Open(String, Boolean, OpenSettings)](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open)|Create an instance of the SpreadsheetDocument class from the specified file. -Open(Stream, Boolean, OpenSettings)|[Open(Stream, Boolean, OpenSettings)](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open)|Create an instance of the SpreadsheetDocument class from the specified I/O stream. +Open(String, Boolean)|[Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open?#documentformat-openxml-packaging-spreadsheetdocument-open(system-string-system-boolean))|Create an instance of the SpreadsheetDocument class from the specified file. +Open(Stream, Boolean)|[Open(Stream, Boolean](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open?#documentformat-openxml-packaging-spreadsheetdocument-open(system-io-stream-system-boolean))|Create an instance of the SpreadsheetDocument class from the specified IO stream. +Open(String, Boolean, OpenSettings)|[Open(String, Boolean, OpenSettings)](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open?#documentformat-openxml-packaging-spreadsheetdocument-open(system-string-system-boolean-documentformat-openxml-packaging-opensettings))|Create an instance of the SpreadsheetDocument class from the specified file. +Open(Stream, Boolean, OpenSettings)|[Open(Stream, Boolean, OpenSettings)](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open?#documentformat-openxml-packaging-spreadsheetdocument-open(system-io-stream-system-boolean-documentformat-openxml-packaging-opensettings))|Create an instance of the SpreadsheetDocument class from the specified I/O stream. -The table earlier in this topic lists only those **Open** methods that accept a Boolean value as the +The table earlier in this topic lists only those `Open` methods that accept a Boolean value as the second parameter to specify whether a document is editable. To open a -document for read-only access, specify **False** for this parameter. +document for read-only access, specify `False` for this parameter. -Notice that two of the **Open** methods create +Notice that two of the `Open` methods create an instance of the SpreadsheetDocument class based on a string as the first parameter. The first example in the sample code uses this -technique. It uses the first **Open** method in +technique. It uses the first `Open` method in the table earlier in this topic; with a signature that requires two parameters. The first parameter takes a string that represents the full path file name from which you want to open the document. The second -parameter is either **true** or **false**. This example uses **false** and indicates that you want to open the +parameter is either `true` or `false`. This example uses `false` and indicates that you want to open the file as read-only. -The following code example calls the **Open** +The following code example calls the `Open` Method. ### [C#](#tab/cs-0) @@ -78,7 +82,7 @@ Method. *** -The other two **Open** methods create an +The other two `Open` methods create an instance of the SpreadsheetDocument class based on an input/output stream. You might use this approach, for example, if you have a Microsoft SharePoint Foundation 2010 application that uses stream @@ -99,12 +103,12 @@ Suppose you have an application that uses the Open XML support in the System.IO.Packaging namespace of the .NET Framework Class Library, and you want to use the Open XML SDK to work with a package as read-only. Whereas the Open XML SDK includes method overloads that -accept a **Package** as the first parameter, +accept a `Package` as the first parameter, there is not one that takes a Boolean as the second parameter to indicate whether the document should be opened for editing. The recommended method is to open the package as read-only at first, -before creating the instance of the **SpreadsheetDocument** class, as shown in the second +before creating the instance of the `SpreadsheetDocument` class, as shown in the second example in the sample code. The following code example performs this operation. @@ -115,62 +119,7 @@ operation. [!code-vb[](../../samples/spreadsheet/open_for_read_only_access/vb/Program.vb#snippet3)] --------------------------------------------------------------------------------- -## Basic Document Structure -The basic document structure of a SpreadsheetML document consists of the -[Sheets](/dotnet/api/documentformat.openxml.spreadsheet.sheets) and [Sheet](/dotnet/api/documentformat.openxml.spreadsheet.sheet) elements, which reference the -worksheets in the [Workbook](/dotnet/api/documentformat.openxml.spreadsheet.workbook). A separate XML file is created -for each [Worksheet](/dotnet/api/documentformat.openxml.spreadsheet.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 as follows. - -```xml - - - - - - - -``` - -The worksheet XML files contain one or more block level elements such as -[SheetData](/dotnet/api/documentformat.openxml.spreadsheet.sheetdata). **sheetData** represents the cell table and contains -one or more [Row](/dotnet/api/documentformat.openxml.spreadsheet.row) elements. A **row** contains one or more [Cell](/dotnet/api/documentformat.openxml.spreadsheet.cell) elements. Each cell contains a [CellValue](/dotnet/api/documentformat.openxml.spreadsheet.cellvalue) 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 as follows. - -```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 [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] 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. --------------------------------------------------------------------------------- ## Sample Code The following is the complete sample code in both C\# and Visual Basic. @@ -180,6 +129,7 @@ The following is the complete sample code in both C\# and Visual Basic. ### [Visual Basic](#tab/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 f977223a..c9054095 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: 12/05/2023 +ms.date: 01/10/2025 ms.localizationpriority: high --- # Open a spreadsheet document from a stream @@ -22,7 +22,7 @@ Office to open a spreadsheet document from a stream programmatically. --------------------------------------------------------------------------------- -## When to Open From a Stream +## When to Open From a Stream If you have an application, such as Microsoft SharePoint Foundation 2010, that works with documents by using stream input/output, and you want to use the Open XML SDK to work with one of the documents, this @@ -36,70 +36,16 @@ Open XML SDK. -------------------------------------------------------------------------------- -## The SpreadsheetDocument Object - -The basic document structure of a SpreadsheetML document consists of the -[Sheets](/dotnet/api/documentformat.openxml.spreadsheet.sheets) and [Sheet](/dotnet/api/documentformat.openxml.spreadsheet.sheet) 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](/dotnet/api/documentformat.openxml.spreadsheet.sheetdata). **sheetData** represents the cell table and contains -one or more [Row](/dotnet/api/documentformat.openxml.spreadsheet.row) elements. A **row** contains one or more [Cell](/dotnet/api/documentformat.openxml.spreadsheet.cell) elements. Each cell contains a [CellValue](/dotnet/api/documentformat.openxml.spreadsheet.cellvalue) 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 [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] 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[Spreadsheet Object](../includes/spreadsheet/spreadsheet-object.md)] -------------------------------------------------------------------------------- -## Generating the SpreadsheetML Markup to Add a Worksheet +## Generating the SpreadsheetML Markup to Add a Worksheet + When you have access to the body of the main document part, you add a -worksheet by calling [AddNewPart\(String, String)](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.addnewpart) method to -create a new [WorksheetPart](/dotnet/api/documentformat.openxml.spreadsheet.worksheet.worksheetpart). The following code example -adds the new **WorksheetPart**. +worksheet by calling method to +create a new . The following code example +adds the new `WorksheetPart`. ### [C#](#tab/cs-2) [!code-csharp[](../../samples/spreadsheet/open_from_a_stream/cs/Program.cs#snippet1)] @@ -110,8 +56,9 @@ adds the new **WorksheetPart**. -------------------------------------------------------------------------------- -## Sample Code -In this example, the **OpenAndAddToSpreadsheetStream** method can be used +## 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. The following is the complete sample code in both C\# and Visual Basic. @@ -123,8 +70,9 @@ some text to it. The following is the complete sample code in both C\# and Visua *** -Notice that the **OpenAddAndAddToSpreadsheetStream** method does not -close the stream passed to it. The calling code must do that. +Notice that the `OpenAddAndAddToSpreadsheetStream` method does not +close the stream passed to it. The calling code must do that manually +or with a `using` statement. The following is the complete sample code in both C\# and Visual Basic. @@ -133,9 +81,10 @@ The following is the complete sample code in both C\# and Visual Basic. ### [Visual Basic](#tab/vb) [!code-vb[](../../samples/spreadsheet/open_from_a_stream/vb/Program.vb#snippet0)] +*** -------------------------------------------------------------------------------- -## See also +## See also - [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) 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 3c9a503f..35d7b2ef 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,25 +11,26 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 12/05/2023 +ms.date: 01/10/2025 ms.localizationpriority: high --- # Parse and read a large spreadsheet document This topic shows how to use the classes in the Open XML SDK for Office to programmatically read a large Excel file. For more information -about the basic structure of a **SpreadsheetML** document, see [Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md). +about the basic structure of a `SpreadsheetML` document, see [Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md). [!include[Add-ins note](../includes/addinsnote.md)] -------------------------------------------------------------------------------- -## Approaches to Parsing Open XML Files +## Approaches to Parsing Open XML Files + The Open XML SDK provides two approaches to parsing Open XML files. You can use the SDK Document Object Model (DOM), or the Simple API for XML (SAX) reading and writing features. The SDK DOM is designed to make it easy to query and parse Open XML files by using strongly-typed classes. However, the DOM approach requires loading entire Open XML parts into -memory, which can cause an **Out of Memory** +memory, which can cause an `Out of Memory` exception when you are working with really large files. Using the SAX approach, you can employ an OpenXMLReader to read the XML in the file one element at a time, without having to load the entire file into @@ -59,7 +60,8 @@ This is the recommended approach for reading very large files. -------------------------------------------------------------------------------- -## Sample Code +## Sample Code + You can imagine a scenario where you work for a financial company that handles very large Excel spreadsheets. Those spreadsheets are updated daily by analysts and can easily grow to sizes exceeding hundreds of @@ -88,10 +90,10 @@ The following is the complete code sample in both C\# and Visual Basic. [!code-vb[](../../samples/spreadsheet/parse_and_read_a_large_spreadsheet/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- -## See also +## See also -[Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md) +[Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md) 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 a02ceeaf..5fd49ffc 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: 12/05/2023 +ms.date: 01/10/2025 ms.localizationpriority: medium --- # Retrieve a dictionary of all named ranges in a spreadsheet document @@ -27,7 +27,7 @@ to illustrate this task. The **GetDefinedNames** method accepts a single parameter that indicates the name of the document from which to retrieve the defined names. The method returns an -[Dictionary](/dotnet/api/system.collections.generic.dictionary-2) + instance that contains information about the defined names within the specified workbook, which may be empty if there are no defined names. 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 aaa55f06..ebf2e566 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,12 +12,12 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 12/05/2023 +ms.date: 01/10/2025 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 worksheet. 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. @@ -25,7 +25,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to progra ## GetHiddenRowsOrCols Method -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: +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,7 +37,7 @@ You can use the **GetHiddenRowsOrCols** method to retrieve a list of the hidden ## How the Code Works -The code opens the document, by using the [SpreadsheetDocument.Open](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open) 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](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.workbookpart) property of the document. +The code opens the document, by using the 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 property of the document. ### [C#](#tab/cs-3) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet1)] @@ -47,8 +47,8 @@ The code opens the document, by using the [SpreadsheetDocument.Open](/dotnet/api *** -To find the hidden rows or columns, the code must first retrieve a reference to the specified sheet, given its name. This is not as easy as you might think. The code must look through all the sheet-type descendants of the workbook part's [Workbook](/dotnet/api/documentformat.openxml.packaging.workbookpart.workbook) property, examining the [Name](/dotnet/api/documentformat.openxml.spreadsheet.sheet.name) property of each sheet that it finds. -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](/dotnet/api/documentformat.openxml.spreadsheet.sheet) object, which contains information such as the name and [Id](/dotnet/api/documentformat.openxml.spreadsheet.sheet.id) property of the sheet. The simplest way to accomplish this is to use a LINQ query. +To find the hidden rows or columns, the code must first retrieve a reference to the specified sheet, given its name. This is not as easy as you might think. The code must look through all the sheet-type descendants of the workbook part's property, examining the property of each sheet that it finds. +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 object, which contains information such as the name and property of the sheet. The simplest way to accomplish this is to use a LINQ query. ### [C#](#tab/cs-4) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet2)] @@ -57,7 +57,7 @@ Note that this search simply looks through the relations of the workbook, and do [!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet2)] *** -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](/dotnet/api/documentformat.openxml.spreadsheet.worksheet.worksheetpart) property by calling the [GetPartById](/dotnet/api/documentformat.openxml.packaging.openxmlpartcontainer.getpartbyid) method of the [WorkbookPart](/dotnet/api/documentformat.openxml.packaging.workbookpart) 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 property by calling the method of the object. ### [C#](#tab/cs-5) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet3)] @@ -71,7 +71,7 @@ The sheet information you already retrieved provides an **Id** property, and giv ## 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.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) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet4)] @@ -80,7 +80,7 @@ The code uses the **detectRows** parameter that you specified when you called th [!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet4)] *** -Retrieving the list of hidden columns is a bit trickier, because Excel collapses groups of hidden columns into a single element, and provides [Min](/dotnet/api/documentformat.openxml.spreadsheet.column.min) and [Max](/dotnet/api/documentformat.openxml.spreadsheet.column.max) 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). +Retrieving the list of hidden columns is a bit trickier, because Excel collapses groups of hidden columns into a single element, and provides and 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) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/cs/Program.cs#snippet5)] @@ -94,13 +94,14 @@ Retrieving the list of hidden columns is a bit trickier, because Excel collapses ## Sample Code -The following is the complete **GetHiddenRowsOrCols** code sample in C\# and Visual Basic. +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#snippet0)] ### [Visual Basic](#tab/vb) [!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_rows_or_columns/vb/Program.vb#snippet0)] +*** --------------------------------------------------------------------------------- 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 21abf5a9..591ab8fa 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,22 +10,22 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/29/2023 +ms.date: 01/10/2025 ms.localizationpriority: medium --- # Retrieve a list of the hidden worksheets 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 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. +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 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, 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\](/dotnet/api/system.collections.generic.list-1)** instance with a reference to each hidden **Sheet** object. +You can use the `GetHiddenSheets` method, to retrieve a list of the hidden worksheets in a workbook. The `GetHiddenSheets` method accepts a single parameter, a string that indicates the path of the file that you want to examine. The method works with the workbook you specify, filling a instance with a reference to each hidden `Sheet` object. ## Retrieve the collection of worksheets -The **WorkbookPart** class provides a **Workbook** property, which in turn contains the XML content of the workbook. Although the Open XML SDK provides the **Sheets** property, which returns a collection of the **Sheet** parts, all the information that you need is provided by the **Sheet** elements within the **Workbook** XML content. -The following code uses the **Descendants** generic method of the **Workbook** object to retrieve a collection of **Sheet** objects that contain information about all the sheet child elements of the workbook's XML content. +The `WorkbookPart` class provides a `Workbook` property, which in turn contains the XML content of the workbook. Although the Open XML SDK provides the `Sheets` property, which returns a collection of the `Sheet` parts, all the information that you need is provided by the `Sheet` elements within the `Workbook` XML content. +The following code uses the `Descendants` generic method of the `Workbook` object to retrieve a collection of `Sheet` objects that contain information about all the sheet child elements of the workbook's XML content. ### [C#](#tab/cs-4) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs#snippet1)] @@ -37,9 +37,9 @@ The following code uses the **Descendants** generic method of the **Workbook** o ## 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. -For these worksheets, the **State** property of the **Sheet** object contains an enumerated value of **Hidden**. You can also make a worksheet very hidden by writing code (either in VBA or in another language) that sets the sheet's **Visible** property to the enumerated value **xlSheetVeryHidden**. For worksheets hidden in this manner, the **State** property of the **Sheet** object contains the enumerated value **VeryHidden**. +For these worksheets, the `State` property of the `Sheet` object contains an enumerated value of `Hidden`. You can also make a worksheet very hidden by writing code (either in VBA or in another language) that sets the sheet's `Visible` property to the enumerated value `xlSheetVeryHidden`. For worksheets hidden in this manner, the `State` property of the `Sheet` object contains the enumerated value `VeryHidden`. -Given the collection that contains information about all the sheets, the following code uses the **[Where](/dotnet/api/system.linq.enumerable.where)** 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**. +Given the collection that contains information about all the sheets, the following code uses the 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) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_hidden_worksheets/cs/Program.cs#snippet2)] @@ -50,7 +50,7 @@ Given the collection that contains information about all the sheets, the followi ## Sample code -The following is the complete **GetHiddenSheets** code sample in C\# and Visual Basic. +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#snippet0)] 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 4960dcaf..69b89fcc 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: 11/27/2023 +ms.date: 01/10/2025 ms.localizationpriority: high --- # Retrieve a list of the worksheets in a spreadsheet document @@ -20,7 +20,7 @@ ms.localizationpriority: high This topic shows how to use the classes in the Open XML SDK for Office to programmatically retrieve a list of the worksheets in a Microsoft Excel workbook, without loading -the document into Excel. It contains an example **GetAllWorksheets** method to illustrate this task. +the document into Excel. It contains an example `GetAllWorksheets` method to illustrate this task. @@ -28,9 +28,9 @@ the document into Excel. It contains an example **GetAllWorksheets** method to i ## GetAllWorksheets Method -You can use the **GetAllWorksheets** method, +You can use the `GetAllWorksheets` method, which is shown in the following code, to retrieve a list of the -worksheets in a workbook. The **GetAllWorksheets** method accepts a single +worksheets in a workbook. The `GetAllWorksheets` method accepts a single parameter, a string that indicates the path of the file that you want to examine. @@ -38,19 +38,19 @@ examine. [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb#snippet2)] +[!code-vb[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/vb/Program.vb#snippet1)] *** The method works with the workbook you specify, returning an instance of -the **[Sheets](/dotnet/api/documentformat.openxml.spreadsheet.sheets)** object, from which you can retrieve -a reference to each **[Sheet](/dotnet/api/documentformat.openxml.spreadsheet.sheet)** object. +the object, from which you can retrieve +a reference to each object. -------------------------------------------------------------------------------- ## Calling the GetAllWorksheets Method -To call the **GetAllWorksheets** method, pass +To call the `GetAllWorksheets` method, pass the required value, as shown in the following code. ### [C#](#tab/cs-1) @@ -65,11 +65,11 @@ the required value, as shown in the following code. ## How the Code Works -The sample method, **GetAllWorksheets**, -creates a variable that will contain a reference to the **Sheets** collection of the workbook. At the end of +The sample method, `GetAllWorksheets`, +creates a variable that will contain a reference to the `Sheets` collection of the workbook. At the end of its work, the method returns the variable, which contains either a -reference to the **Sheets** collection, or -null/Nothing if there were no sheets (this cannot occur in a well-formed +reference to the `Sheets` collection, or +`null`/`Nothing` if there were no sheets (this cannot occur in a well-formed workbook). ### [C#](#tab/cs-2) @@ -81,7 +81,7 @@ workbook). The code then continues by opening the document in read-only mode, and -retrieving a reference to the **[WorkbookPart](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.workbookpart)**. +retrieving a reference to the . ### [C#](#tab/cs-3) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs#snippet4)] @@ -91,7 +91,7 @@ retrieving a reference to the **[WorkbookPart](/dotnet/api/documentformat.openxm *** -To get access to the **[Workbook](/dotnet/api/documentformat.openxml.spreadsheet.workbook)** object, the code retrieves the value of the **[Workbook](/dotnet/api/documentformat.openxml.packaging.workbookpart.workbook)** property from the **WorkbookPart**, and then retrieves a reference to the **Sheets** object from the **[Sheets](/dotnet/api/documentformat.openxml.spreadsheet.workbook.sheets)** property of the **Workbook**. The **Sheets** object contains the collection of **[Sheet](/dotnet/api/documentformat.openxml.spreadsheet.sheet)** objects that provide the method's return value. +To get access to the object, the code retrieves the value of the property from the `WorkbookPart`, and then retrieves a reference to the `Sheets` object from the property of the `Workbook`. The `Sheets` object contains the collection of objects that provide the method's return value. ### [C#](#tab/cs-4) [!code-csharp[](../../samples/spreadsheet/retrieve_a_list_of_the_worksheets/cs/Program.cs#snippet5)] @@ -105,7 +105,7 @@ To get access to the **[Workbook](/dotnet/api/documentformat.openxml.spreadsheet ## Sample Code -The following is the complete **GetAllWorksheets** code sample in C\# and Visual +The following is the complete `GetAllWorksheets` code sample in C\# and Visual Basic. ### [C#](#tab/cs) @@ -113,6 +113,7 @@ Basic. ### [Visual Basic](#tab/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 b0058983..399c4b61 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: 11/20/2023 +ms.date: 01/10/2025 ms.localizationpriority: high --- @@ -18,14 +18,14 @@ ms.localizationpriority: high This topic shows how to use the classes in the Open XML SDK for Office to programmatically retrieve the values of cells in a spreadsheet -document. It contains an example **GetCellValue** method to illustrate +document. It contains an example `GetCellValue` method to illustrate this task. ## GetCellValue Method -You can use the **GetCellValue** method to +You can use the `GetCellValue` method to retrieve the value of a cell in a workbook. The method requires the following three parameters: @@ -61,9 +61,9 @@ initializes it to null. ## Accessing the Cell -Next, the code opens the document by using the **[Open](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open)** method, indicating that the document -should be open for read-only access (the final **false** parameter). Next, the code retrieves a -reference to the workbook part by using the **[WorkbookPart](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.workbookpart)** property of the document. +Next, the code opens the document by using the method, indicating that the document +should be open for read-only access (the final `false` parameter). Next, the code retrieves a +reference to the workbook part by using the property of the document. ### [C#](#tab/cs-3) [!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs?name=snippet3)] @@ -75,11 +75,11 @@ reference to the workbook part by using the **[WorkbookPart](/dotnet/api/documen To find the requested cell, the code must first retrieve a reference to the sheet, given its name. The code must search all the sheet-type -descendants of the workbook part workbook element and examine the **[Name](/dotnet/api/documentformat.openxml.spreadsheet.sheet.name)** property of each sheet that it finds. +descendants of the workbook part workbook element and examine the property of each sheet that it finds. Be aware that this search looks through the relations of the workbook, and does not actually find a worksheet part. It finds a reference to a -**[Sheet](/dotnet/api/documentformat.openxml.spreadsheet.sheet)**, which contains information such as -the name and **[Id](/dotnet/api/documentformat.openxml.spreadsheet.sheet.id)** of the sheet. The simplest way to do +, which contains information such as +the name and of the sheet. The simplest way to do this is to use a LINQ query, as shown in the following code example. ### [C#](#tab/cs-4) @@ -90,15 +90,15 @@ this is to use a LINQ query, as shown in the following code example. *** -Be aware that the [FirstOrDefault](/dotnet/api/system.linq.enumerable.firstordefault) +Be aware that the 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 that you already retrieved provides an **[Id](/dotnet/api/documentformat.openxml.spreadsheet.sheet.id)** property, and given that **Id** property, the code can retrieve a reference to -the corresponding **[WorksheetPart](/dotnet/api/documentformat.openxml.spreadsheet.worksheet.worksheetpart)** by calling the workbook part -**[GetPartById](/dotnet/api/documentformat.openxml.packaging.openxmlpartcontainer.getpartbyid)** method. +information that you already retrieved provides an property, and given that **Id** property, the code can retrieve a reference to +the corresponding by calling the workbook part + method. ### [C#](#tab/cs-5) [!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs?name=snippet5)] @@ -109,10 +109,10 @@ the corresponding **[WorksheetPart](/dotnet/api/documentformat.openxml.spreadshe Just as when locating the named sheet, when locating the named cell, the -code uses the **[Descendants](/dotnet/api/documentformat.openxml.openxmlelement.descendants)** method, searching for the first -match in which the **[CellReference](/dotnet/api/documentformat.openxml.spreadsheet.celltype.cellreference)** property equals the specified -**addressName** -parameter. After this method call, the variable named **theCell** will either contain a reference to the cell, +code uses the method, searching for the first +match in which the property equals the specified +`addressName` +parameter. After this method call, the variable named `theCell` will either contain a reference to the cell, or will contain a null reference. ### [C#](#tab/cs-6) @@ -125,9 +125,9 @@ or will contain a null reference. ## Retrieving the Value -At this point, the variable named **theCell** +At this point, the variable named `theCell` contains either a null reference, or a reference to the cell that you -requested. If you examine the Open XML content (that is, **theCell.OuterXml**) for the cell, you will find XML +requested. If you examine the Open XML content (that is, `theCell.OuterXml`) for the cell, you will find XML such as the following. ```xml @@ -136,7 +136,7 @@ such as the following. ``` -The **[InnerText](/dotnet/api/documentformat.openxml.openxmlelement.innertext)** property contains the content for +The property contains the content for the cell, and so the next block of code retrieves this value. ### [C#](#tab/cs-7) @@ -149,10 +149,11 @@ the cell, and so the next block of code retrieves this value. Now, the sample method must interpret the value. As it is, the code handles numeric and date, string, and Boolean values. You can extend the -sample as necessary. The **[Cell](/dotnet/api/documentformat.openxml.spreadsheet.cell)** type provides a **[DataType](/dotnet/api/documentformat.openxml.spreadsheet.celltype.datatype)** property that indicates the type -of the data within the cell. The value of the **DataType** property is null for numeric and date -types. It contains the value **CellValues.SharedString** for strings, and **CellValues.Boolean** for Boolean values. If the -**DataType** property is null, the code returns +sample as necessary. The type provides a + property that indicates the type +of the data within the cell. The value of the `DataType` property is null for numeric and date +types. It contains the value `CellValues.SharedString` for strings, and `CellValues.Boolean` for Boolean values. If the +`DataType` property is null, the code returns the value of the cell (it is a numeric value). Otherwise, the code continues by branching based on the data type. @@ -164,8 +165,8 @@ continues by branching based on the data type. *** -If the **DataType** property contains **CellValues.SharedString**, the code must retrieve a -reference to the single **[SharedStringTablePart](/dotnet/api/documentformat.openxml.packaging.workbookpart.sharedstringtablepart)**. +If the `DataType` property contains `CellValues.SharedString`, the code must retrieve a +reference to the single . ### [C#](#tab/cs-9) [!code-csharp[](../../samples/spreadsheet/retrieve_the_values_of_cells/cs/Program.cs#snippet9)] @@ -177,7 +178,7 @@ reference to the single **[SharedStringTablePart](/dotnet/api/documentformat.ope Next, if the string table exists (and if it does not, the workbook is damaged and the sample code returns the index into the string table -instead of the string itself) the code returns the **InnerText** property of the element it finds at the +instead of the string itself) the code returns the `InnerText` property of the element it finds at the specified index (first converting the value property to an integer). ### [C#](#tab/cs-10) @@ -188,7 +189,7 @@ specified index (first converting the value property to an integer). *** -If the **DataType** property contains **CellValues.Boolean**, the code converts the 0 or 1 +If the `DataType` property contains `CellValues.Boolean`, the code converts the 0 or 1 it finds in the cell value into the appropriate text string. ### [C#](#tab/cs-11) @@ -199,17 +200,18 @@ it finds in the cell value into the appropriate text string. *** -Finally, the procedure returns the variable **value**, which contains the requested information. +Finally, the procedure returns the variable `value`, which contains the requested information. ## Sample Code -The following is the complete **GetCellValue** code sample in C\# and Visual Basic. +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#snippet0)] ### [Visual Basic](#tab/vb) [!code-vb[](../../samples/spreadsheet/retrieve_the_values_of_cells/vb/Program.vb#snippet0)] +*** ## See also diff --git a/docs/spreadsheet/overview.md b/docs/spreadsheet/overview.md index d38800b9..b3808c3a 100644 --- a/docs/spreadsheet/overview.md +++ b/docs/spreadsheet/overview.md @@ -21,55 +21,60 @@ This section provides how-to topics for working with spreadsheet documents using ## In this section -- [Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md) +- [Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md) -- [Working with the calculation chain](working-with-the-calculation-chain.md) +- [Add custom UI to a spreadsheet document](how-to-add-custom-ui-to-a-spreadsheet-document.md) -- [Working with conditional formatting](working-with-conditional-formatting.md) +- [Calculate the sum of a range of cells in a spreadsheet document](how-to-calculate-the-sum-of-a-range-of-cells-in-a-spreadsheet-document.md) -- [Working with formulas](working-with-formulas.md) +- [Copy a Worksheet Using SAX (Simple API for XML)](how-to-copy-a-worksheet-with-sax.md) -- [Working with PivotTables](working-with-pivottables.md) +- [Create a spreadsheet document by providing a file name](how-to-create-a-spreadsheet-document-by-providing-a-file-name.md) -- [Working with the shared string table](working-with-the-shared-string-table.md) +- [Delete text from a cell in a spreadsheet document](how-to-delete-text-from-a-cell-in-a-spreadsheet.md) -- [Working with sheets](working-with-sheets.md) +- [Get a column heading in a spreadsheet document](how-to-get-a-column-heading-in-a-spreadsheet.md) -- [Working with SpreadsheetML tables](working-with-tables.md) +- [Get worksheet information from an Open XML package](how-to-get-worksheet-information-from-a-package.md) -- [Calculate the sum of a range of cells in a spreadsheet document](how-to-calculate-the-sum-of-a-range-of-cells-in-a-spreadsheet-document.md) +- [Insert a chart into a spreadsheet document](how-to-insert-a-chart-into-a-spreadsheet.md) -- [Create a spreadsheet document by providing a file name](how-to-create-a-spreadsheet-document-by-providing-a-file-name.md) +- [Insert a new worksheet into a spreadsheet document](how-to-insert-a-new-worksheet-into-a-spreadsheet.md) -- [Delete text from a cell in a spreadsheet document](how-to-delete-text-from-a-cell-in-a-spreadsheet.md) +- [Insert text into a cell in a spreadsheet document](how-to-insert-text-into-a-cell-in-a-spreadsheet.md) -- [Get a column heading in a spreadsheet document](how-to-get-a-column-heading-in-a-spreadsheet.md) +- [Merge two adjacent cells in a spreadsheet document](how-to-merge-two-adjacent-cells-in-a-spreadsheet.md) -- [Get worksheet information from an Open XML package](how-to-get-worksheet-information-from-a-package.md) +- [Open a spreadsheet document for read-only access](how-to-open-a-spreadsheet-document-for-read-only-access.md) -- [Insert a chart into a spreadsheet document](how-to-insert-a-chart-into-a-spreadsheet.md) +- [Open a spreadsheet document from a stream](how-to-open-a-spreadsheet-document-from-a-stream.md) -- [Insert a new worksheet into a spreadsheet document](how-to-insert-a-new-worksheet-into-a-spreadsheet.md) +- [Parse and read a large spreadsheet document](how-to-parse-and-read-a-large-spreadsheet.md) -- [Insert text into a cell in a spreadsheet document](how-to-insert-text-into-a-cell-in-a-spreadsheet.md) +- [Retrieve a dictionary of all named ranges in a spreadsheet document](how-to-retrieve-a-dictionary-of-all-named-ranges-in-a-spreadsheet.md) -- [Merge two adjacent cells in a spreadsheet document](how-to-merge-two-adjacent-cells-in-a-spreadsheet.md) +- [Retrieve a list of the hidden rows or columns in a spreadsheet document](how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md) -- [Open a spreadsheet document for read-only access](how-to-open-a-spreadsheet-document-for-read-only-access.md) +- [Retrieve a list of the hidden worksheets in a spreadsheet document](how-to-retrieve-a-list-of-the-hidden-worksheets-in-a-spreadsheet.md) -- [Open a spreadsheet document from a stream](how-to-open-a-spreadsheet-document-from-a-stream.md) +- [Retrieve the values of cells in a spreadsheet document](how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md) -- [Parse and read a large spreadsheet document](how-to-parse-and-read-a-large-spreadsheet.md) +- [Retrieve a list of the worksheets in a spreadsheet document](how-to-retrieve-a-list-of-the-worksheets-in-a-spreadsheet.md) -- [Retrieve a dictionary of all named ranges in a spreadsheet document](how-to-retrieve-a-dictionary-of-all-named-ranges-in-a-spreadsheet.md) +- [Working with the calculation chain](working-with-the-calculation-chain.md) -- [Retrieve a list of the hidden rows or columns in a spreadsheet document](how-to-retrieve-a-list-of-the-hidden-rows-or-columns-in-a-spreadsheet.md) +- [Working with conditional formatting](working-with-conditional-formatting.md) -- [Retrieve a list of the hidden worksheets in a spreadsheet document](how-to-retrieve-a-list-of-the-hidden-worksheets-in-a-spreadsheet.md) +- [Working with formulas](working-with-formulas.md) -- [Retrieve the values of cells in a spreadsheet document](how-to-retrieve-the-values-of-cells-in-a-spreadsheet.md) +- [Working with PivotTables](working-with-pivottables.md) +- [Working with the shared string table](working-with-the-shared-string-table.md) + +- [Working with sheets](working-with-sheets.md) + +- [Working with SpreadsheetML tables](working-with-tables.md) ## Related sections -- [Getting started with the Open XML SDK for Office](../getting-started.md) +- [Getting started with the Open XML SDK for Office](../getting-started.md) diff --git a/docs/spreadsheet/structure-of-a-spreadsheetml-document.md b/docs/spreadsheet/structure-of-a-spreadsheetml-document.md index dce41e7c..19648724 100644 --- a/docs/spreadsheet/structure-of-a-spreadsheetml-document.md +++ b/docs/spreadsheet/structure-of-a-spreadsheetml-document.md @@ -11,19 +11,19 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/14/2025 ms.localizationpriority: high --- # Structure of a SpreadsheetML document -The document structure of a **SpreadsheetML** -document consists of the \<**workbook**\> -element that contains \<**sheets**\> and -\<**sheet**\> elements that reference the +The document structure of a `SpreadsheetML` +document consists of the `` +element that contains `` and +`` elements that reference the worksheets in the workbook. A separate XML file is created for each worksheet. These elements are the minimum elements required for a valid spreadsheet document. In addition, a spreadsheet document might contain -\<**table**\>, \<**chartsheet**\>, \<**pivotTableDefinition**\>, or other spreadsheet +``, ``, ``, or other spreadsheet related elements. [!include[Add-ins note](../includes/addinsnote.md)] @@ -32,25 +32,25 @@ related elements. ## Important Spreadsheet Parts Using the Open XML SDK for Office, 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 +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 some of the important spreadsheet elements. | Package Part| Top Level SpreadsheetML Element | Open XML SDK Class | Description| |:------------|:--------------------------------|:-----------------------|:-----------| -| Workbook | workbook | [Workbook](/dotnet/api/documentformat.openxml.spreadsheet.workbook) | The root element for the main document part.| -| Worksheet | worksheet | [Worksheet](/dotnet/api/documentformat.openxml.spreadsheet.worksheet) | A type of sheet that represent a grid of cells that contains text, numbers, dates or formulas. For more information, see [Working with sheets](working-with-sheets.md). | -|Chart Sheet | chartsheet | [Chartsheet](/dotnet/api/documentformat.openxml.spreadsheet.chartsheet) | A sheet that represents a chart that is stored as its own sheet. For more information, see [Working with sheets](working-with-sheets.md). | -| Table | table | [Table](/dotnet/api/documentformat.openxml.spreadsheet.table) | A logical construct that specifies that a range of data belongs to a single dataset. For more information, see [Working with SpreadsheetML tables](overview.md). | -|Pivot Table | [pivotTableDefinition](/dotnet/api/documentformat.openxml.spreadsheet.pivottabledefinition) | [PivotTableDefinition](/dotnet/api/documentformat.openxml.spreadsheet.pivottabledefinition) | A logical construct that displays aggregated view of data in an understandable layout. For more information, see [Working with PivotTables](working-with-pivottables.md). | -|Pivot Cache | pivotCacheDefinition | [PivotCacheDefinition](/dotnet/api/documentformat.openxml.spreadsheet.pivotcachedefinition) | A construct that defines the source of the data in the PivotTable. For more information, see [Working with PivotTables](working-with-pivottables.md). | -|Pivot Cache Records | pivotCacheRecords | [PivotCacheRecords](/dotnet/api/documentformat.openxml.spreadsheet.pivotcacherecords) | A cache of the source data of the PivotTable. For more information, see [Working with PivotTables](working-with-pivottables.md). | -| Calculation Chain | calcChain | [CalculationChain](/dotnet/api/documentformat.openxml.spreadsheet.calculationchain) | A construct that specifies the order in which cells in the workbook were last calculated. For more information, see [Working with the calculation chain](working-with-the-calculation-chain.md). | -|Shared String Table | sst | [SharedStringTable](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringtable) | A construct that contains one occurrence of each unique string that occurs on all worksheets in a workbook. For more information, see [Working with the shared string table](working-with-the-shared-string-table.md). | -|Conditional Formatting | conditionalFormatting | [ConditionalFormatting](/dotnet/api/documentformat.openxml.spreadsheet.conditionalformatting) | A construct that defines a format applied to a cell or series of cells. For more information, see [Working with conditional formatting](working-with-conditional-formatting.md). | -| Formulas | f | [CellFormula](/dotnet/api/documentformat.openxml.spreadsheet.cellformula) | A construct that defines the formula text for a cell that contains a formula. For more information, see [Working with formulas](working-with-formulas.md). | +| Workbook | `` | | The root element for the main document part.| +| Worksheet | `` | | A type of sheet that represent a grid of cells that contains text, numbers, dates or formulas. For more information, see [Working with sheets](working-with-sheets.md). | +|Chart Sheet | `` | | A sheet that represents a chart that is stored as its own sheet. For more information, see [Working with sheets](working-with-sheets.md). | +| Table | `
` | | A logical construct that specifies that a range of data belongs to a single dataset. For more information, see [Working with SpreadsheetML tables](overview.md). | +|Pivot Table | `` | | A logical construct that displays aggregated view of data in an understandable layout. For more information, see [Working with PivotTables](working-with-pivottables.md). | +|Pivot Cache | `` | | A construct that defines the source of the data in the PivotTable. For more information, see [Working with PivotTables](working-with-pivottables.md). | +|Pivot Cache Records | `` | | A cache of the source data of the PivotTable. For more information, see [Working with PivotTables](working-with-pivottables.md). | +| Calculation Chain | `` | | A construct that specifies the order in which cells in the workbook were last calculated. For more information, see [Working with the calculation chain](working-with-the-calculation-chain.md). | +|Shared String Table | `` | | A construct that contains one occurrence of each unique string that occurs on all worksheets in a workbook. For more information, see [Working with the shared string table](working-with-the-shared-string-table.md). | +|Conditional Formatting | `` | | A construct that defines a format applied to a cell or series of cells. For more information, see [Working with conditional formatting](working-with-conditional-formatting.md). | +| Formulas | `` | | A construct that defines the formula text for a cell that contains a formula. For more information, see [Working with formulas](working-with-formulas.md). | -------------------------------------------------------------------------------- ## Minimum Workbook Scenario @@ -60,13 +60,13 @@ introduces the minimum workbook scenario. The smallest possible (blank) workbook must contain the following: -A single sheet +A single sheet -A sheet ID +A sheet ID -A relationship Id that points to the location of the sheet definition +A relationship Id that points to the location of the sheet definition -© Ecma International: December 2006. +© Ecma International: December 2006. ### Open XML SDK Code Example @@ -74,10 +74,10 @@ This code example uses the classes in the Open XML SDK to create a minimum, blank workbook. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/structure_ofml/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/structure_ofml/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/structure_ofml/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/structure_ofml/vb/Program.vb#snippet0)] ### Generated SpreadsheetML @@ -93,13 +93,14 @@ workbook. Figure 1. .zip folder structure - - ![Structure of a minimum workbook](../media/odc_oxml_xl_documentstructure_fig02.gif) -The **workbook.xml** file contains \<**sheet**\> elements that reference the worksheets in + + ![Structure of a minimum workbook](../media/odc_oxml_xl_documentstructure_fig02.gif) + +The **workbook.xml** file contains `` elements that reference the worksheets in the workbook. Each worksheet is associated to the workbook via a Sheet -ID and a relationship ID. The **sheetID** is +ID and a relationship ID. The `sheetID` is the ID used within the package to identify a sheet and must be unique -within the workbook. The **id** is the +within the workbook. The `id` is the relationship ID that identifies the sheet part definition associated with a sheet. @@ -117,7 +118,7 @@ the Open XML SDK code to create a minimum workbook. ``` The **workbook.xml.rels** file contains the -\<**Relationship**\> elements that define the +`` elements that define the relationships between the workbook and the worksheets it contains. The following XML code is the spreadsheetML that represents the @@ -131,9 +132,9 @@ when you run the Open XML SDK to create a minimum workbook. ``` -The **sheet.xml** file contains the \<**sheetData**\> element that represents the cell -table. In this example, the workbook is blank, so the \<**sheetData**\> element is empty. For more -information about sheets, see [Working with sheets](working-with-sheets.md)**. +The **sheet.xml** file contains the `` element that represents the cell +table. In this example, the workbook is blank, so the `` element is empty. For more +information about sheets, see [Working with sheets](working-with-sheets.md). The following XML code is the spreadsheetML that represents the worksheet part of the spreadsheet document. This code is generated when @@ -148,6 +149,7 @@ you run the Open XML SDK to create a minimum workbook. -------------------------------------------------------------------------------- ## Typical Workbook Scenario + A typical workbook will not be a blank, minimum workbook. A typical workbook might contain numbers, text, charts, tables, and pivot tables. Each of these additional parts is contained within the .zip package of @@ -158,5 +160,5 @@ typical spreadsheet. Figure 2. Typical spreadsheet elements - + ![Structure of a SpreadsheetML document](../media/odc_oxml_xl_documentstructure_fig01.gif) diff --git a/docs/spreadsheet/working-with-conditional-formatting.md b/docs/spreadsheet/working-with-conditional-formatting.md index b07efd75..7b37f642 100644 --- a/docs/spreadsheet/working-with-conditional-formatting.md +++ b/docs/spreadsheet/working-with-conditional-formatting.md @@ -11,19 +11,20 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/14/2025 ms.localizationpriority: medium --- # Working with conditional formatting -This topic discusses the Open XML SDK **[ConditionalFormatting](/dotnet/api/documentformat.openxml.spreadsheet.conditionalformatting)** class and how it +This topic discusses the Open XML SDK  class and how it relates to the Open XML File Format SpreadsheetML schema. For more information about the overall structure of the parts and elements that -make up a SpreadsheetML document, see [Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md)**. +make up a SpreadsheetML document, see [Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md). --------------------------------------------------------------------------------- -## Conditional Formatting in SpreadsheetML +## Conditional Formatting in SpreadsheetML + Cell based conditional formatting provides structure to data inside a worksheet. Showing colors, in addition to showing a value, helps distinguish the relative height of those values. There are several @@ -34,33 +35,34 @@ highs and lows. Conditional formatting is applicable to a cell in a worksheet directly. The value does not have to be part of a table. All conditional formatting settings are stored at the worksheet level. -The worksheet stores one \<**conditionalFormatting**\> element for each format +The worksheet stores one `` element for each format applied to a cell or series of cells. The collection of cells on which -the format is applied is defined using the **sqref** attribute. The **sqref** attribute specifies a cell range using the +the format is applied is defined using the `sqref` attribute. The `sqref` attribute specifies a cell range using the 'from:to' notation, for example 'A1:A10'. The following table lists the common Open XML SDK classes used when -working with the **ConditionalFormatting** +working with the `ConditionalFormatting` class. | **SpreadsheetML Element** | **Open XML SDK Class** | |---------------------------|------------------------------------------------------------------------------------------------------------------------------------------------| -| cfRule | [ConditionalFormattingRule](/dotnet/api/documentformat.openxml.spreadsheet.conditionalformattingrule) | -| dataBar | [DataBar](/dotnet/api/documentformat.openxml.spreadsheet.databar) | -| colorScale | [ColorScale](/dotnet/api/documentformat.openxml.spreadsheet.colorscale) | -| iconSet | [IconSet](/dotnet/api/documentformat.openxml.spreadsheet.iconset) | +| `` | | +| `` | | +| `` | | +| `` | | -------------------------------------------------------------------------------- -## Open XML SDK Conditional Formatting Class -The Open XML SDK**ConditionalFormatting** -class represents the table (\<**conditionalFormatting**\>) element defined in the -Open XML File Format schema for SpreadsheetML documents. Use the **ConditionalFormatting** class to manipulate -individual \<**conditionalFormatting**\> +## Open XML SDK Conditional Formatting Class + +The Open XML SDK `ConditionalFormatting` +class represents the table (``) element defined in the +Open XML File Format schema for SpreadsheetML documents. Use the `ConditionalFormatting` class to manipulate +individual `` elements in a SpreadsheetML document. The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the **ConditionalFormatting** (\<**conditionalFormatting**\>) element. +specification introduces the `ConditionalFormatting` (``) element. A Conditional Format is a format, such as cell shading or font color, that a spreadsheet application can automatically apply to cells if a @@ -77,13 +79,13 @@ applied to cells that match the criteria. ``` -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Conditional Formatting Rule Class The following information from the ISO/IEC 29500 specification -introduces the **ConditionalFormattingRule** -(\<**cfRule**\>) element. +introduces the `ConditionalFormattingRule` +(``) element. This collection represents a description of a conditional formatting rule. @@ -92,7 +94,7 @@ Example: This example shows a conditional formatting rule highlighting cells whose values are greater than 0.5. Note that in this case the content of -\ is a static value, but can also be a formula expression. +`` is a static value, but can also be a formula expression. ```xml @@ -106,18 +108,18 @@ whose values are greater than 0.5. Note that in this case the content of Only rules with a type attribute value of expression support formula syntax. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] Each conditional format is allowed to specify various formatting rules. You can apply color scale and data bar formatting at the same time for instance. Each conditional format is represented using a separate -\<**cfRule**\> element. To specify their user -interface display priority you can use the **priority** attribute. Because a \<**conditionalFormatting**\> element can overlap other +`` element. To specify their user +interface display priority you can use the `priority` attribute. Because a `` element can overlap other formatted areas on the worksheet the priority is global for all the conditional formats defined for that worksheet. -The \<**cfRule**\> element has many formatting -types, such as **cellIs** and **top10**, which can be applied. Each type of +The `` element has many formatting +types, such as `cellIs` and `top10`, which can be applied. Each type of formatting uses common elements to define its settings. For more information about conditional formatting rule attributes, see the ISO/IEC 29500 specification. @@ -125,7 +127,7 @@ ISO/IEC 29500 specification. ### Data Bar Class The following information from the ISO/IEC 29500 specification -introduces the **DataBar** (\<**dataBar**\>) element. +introduces the `DataBar` (``) element. Describes a data bar conditional formatting rule. @@ -154,28 +156,28 @@ default, 10% and 90% respectively.) The minimum difference in length (or increment amount) is 1 pixel. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] Data bars take a single color and display it as a bar. The length of the bar indicates the relative height of the cell value. A data bar uses a separate model inside the conditional formatting rule to define its -settings. The \<**dataBar**\> element stores +settings. The `` element stores all the relevant data. A data bar requires three settings: the minimum and maximum values to compare cell values to, and a color. The first -\<**cfvo**\> element, or conditional format -value object, defines the minimum value, the second \<**cfvo**\> elements defines the maximum value. You +`` element, or conditional format +value object, defines the minimum value, the second `` elements defines the maximum value. You can use different ways to specify a value, like using a formula or hard-coded value. Another common option is to use the 'min' and 'max' -types. These \<**cfvo**\> element types specify +types. These `` element types specify the minimum and maximum values found in the cell range that have the format applied. This provides a clean stepped gradient between the lowest and highest items. In addition, you can specify the color of the -data bar by using the \<**color**\> element. +data bar by using the `` element. ### Color Scale Class The following information from the ISO/IEC 29500 specification -introduces the **ColorScale** (\<**colorScale**\>) element. +introduces the `ColorScale` (``) element. Describes a gradated color scale in this conditional formatting rule. @@ -189,21 +191,21 @@ Example: ``` -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] Color scales provide a display that indicates the relative value between all cell items, similar to a data bar. A color scale uses a separate model inside the conditional formatting rule to define its settings. You -can specify up to three \<**cfvo**\>, or +can specify up to three ``, or conditional format value object, element values: one for the start of the scale, one for the middle of the scale, and one for the end of the scale. The middle value is optional. In addition, you can specify the -color of the color scale by using the \<**color**\> element. +color of the color scale by using the `` element. ### Icon Set Class The following information from the ISO/IEC 29500 specification -introduces the **IconSet** (\<**iconSet**\>) element. +introduces the `IconSet` (``) element. Describes an icon set conditional formatting rule. @@ -222,13 +224,13 @@ value is greater than or equal to the 67th percentile. ``` -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] Using icon sets you can apply different sets of icons to the cells that contain your data. The icon set uses a range of values to identify which -set of cells to apply the formatting rule to. The first \<**cfvo**\> element identifies the lowest value of the -range, the second \<**cfvo**\>element -identifies the middle point, and the third \<**cfvo**\> element identifies the highest value. An +set of cells to apply the formatting rule to. The first `` element identifies the lowest value of the +range, the second ``element +identifies the middle point, and the third `` element identifies the highest value. An icon set identifies which icons to apply to the cells. You can choose from various hard coded icons. For more information about what icons are available, see the ISO/IEC 29500 specification. diff --git a/docs/spreadsheet/working-with-formulas.md b/docs/spreadsheet/working-with-formulas.md index 08d63229..c900c987 100644 --- a/docs/spreadsheet/working-with-formulas.md +++ b/docs/spreadsheet/working-with-formulas.md @@ -11,42 +11,41 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/14/2025 ms.localizationpriority: high --- # Working with formulas -This topic discusses the Open XML SDK [CellFormula](/dotnet/api/documentformat.openxml.spreadsheet.cellformula) class and how it relates to the +This topic discusses the Open XML SDK  class and how it relates to the Open XML File Format SpreadsheetML schema. For more information about the overall structure of the parts and elements that make up a -SpreadsheetML document, see [Structure of a -SpreadsheetML document (Open XML -SDK)](structure-of-a-spreadsheetml-document.md). +SpreadsheetML document, see [Structure of a SpreadsheetML document (Open XML SDK)](structure-of-a-spreadsheetml-document.md). -------------------------------------------------------------------------------- ## Formulas in SpreadsheetML + You can use formulas to create computational models. Formulas allow for automatic calculation of values based on data inside and outside the spreadsheet or the output of other computed cells in the spreadsheet. Formulas are stored inside each cell that uses a formula, in the -worksheet XML file. Use the **CellFormula** -(\<**f**\>) element to define the formula text. +worksheet XML file. Use the `CellFormula` +(``>) element to define the formula text. Formulas can contain mathematical expressions that include a wide range of predefined functions. -The **CellValue** (\<**v**\>) element, stores the cached formula value +The `CellValue` (``>) element, stores the cached formula value based on the last time the formula was calculated. This allows the user to postpone calculation of the formula values when the spreadsheet is opened, which saves time when opening a worksheet. You do not have to specify the value, and if you omit it, it is the responsibility of the Open XML reader to compute the value based on the formula definition -when the worksheet is opened. For more information about the **CellValue** class, see [CellValue](/dotnet/api/documentformat.openxml.spreadsheet.cellvalue). +when the worksheet is opened. For more information about the `CellValue` class, see . The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the **cellFormula** -(\<**f**\>) element. +specification introduces the `cellFormula` +(``>) element. A SpreadsheetML formula is the syntactic representation of a series of calculations that is parsed or interpreted by the spreadsheet @@ -56,7 +55,7 @@ based upon zero-to-many inputs. A formula is an expression that can contain the following: constants, operators, cell references, calls to functions, and names. -**Example**: Consider the formula PI()\*(A2^2). In this case, +`Example`: Consider the formula PI()\*(A2^2). In this case, - PI() results in a call to the function PI, which returns the value of π. - The cell reference A2 returns the value in that cell. @@ -103,7 +102,7 @@ An array value or constant represents a collection of one or more elements, whose values can have any type (i.e., the elements of an array need not all have the same type). -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] For more information about formula syntax see the ISO/IEC 29500 specification. diff --git a/docs/spreadsheet/working-with-pivottables.md b/docs/spreadsheet/working-with-pivottables.md index eea2e369..45ab2c45 100644 --- a/docs/spreadsheet/working-with-pivottables.md +++ b/docs/spreadsheet/working-with-pivottables.md @@ -11,17 +11,18 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/14/2025 ms.localizationpriority: high --- # Working with PivotTables -This topic discusses the Open XML SDK **[PivotTableDefinition](/dotnet/api/documentformat.openxml.spreadsheet.pivottabledefinition)** class and how it relates to the Open XML File Format SpreadsheetML schema. For more information about the overall structure of the parts and elements that make up a SpreadsheetML document, see [Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md). +This topic discusses the Open XML SDK  class and how it relates to the Open XML File Format SpreadsheetML schema. For more information about the overall structure of the parts and elements that make up a SpreadsheetML document, see +[Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md). ## PivotTable in SpreadsheetML -The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the **PivotTableDefinition** (\<**pivotTableDefinition**\>) element. +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `PivotTableDefinition` (``) element. PivotTables display aggregated views of data easily and in an understandable layout. Hundreds or thousands of pieces of underlying @@ -85,18 +86,18 @@ is displayed in the cells of a worksheet and therefore you need to construct them as well. You can also have the user update the PivotTable cells when opening the document. -The following table lists the common Open XML SDK classes used when working with the **PivotTableDefinition** class. +The following table lists the common Open XML SDK classes used when working with the `PivotTableDefinition` class. | **SpreadsheetML Element** | **Open XML SDK Class** | |---------------------------|-------------------------------------------------------------------------------------------------------------------| -| pivotField | [PivotField](/dotnet/api/documentformat.openxml.spreadsheet.pivotfield) | -| pivotCacheDefinition | [PivotCacheDefinition](/dotnet/api/documentformat.openxml.spreadsheet.pivotcachedefinition) | -| pivotCacheRecords | [PivotCacheRecords](/dotnet/api/documentformat.openxml.spreadsheet.pivotcacherecords) | +| `` | | +| `` | | +| `` | | ## Open XML SDK PivotTableDefinition Class -The Open XML SDK**PivotTableDefinition** -class represents the PivotTable definition (\<**pivotTableDefinition**\>) element defined in the Open XML File Format schema for SpreadsheetML documents. Use the **PivotTableDefinition** class to manipulate individual \<**pivotTableDefinition**\> elements in a SpreadsheetML document. +The Open XML SDK `PivotTableDefinition` +class represents the PivotTable definition (``) element defined in the Open XML File Format schema for SpreadsheetML documents. Use the `PivotTableDefinition` class to manipulate individual `` elements in a SpreadsheetML document. The main function of the PivotTable definition is to store information about which field is displayed on which axis of the PivotTable and in @@ -109,30 +110,30 @@ added to the workbook part, and defines the caption label to display above the data area of the PivotTable. All of these elements are required. -The three main pieces of the **pivotTableDefinition** are: the location of the +The three main pieces of the `PivotTableDefinition` are: the location of the table, the display information for the cached fields, and the positioning information of the cached fields. For more information about -these and other additional elements that make up the **pivotTableDefinition**, see the ISO/IEC 29500 +these and other additional elements that make up the `PivotTableDefinition`, see the ISO/IEC 29500 specification. ### PivotField Class -The **PivotTableDefinition** element contains the **PivotField** (\<**pivotField**\>) elements. The following information from the ISO/IEC 29500 specification introduces the **PivotField** (\<**pivotField**\>) element. +The `PivotTableDefinition` element contains the `PivotField` (``) elements. The following information from the ISO/IEC 29500 specification introduces the `PivotField` (``) element. Represents a single field in the PivotTable. This element contains information about the field, including the collection of items in the field. First, define the collection of fields that appear on the PivotTable -using the **pivotFields** element. Each field +using the `pivotFields` element. Each field serves as a cache for the data of that field in the data source. You do -not need to define the cache. Instead, you can set the **item** element equal to **default** and have the user update the table when -they open the document. The **showAll** +not need to define the cache. Instead, you can set the `item` element equal to `default` and have the user update the table when +they open the document. The `showAll` attribute is used to hide certain elements for that data dimension. After defining which fields are part of the table, the fields are applied to the four areas of the PivotTable. ### Pivot Cache Definition Class -The following information from the ISO/IEC 29500 specification introduces the **PivotCacheDefinition** (\<**pivotCacheDefinition**\>) element. +The following information from the ISO/IEC 29500 specification introduces the `PivotCacheDefinition` (``) element. The pivotCacheDefinition part defines each field in the pivotCacheRecords part, including field name and information about the @@ -155,17 +156,17 @@ when you pivot the table. There are various types of data sources, for example: worksheets, database, OLAP cube, and other PivotTables. The last part of the cache definition defines the fields of the data -source using the **cacheField** element. The -**cacheField** element is used for two +source using the `cacheField` element. The +`cacheField` element is used for two purposes: it defines the data type and formatting of the field, and it is used as a cache for shared strings. The pivot values are stored in the pivot cache records part. When a recurring string is used as a -value, the cache record uses a reference into the **cacheField** collection of shared items. +value, the cache record uses a reference into the `cacheField` collection of shared items. ### Pivot Cache Records Class -The following information from the ISO/IEC 29500 specification introduces the **PivotCacheRecords** (\<**pivotCacheRecords**\>) element. +The following information from the ISO/IEC 29500 specification introduces the `PivotCacheRecords` (``) element. The pivotCacheRecords part contains the underlying data to be aggregated. It is a cache of the source data. -The cache records part can store any number of cached records. Each record has the same number of values defined as there are fields in the cache definition. Each record is defined with the **r** element. This record contains value items as child elements. You can provide certain typed values, such as Numeric, Boolean, or Date-Time, or you can reference into the shared items. +The cache records part can store any number of cached records. Each record has the same number of values defined as there are fields in the cache definition. Each record is defined with the `r` element. This record contains value items as child elements. You can provide certain typed values, such as Numeric, Boolean, or Date-Time, or you can reference into the shared items. diff --git a/docs/spreadsheet/working-with-sheets.md b/docs/spreadsheet/working-with-sheets.md index 918df05c..1b98b40f 100644 --- a/docs/spreadsheet/working-with-sheets.md +++ b/docs/spreadsheet/working-with-sheets.md @@ -11,12 +11,12 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/14/2025 ms.localizationpriority: high --- # Working with sheets -This topic discusses the Open XML SDK [Worksheet](/dotnet/api/documentformat.openxml.spreadsheet.worksheet), [Chartsheet](/dotnet/api/documentformat.openxml.spreadsheet.chartsheet), and [DialogSheet](/dotnet/api/documentformat.openxml.spreadsheet.dialogsheet) classes and how they relate to +This topic discusses the Open XML SDK , , and classes and how they relate to the Open XML File Format SpreadsheetML schema. For more information about the overall structure of the parts and elements that make up a SpreadsheetML document, see [Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md). @@ -25,7 +25,7 @@ SpreadsheetML document, see [Structure of a SpreadsheetML document](structure-of ## Sheets in SpreadsheetML The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the **sheet** (\<**sheet**\>) element. +specification introduces the **sheet** (``) element. Sheets are the central structures within a workbook, and are where the user does most of their spreadsheet work. The most common type of sheet @@ -40,17 +40,17 @@ these are also included in the sheet definition on disk. Other types of sheets include chart sheets and dialog sheets. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ## Open XML SDK Worksheet Class -The Open XML SDK**Worksheet** class -represents the **worksheet** (\<**worksheet**\>) element defined in the Open XML File -Format schema for SpreadsheetML documents. Use the **Worksheet** class to manipulate individual \<**worksheet**\> elements in a SpreadsheetML document. +The Open XML SDK `Worksheet` class +represents the `worksheet` (``) element defined in the Open XML File +Format schema for SpreadsheetML documents. Use the `Worksheet` class to manipulate individual `` elements in a SpreadsheetML document. The following information from the ISO/IEC 29500 specification -introduces the **worksheet** (\<**worksheet**\>) element. +introduces the `worksheet` (``) element. An instance of this part type contains all the data, formulas, and characteristics associated with a given worksheet. @@ -80,39 +80,39 @@ simplify the logic required to insert a new sheetData collection into an existing (but empty) sheet, the sheetData collection is required, even when empty. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] A typical spreadsheet has at least one worksheet. The worksheet contains -a table like structure for defining data, represented by the **sheetData** element. A sheet that contains data -uses the **worksheet** element as the root +a table like structure for defining data, represented by the `sheetData` element. A sheet that contains data +uses the `worksheet` element as the root element for defining worksheets. Inside a worksheet the data is split up into three distinct sections. The first section contains optional sheet properties. The second section contains the data, using the required -**sheetData** element. The third section contains optional supporting +`sheetData` element. The third section contains optional supporting features such as sheet protection and filter information. To define an -empty worksheet you only have to use the **worksheet** and **sheetData** elements. The **sheetData** element can be empty. - -To create new values for the worksheet you define rows inside the **sheetData** element. These rows contain cells, -which contain values. The **row** element -defines a new row. Normally the first row in the **sheetData** is the first row in the visible sheet. -Inside the row you create new **cells** using the \<**c**\> element. Values for cells can be provided by -storing a \<**v**\> element inside the cell. -Usually the \<**v**\> element contains the +empty worksheet you only have to use the `worksheet` and `sheetData` elements. The `sheetData` element can be empty. + +To create new values for the worksheet you define rows inside the `sheetData` element. These rows contain cells, +which contain values. The `row` element +defines a new row. Normally the first row in the `sheetData` is the first row in the visible sheet. +Inside the row you create new `cells` using the `` element. Values for cells can be provided by +storing a `` element inside the cell. +Usually the `` element contains the current value of the worksheet cell. If the value is a numeric value, it -is stored directly in the \<**v**\> element in +is stored directly in the `` element in the XML file. If the value is a string value, it is stored in a shared string table. For more information about using the shared string table to store string values, see [Working with the shared string table](working-with-the-shared-string-table.md). The following table lists the common Open XML SDK classes used when -working with the [Worksheet](/dotnet/api/documentformat.openxml.spreadsheet.worksheet) class. +working with the class. | **SpreadsheetML Element** | **Open XML SDK Class** | |---|---| -| sheetData | [SheetData](/dotnet/api/documentformat.openxml.spreadsheet.sheetdata) | -| row | [Row](/dotnet/api/documentformat.openxml.spreadsheet.row) | -| c | [Cell](/dotnet/api/documentformat.openxml.spreadsheet.cell) | -| v | [CellValue](/dotnet/api/documentformat.openxml.spreadsheet.cellvalue) | +| `` | | +| `` | | +| `` | | +| `` | | For more information about optional spreadsheet elements, such as sheet properties and supporting sheet features, see the ISO/IEC 29500 @@ -121,29 +121,29 @@ specification. ### SheetData Class The following information from the ISO/IEC 29500 specification -introduces the **sheet data** (\<**sheetData**\>) element. +introduces the **sheet data** (``) element. The cell table is the core structure of a worksheet. It consists of all the text, numbers, and formulas in the grid. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Row Class The following information from the ISO/IEC 29500 specification -introduces the **row** (\<**row**\>) element. +introduces the **row** (``) element. The cells in the cell table are organized by row. Each row has an index (attribute r) so that empty rows need not be written out. Each row indicates the number of cells defined for it, as well as their relative position in the sheet. In this example, the first row of data is row 2. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Cell Class The following information from the ISO/IEC 29500 specification -introduces the **cell** (\<**c**\>) element. +introduces the **cell** (``) element. The cell itself is expressed by the c collection. Each cell indicates its location in the grid using A1-style reference notation. A cell can @@ -152,19 +152,19 @@ also indicate a style identifier (attribute s) and a data type order to optimize load/save operations, default data values are not written out. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### CellValue Class The following information from the ISO/IEC 29500 specification -introduces the **cell value** (\<**v**\>) element. +introduces the **cell value** (``) element. Cells contain values, whether the values were directly entered (e.g., cell A2 in our example has the value External Link:) or are the result of a calculation (e.g., cell B3 in our example has the formula B2+1). String values in a cell are not stored in the cell table unless they are -the result of a calculation. Therefore, instead of seeing External Link: +the result of a calculation. Therefore, instead of seeing External Link as the content of the cell's v node, instead you see a zero-based index into the shared string table where that string is stored uniquely. This is done to optimize load/save performance and to reduce duplication of @@ -172,20 +172,20 @@ information. To determine whether the 0 in v is a number or an index to a string, the cell's data type must be examined. When the data type indicates string, then it is an index and not a numeric value. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### Open XML SDK Code Example The following code example creates a spreadsheet document with the -specified file name and instantiates a **Worksheet** class, and then adds a row and adds a +specified file name and instantiates a `Worksheet` class, and then adds a row and adds a cell to the cell table at position A1. Then the value of the cell in A1 is set equal to the numeric value 100. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/working_with_sheets/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/working_with_sheets/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/working_with_sheets/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/working_with_sheets/vb/Program.vb#snippet0)] ### Generated SpreadsheetML @@ -208,7 +208,7 @@ the "sheet.xml" file in the "worksheets" folder of the .zip file. ## The Open XML SDK Chartsheet Class The following information from the ISO/IEC 29500 specification -introduces the **chartsheet** (\<**chartsheet**\>) element. +introduces the **chartsheet** (``) element. An instance of this part type represents a chart that is stored in its own sheet. @@ -227,19 +227,19 @@ relationship in the Chartsheet part's relationship item: ``` -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following table lists the common Open XML SDK classes used when -working with the [Chartsheet](/dotnet/api/documentformat.openxml.spreadsheet.chartsheet) class. +working with the class. | **SpreadsheetML Element** | **Open XML SDK Class** | |---|---| -| drawing | [Drawing](/dotnet/api/documentformat.openxml.spreadsheet.drawing) | +| `` | | ### Drawing Class The following information from the ISO/IEC 29500 specification -introduces the **drawings** (\<**wsDr**\>) element. +introduces the **drawings** (``) element. An instance of this part type contains the presentation and layout information for one or more drawing elements that are present on this @@ -250,13 +250,13 @@ such part shall be the target of an explicit relationship from a Worksheet part (§12.3.24), or a Chartsheet part (§12.3.2). There shall be only one Drawings part per worksheet or chartsheet. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ## Open XML SDK Dialogsheet Class The following information from the ISO/IEC 29500 specification -introduces the **dialogsheet** (\<**dialogsheet**\>) element. +introduces the **dialogsheet** (``) element. An instance of this part type contains information about a legacy custom dialog box for a user form. @@ -280,4 +280,4 @@ Example: sheet1.xml contains the following: ``` -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] diff --git a/docs/spreadsheet/working-with-tables.md b/docs/spreadsheet/working-with-tables.md index 5aba0b64..191597a4 100644 --- a/docs/spreadsheet/working-with-tables.md +++ b/docs/spreadsheet/working-with-tables.md @@ -11,21 +11,20 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/14/2025 ms.localizationpriority: high --- # Working with SpreadsheetML tables -This topic discusses the Open XML SDK **[Table](/dotnet/api/documentformat.openxml.spreadsheet.table)** class and how it relates to the Open +This topic discusses the Open XML SDK  class and how it relates to the Open XML File Format SpreadsheetML schema. For more information about the overall structure of the parts and elements that make up a SpreadsheetML -document, see [Structure of a SpreadsheetML document -(Open XML SDK)](structure-of-a-spreadsheetml-document.md). +document, see [Structure of a SpreadsheetML document (Open XML SDK)](structure-of-a-spreadsheetml-document.md). ## Tables in SpreadsheetML -The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the **table** (\<**table**\>) element. +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `table` (`
`) element. A table helps organize and provide structure to lists of information in a worksheet. Tables have clearly labeled columns, rows, and data @@ -54,7 +53,7 @@ the various attributes for the particular table object. A SpreadsheetML table is a logical construct that specifies that a range of data belongs to a single dataset. SpreadsheetML already uses a table-like model for specifying values in rows and columns, but you can -also label a subset of the sheet as a **table** +also label a subset of the sheet as a `table` and give it certain properties that are useful for analysis. A table in SpreadsheetML allows you to analyze data in new ways, such as by using filtering, formatting and binding of data. @@ -64,23 +63,23 @@ in a separate part inside the package. The table part does not contain any table data. The data is maintained in the worksheet cells. For more information about data is stored in the worksheet, see [Working with sheets](working-with-sheets.md). -The following table lists the common Open XML SDK classes used when working with the **Table** class. +The following table lists the common Open XML SDK classes used when working with the `Table` class. | **SpreadsheetML Element** | **Open XML SDK Class** | |---------------------------|------------------------------------------------------------------------------------------------------------------------| -| tableColumn | [TableColumn](/dotnet/api/documentformat.openxml.spreadsheet.tablecolumn) | -| autoFilter | [AutoFilter](/dotnet/api/documentformat.openxml.spreadsheet.table.autofilter) | +| `` | | +| `` | | ## Open XML SDK Table Class -The Open XML SDK**Table** class represents -the table (\<**table**\>) element defined in +The Open XML SDK `Table` class represents +the table (`
`) element defined in the Open XML File Format schema for SpreadsheetML documents. Use the -**Table** class to manipulate individual -\<**table**\> elements in a SpreadsheetML +`Table` class to manipulate individual +`
` elements in a SpreadsheetML document. -The following information from the ISO/IEC 29500 specification introduces the **table** (\<**table**\>) element. +The following information from the ISO/IEC 29500 specification introduces the `table` (`
`) element. An instance of this part type contains a description of a single table and its autofilter information. (The data for the table is stored in the @@ -96,13 +95,13 @@ enable autofiltering you must define at least one autofilter, which can be empty. If you do not define any autofilter, autofiltering will be disabled when the document is opened in Excel. -The **table** element has several attributes -used to identify the table and the data range it covers. The **id** and **name** -attributes must be unique across all table parts. The **displayName** attribute must be unique across all +The `table` element has several attributes +used to identify the table and the data range it covers. The `id` and `name` +attributes must be unique across all table parts. The `displayName` attribute must be unique across all table parts and unique across all defined names in the workbook. The -**name** attribute is used by the object model -in Excel. The **displayName** attribute is used -by references in formulas. The **ref** +`name` attribute is used by the object model +in Excel. The `displayName` attribute is used +by references in formulas. The `ref` attribute is used to identify the cell range that the table covers. This includes not only the table data, but also the table header containing column names. For more information about table attributes, see the @@ -110,18 +109,18 @@ ISO/IEC 29500 specification. ### Table Column Class -To add columns to your table you add new **tableColumn** elements to the **tableColumns** collection. The collection has a +To add columns to your table you add new `tableColumn` elements to the `tableColumns` collection. The collection has a count attribute that tracks the number of columns. The following information from the ISO/IEC 29500 specification -introduces the **TableColumn** (\<**tableColumn**\>) element. +introduces the `TableColumn` (``) element. An element representing a single column for this table. ### Auto Filter Class The following information from the ISO/IEC 29500 specification -introduces the **AutoFilter** (\<**autoFilter**\>) element. +introduces the `AutoFilter` (``) element. AutoFilter temporarily hides rows based on filter criteria, which is applied column by column to a table of data in the worksheet. This @@ -151,7 +150,7 @@ The table contains three columns and three rows, plus a column header. The following XML defines the worksheet and is contained in the "sheet1.xml" file. The worksheet XML file contains the actual data -displayed in the table, and contains the **tablePart** element that references the +displayed in the table, and contains the `tablePart` element that references the "table1.xml" file, which contains the table definition. ```xml diff --git a/docs/spreadsheet/working-with-the-calculation-chain.md b/docs/spreadsheet/working-with-the-calculation-chain.md index 47b33de0..c1bf0363 100644 --- a/docs/spreadsheet/working-with-the-calculation-chain.md +++ b/docs/spreadsheet/working-with-the-calculation-chain.md @@ -11,12 +11,12 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/14/2025 ms.localizationpriority: high --- # Working with the calculation chain -This topic discusses the Open XML SDK [CalculationChain](/dotnet/api/documentformat.openxml.spreadsheet.calculationchain) class and how it relates +This topic discusses the Open XML SDK  class and how it relates to the Open XML File Format SpreadsheetML schema. For more information about the overall structure of the parts and elements that make up a SpreadsheetML document, see [Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md). @@ -25,7 +25,7 @@ SpreadsheetML document, see [Structure of a SpreadsheetML document](structure-of ## CalculationChain in SpreadsheetML The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the **CalculationChain** (\<**calcChain**\>) element. +specification introduces the `CalculationChain` (``) element. An instance of this part type contains an ordered set of references to all cells in all worksheets in the workbook whose value is calculated @@ -67,41 +67,41 @@ expressed in the Calculation Chain part does not force or dictate to the implementing application the order in which calculations must be performed at runtime. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] The following table lists the common Open XML SDK classes used when -working with the **CalculationChain** class. +working with the `CalculationChain` class. | **SpreadsheetML Element** | **Open XML SDK Class** | |---------------------------|----------------------------| -| c | CalculationCell | +| `` | CalculationCell | ## Open XML SDK CalculationChain Class -The Open XML SDK**CalculationChain** class -represents the paragraph (\<**calcChain**\>) +The Open XML SDK `CalculationChain` class +represents the paragraph (``) element defined in the Open XML File Format schema for SpreadsheetML -documents. Use the **CalculationChain** class -to manipulate individual \<**calcChain**\> +documents. Use the `CalculationChain` class +to manipulate individual `` elements in a SpreadsheetML document. ### Calculation Cell Class -The **CalculationCell** class represents the -cell (\<**si**\>) element that represents a +The `CalculationCell` class represents the +cell (``) element that represents a cell that contains a formula. The following information from the ISO/IEC 29500 specification -introduces the **CalculationCell** (\<**c**\>) element. +introduces the `CalculationCell` (``) element. Every c element represents a cell containing a formula. The first cell -calculated appears first (top-tobottom), and so on. The reference +calculated appears first (top-to-bottom), and so on. The reference attribute r indicates the cell's address in the sheet. The index attribute i indicates the index of the sheet with which that cell is associated. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ### SpreadsheetML diff --git a/docs/spreadsheet/working-with-the-shared-string-table.md b/docs/spreadsheet/working-with-the-shared-string-table.md index b299e957..a136770c 100644 --- a/docs/spreadsheet/working-with-the-shared-string-table.md +++ b/docs/spreadsheet/working-with-the-shared-string-table.md @@ -11,21 +11,22 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 01/14/2025 ms.localizationpriority: high --- # Working with the shared string table -This topic discusses the Open XML SDK [SharedStringTable](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringtable) class and how it relates +This topic discusses the Open XML SDK  class and how it relates to the Open XML File Format SpreadsheetML schema. For more information about the overall structure of the parts and elements that make up a SpreadsheetML document, see [Structure of a SpreadsheetML document](structure-of-a-spreadsheetml-document.md). -------------------------------------------------------------------------------- -## SharedStringTable in SpreadsheetML +## SharedStringTable in SpreadsheetML + The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] -specification introduces the **SharedStringTable** (\<**sst**\>) element. +specification introduces the `SharedStringTable` (``) element. An instance of this part type contains one occurrence of each unique string that occurs on all worksheets in a workbook. @@ -41,7 +42,7 @@ table that is shared across the workbook is to improve performance in opening and saving the file by only reading and writing the repetitive information once. -© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] +© [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] Shared strings optimize space requirements when the spreadsheet contains multiple instances of the same string. Spreadsheets that contain @@ -69,27 +70,28 @@ strings that can appear multiple times in one sheet or in multiple sheets. The following table lists the common Open XML SDK classes used when -working with the **SharedStringTable** class. +working with the SharedStringTable class. | **SpreadsheetML Element** | **Open XML SDK Class** | |---------------------------|------------------------------------------------------------------------------------------------------------------------------| -| si | [SharedStringItem](/dotnet/api/documentformat.openxml.spreadsheet.sharedstringitem) | -| t | [Text](/dotnet/api/documentformat.openxml.spreadsheet.text) | +| `` | | +| `` | | -------------------------------------------------------------------------------- -## Open XML SDK SharedStringTable Class -The Open XML SDK**SharedStringTable** class -represents the paragraph (\<**sst**\>) element +## Open XML SDK SharedStringTable Class + +The Open XML SDK `SharedStringTable` class +represents the paragraph (``) element defined in the Open XML File Format schema for SpreadsheetML documents. -Use the **SharedStringTable** class to -manipulate individual \<**sst**\> elements in a +Use the `SharedStringTable` class to +manipulate individual `` elements in a SpreadsheetML document. ### Shared String Item Class -The **SharedStringItem** class represents the -shared string item (\<**si**\>) element which +The `SharedStringItem` class represents the +shared string item (``) element which represents an individual string in the shared string table. If the string is a simple string with formatting applied at the cell @@ -107,9 +109,9 @@ text is stored in the shared string table. The next two strings ("Cell A2" and "Cell B2") contain character level formatting. The word "Cell" is formatted differently from "A2" and "B2", therefore the formatting for the cells is stored along with the text within the shared string -item using the **RichTextRun** (\<**r**\>) and **RunProperties** (\<**rPr**\>) elements. To preserve the white space in -between the text that is formatted differently, the **space** attribute of the **text** (\<**t**\>) element -is set equal to **preserve**. For more +item using the `RichTextRun` (``) and `RunProperties` (``) elements. To preserve the white space in +between the text that is formatted differently, the `space` attribute of the `text` (``) element +is set equal to `preserve`. For more information about the rich text run and run properties elements, see the ISO/IEC 29500 specification. @@ -195,24 +197,24 @@ ISO/IEC 29500 specification. ``` ### Text Class -The **Text** class represents the text (\<**t**\>) element which represents the text content +The `Text` class represents the text (``) element which represents the text content shown as part of a string. ### Open XML SDK Code Example -The following code takes a **String** and a -**SharedStringTablePart** and verifies if the +The following code takes a `String` and a +`SharedStringTablePart` and verifies if the specified text exists in the shared string table. If the text does not exist, it is added as a shared string item to the shared string table. -For more information about how to use the **SharedStringTable** class to programmatically +For more information about how to use the `SharedStringTable` class to programmatically insert text into a cell, see [How to: Insert text into a cell in a spreadsheet document](how-to-insert-text-into-a-cell-in-a-spreadsheet.md). ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/working_with_the_shared_string_table/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/working_with_the_shared_string_table/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/working_with_the_shared_string_table/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/working_with_the_shared_string_table/vb/Program.vb#snippet0)] ### Generated SpreadsheetML If you run the Open XML SDK in the [How to: Insert text into a cell in a spreadsheet document](how-to-insert-text-into-a-cell-in-a-spreadsheet.md) topic and insert diff --git a/docs/toc.yml b/docs/toc.yml index 5ca0a2ed..037d90b8 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -5,10 +5,10 @@ - name: Getting started items: - name: Overview - href: getting-started.md - - name: About the Open XML SDK + href: getting-started.md + - name: About the Open XML SDK href: about-the-open-xml-sdk.md - - name: What's new in the Open XML SDK + - name: What's new in the Open XML SDK href: what-s-new-in-the-open-xml-sdk.md - name: Open XML SDK design considerations href: open-xml-sdk-design-considerations.md @@ -21,7 +21,7 @@ - name: Custom SDK Features href: general/features.md - name: Introduction to markup compatibility - href: general/introduction-to-markup-compatibility.md + href: general/introduction-to-markup-compatibility.md - name: Add a new document part that receives a relationship ID to a package href: general/how-to-add-a-new-document-part-that-receives-a-relationship-id-to-a-package.md - name: Add a new document part to a package @@ -43,9 +43,15 @@ - name: Presentations items: - name: Overview - href: presentation/overview.md + href: presentation/overview.md + - name: Add an audio file to a slide in a presentation + href: presentation/how-to-add-an-audio-to-a-slide-in-a-presentation.md - name: Add a comment to a slide in a presentation href: presentation/how-to-add-a-comment-to-a-slide-in-a-presentation.md + - name: Reply to a comment in a presentation + href: presentation/how-to-reply-to-a-comment-in-a-presentation.md + - name: Add a video to a slide in a presentation + href: presentation/how-to-add-a-video-to-a-slide-in-a-presentation.md - name: Apply a theme to a presentation href: presentation/how-to-apply-a-theme-to-a-presentation.md - name: Change the fill color of a shape in a presentation @@ -53,7 +59,7 @@ - name: Create a presentation document by providing a file name href: presentation/how-to-create-a-presentation-document-by-providing-a-file-name.md - name: Delete all the comments by an author from all the slides in a presentation - href: presentation/how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentatio.md + href: presentation/how-to-delete-all-the-comments-by-an-author-from-all-the-slides-in-a-presentation.md - name: Delete a slide from a presentation href: presentation/how-to-delete-a-slide-from-a-presentation.md - name: Get all the external hyperlinks in a presentation @@ -73,9 +79,11 @@ - name: Open a presentation document for read-only access href: presentation/how-to-open-a-presentation-document-for-read-only-access.md - name: Retrieve the number of slides in a presentation document - href: presentation/how-to-retrieve-the-number-of-slides-in-a-presentation-document.md + href: presentation/how-to-retrieve-the-number-of-slides-in-a-presentation-document.md - name: Structure of a PresentationML document href: presentation/structure-of-a-presentationml-document.md + - name: Add a transition to a slide in a presentation + href: presentation/how-to-add-transitions-between-slides-in-a-presentation.md - name: Working with animation href: presentation/working-with-animation.md - name: Working with comments @@ -102,6 +110,8 @@ href: spreadsheet/how-to-add-custom-ui-to-a-spreadsheet-document.md - name: Calculate the sum of a range of cells in a spreadsheet document href: spreadsheet/how-to-calculate-the-sum-of-a-range-of-cells-in-a-spreadsheet-document.md + - name: Copy a Worksheet Using SAX (Simple API for XML) + href: spreadsheet/how-to-copy-a-worksheet-with-sax.md - name: Create a spreadsheet document by providing a file name href: spreadsheet/how-to-create-a-spreadsheet-document-by-providing-a-file-name.md - name: Delete text from a cell in a spreadsheet @@ -153,7 +163,7 @@ - name: Overview href: word/overview.md - name: Structure of a WordprocessingML document - href: word/structure-of-a-wordprocessingml-document.md + href: word/structure-of-a-wordprocessingml-document.md - name: Accept all revisions in a word processing document href: word/how-to-accept-all-revisions-in-a-word-processing-document.md - name: Add tables to word processing documents @@ -192,6 +202,8 @@ href: word/how-to-remove-hidden-text-from-a-word-processing-document.md - name: Remove the headers and footers from a word processing document href: word/how-to-remove-the-headers-and-footers-from-a-word-processing-document.md + - name: Replace Text in a Word Document Using SAX (Simple API for XML)' + href: word/how-to-replace-text-in-a-word-document-with-sax.md - name: Replace the header in a word processing document href: word/how-to-replace-the-header-in-a-word-processing-document.md - name: Replace the styles parts in a word processing document diff --git a/docs/word/how-to-accept-all-revisions-in-a-word-processing-document.md b/docs/word/how-to-accept-all-revisions-in-a-word-processing-document.md index 0bf65264..d7e22c4f 100644 --- a/docs/word/how-to-accept-all-revisions-in-a-word-processing-document.md +++ b/docs/word/how-to-accept-all-revisions-in-a-word-processing-document.md @@ -10,7 +10,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/30/2021 +ms.date: 09/12/2024 ms.localizationpriority: high --- @@ -20,7 +20,7 @@ This topic shows how to use the Open XML SDK for Office to accept all revisions [!include[Structure](../includes/word/structure.md)] -The basic document structure of a **WordProcessingML** document consists of the **document** and **body** elements, followed by one or more block level elements such as **p**, which represents a paragraph. A paragraph contains one or more **r** elements. The **r** stands for run, which is a region of text with a common set of properties, such as formatting. A run contains one or more **t** elements. The **t** element contains a range of text. The following code example shows the **WordprocessingML** markup for a document that contains the text "Example text." +The basic document structure of a `WordProcessingML` document consists of the `document` and `body` elements, followed by one or more block level elements such as `p`, which represents a paragraph. A paragraph contains one or more `r` elements. The `r` stands for run, which is a region of text with a common set of properties, such as formatting. A run contains one or more `t` elements. The `t` element contains a range of text. The following code example shows the `WordprocessingML` markup for a document that contains the text "Example text." ```xml @@ -34,21 +34,21 @@ The basic document structure of a **WordProcessingML** document consists of the ``` -Using the Open XML SDK, you can create document structure and content using strongly-typed classes that correspond to **WordprocessingML** elements. You will find these classes in the [DocumentFormat.OpenXml.Wordprocessing](/dotnet/api/documentformat.openxml.wordprocessing) namespace. The following table lists the class names of the classes that correspond to the **document**, **body**, **p**, **r**, and **t** elements. +Using the Open XML SDK, you can create document structure and content using strongly-typed classes that correspond to `WordprocessingML` elements. You will find these classes in the namespace. The following table lists the class names of the classes that correspond to the `document`, `body`, `p`, `r`, and `t` elements. | WordprocessingML Element | Open XML SDK Class | Description | |---|---|---| -| document | [Document](/dotnet/api/documentformat.openxml.wordprocessing.document) | The root element for the main document part. | -| body | [Body](/dotnet/api/documentformat.openxml.wordprocessing.body) | The container for the block level structures such as paragraphs, tables, annotations and others specified in the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification. | -| p | [Paragraph](/dotnet/api/documentformat.openxml.wordprocessing.paragraph) | A paragraph. | -| r | [Run](/dotnet/api/documentformat.openxml.wordprocessing.run) | A run. | -| t | [Text](/dotnet/api/documentformat.openxml.wordprocessing.text) | A range of text. | +| document | | The root element for the main document part. | +| body | | The container for the block level structures such as paragraphs, tables, annotations and others specified in the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification. | +| p | | A paragraph. | +| r | | A run. | +| t | | A range of text. | ## ParagraphPropertiesChange Element -When you accept a revision mark, you change the properties of a paragraph either by deleting an existing text or inserting a new text. In the following sections, you read about three elements that are used in the code to change the paragraph contents, mainly, `` (Revision Information for Paragraph Properties), **``** (Deleted Paragraph), and **``** (Inserted Table Row) elements. +When you accept a revision mark, you change the properties of a paragraph either by deleting existing text or inserting new text. In the following sections, you read about three elements that are used in the code to change the paragraph contents, mainly, `` (Revision Information for Paragraph Properties), `` (Deleted Paragraph), and `` (Inserted Table Row) elements. -The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the **ParagraphPropertiesChange** element (**pPrChange**). +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the `ParagraphPropertiesChange` element (`pPrChange`). ### *pPrChange (Revision Information for Paragraph Properties) @@ -71,24 +71,27 @@ Consider a paragraph in a WordprocessingML document which is centered, and this ``` -The element specifies that there was a revision to the paragraph properties at 01-01-2006 by Samantha Smith, and the previous set of paragraph properties on the paragraph was the null set (in other words, no paragraph properties explicitly present under the element). **pPr** **pPrChange** +The element specifies that there was a revision to the paragraph properties at 01-01-2006 by Samantha Smith, and the previous set of paragraph properties on the paragraph was the null set (in other words, no paragraph properties explicitly present under the element). `pPr` `pPrChange` © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] ## Deleted Element The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification -introduces the Deleted element (**del**). +introduces the Deleted element (`del`). ### del (Deleted Paragraph) -This element specifies that the paragraph mark delimiting the end of a paragraph within a WordprocessingML document shall be treated as deleted (in other words, the contents of this paragraph are no longer delimited by this paragraph mark, and are combined with the following paragraph—but those contents shall not automatically be marked as deleted) as part of a tracked revision. +This element specifies that the paragraph mark delimiting the end of a paragraph within a WordprocessingML document shall be treated as deleted (in other words, the contents of this paragraph are no longer delimited by this paragraph mark, and are combined with the following paragraph, but those contents shall not automatically be marked as deleted) as part of a tracked revision. Consider a document consisting of two paragraphs (with each paragraph delimited by a pilcrow ¶): -![Two paragraphs each delimited by a pilcrow](../media/w-delparagraphs01.gif) If the physical character delimiting the end of the first paragraph is deleted and this change is tracked as a revision, the following will result: +![Two paragraphs each delimited by a pilcrow](../media/w-delparagraphs01.gif) + +If the physical character delimiting the end of the first paragraph is deleted and this change is tracked as a revision, the following will result: ![Two paragraphs delimited by a single pilcrow](../media/w-delparagraphs02.gif) + This revision is represented using the following WordprocessingML: ```xml @@ -109,7 +112,7 @@ This revision is represented using the following WordprocessingML: ``` -The **del** element on the run properties for +The `del` element on the run properties for the first paragraph mark specifies that this paragraph mark was deleted, and this deletion was tracked as a revision. @@ -118,7 +121,7 @@ and this deletion was tracked as a revision. ## The Inserted Element The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification -introduces the Inserted element (**ins**). +introduces the Inserted element (`ins`). ### ins (Inserted Table Row) @@ -156,23 +159,93 @@ using the following WordprocessingML: ``` -The **ins** element on the table row properties for the second table row +The `ins` element on the table row properties for the second table row specifies that this row was inserted, and this insertion was tracked as a revision. © [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)] -## Sample Code +## Move From Element -The following code example shows how to accept the entire revisions in a -word processing document. To run the program, you can pass in the file path -and the author name: +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification +introduces the Move From element (`moveFrom`). + +### moveFrom (Move Source Paragraph) + +This element indicates that the parent paragraph has been relocated +from this position and marked as a revision. This does not affect the revision +status of the paragraph's content and pertains solely to the paragraph's +existence as a distinct entity. + +Consider a WordprocessingML document where a paragraph of text is moved down +within the document. This relocated paragraph would be represented using the +following WordprocessingML markup: + +```xml + + + + + + + + … + +``` + +### moveFromRangeStart (Move Source Location Container - Start) + +This element marks the beginning of a region where the move source contents are part of a single named move. +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification +introduces the Move From Range Start element (`moveFromRangeStart`). + +### moveFromRangeEnd (Move Source Location Container - End) + +This element marks the end of a region where the move source contents are part of a single named move. +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification +introduces the Move From Range End element (`moveFromRangeEnd`). + +## The Moved To Element +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification +introduces the MoveTo element (`moveTo`). + +### moveTo (Move Destination Paragraph) +This element specifies that the parent paragraph has been moved to this location and tracked as a revision. +This does not imply anything about the revision state of the contents of the paragraph, and applies only to the existence of the paragraph as its own unique paragraph. -```dotnetcli -dotnet run -- [filePath] [authorName] +Consider a WordprocessingML document in which a paragraph of text is moved down in the document. +This moved paragraph would be represented using the following WordprocessingML markup: + +```xml + + + + + + + + … + ``` -After you have run the program, open the word processing file to make +### moveToRangeStart (Move Destination Location Container - Start) + +This element specifies the start of the region whose move destination contents are part of a single named move. +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification +introduces the Move To Range Start element (`moveToRangeStart`). + +### moveToRangeEnd (Move Destination Location Container - End) + +This element specifies the end of a region whose move destination contents are part of a single named move. +The following information from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification +introduces the Move To Range End element (`moveToRangeEnd`). + +## Sample Code + +The following code example shows how to accept the entire revisions in a +word processing document. + +After you have run the program, open the word processing document to make sure that all revision marks have been accepted. ### [C#](#tab/cs) diff --git a/docs/word/how-to-add-tables-to-word-processing-documents.md b/docs/word/how-to-add-tables-to-word-processing-documents.md index e242dcc2..7181cb65 100644 --- a/docs/word/how-to-add-tables-to-word-processing-documents.md +++ b/docs/word/how-to-add-tables-to-word-processing-documents.md @@ -10,19 +10,19 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 09/12/2024 ms.localizationpriority: high --- # Add tables to word processing documents -This topic shows how to use the classes in the Open XML SDK for Office to programmatically add a table to a word processing document. It contains an example **AddTable** method to illustrate this task. +This topic shows how to use the classes in the Open XML SDK for Office to programmatically add a table to a word processing document. It contains an example `AddTable` method to illustrate this task. ## AddTable method -You can use the **AddTable** method to add a simple table to a word processing document. The **AddTable** method accepts two parameters, indicating the following: +You can use the `AddTable` method to add a simple table to a word processing document. The `AddTable` method accepts two parameters, indicating the following: - The name of the document to modify (string). @@ -30,245 +30,74 @@ You can use the **AddTable** method to add a simple table to a word processing d table. ### [C#](#tab/cs-0) -```csharp - public static void AddTable(string fileName, string[,] data) -``` - +[!code-csharp[](../../samples/word/add_tables/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Sub AddTable(ByVal fileName As String, - ByVal data(,) As String) -``` +[!code-vb[](../../samples/word/add_tables/vb/Program.vb#snippet1)] *** ## Call the AddTable method -The **AddTable** method modifies the document you specify, adding a table that contains the information in the two-dimensional array that you provide. To call the method, pass both of the parameter values, as shown in the following code. +The `AddTable` method modifies the document you specify, adding a table that contains the information in the two-dimensional array that you provide. To call the method, pass both of the parameter values, as shown in the following code. ### [C#](#tab/cs-1) -```csharp - const string fileName = @"C:\Users\Public\Documents\AddTable.docx"; - AddTable(fileName, new string[,] - { { "Texas", "TX" }, - { "California", "CA" }, - { "New York", "NY" }, - { "Massachusetts", "MA" } } - ); -``` - +[!code-csharp[](../../samples/word/add_tables/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Const fileName As String = "C:\Users\Public\Documents\AddTable.docx" - AddTable(fileName, New String(,) { - {"Texas", "TX"}, - {"California", "CA"}, - {"New York", "NY"}, - {"Massachusetts", "MA"}}) -``` +[!code-vb[](../../samples/word/add_tables/vb/Program.vb#snippet2)] *** ## How the code works -The following code starts by opening the document, using the [WordprocessingDocument.Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method and indicating that the document should be open for read/write access (the final **true** parameter value). Next the code retrieves a reference to the root element of the main document part, using the [Document](/dotnet/api/documentformat.openxml.packaging.maindocumentpart.document) property of the [MainDocumentPart](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.maindocumentpart) of the word processing document. +The following code starts by opening the document, using the method and indicating that the document should be open for read/write access (the final `true` parameter value). Next the code retrieves a reference to the root element of the main document part, using the property of the of the word processing document. ### [C#](#tab/cs-2) -```csharp - using (var document = WordprocessingDocument.Open(fileName, true)) - { - var doc = document.MainDocumentPart.Document; - // Code removed here… - } -``` - +[!code-csharp[](../../samples/word/add_tables/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - Using document = WordprocessingDocument.Open(fileName, True) - Dim doc = document.MainDocumentPart.Document - ' Code removed here… - End Using -``` +[!code-vb[](../../samples/word/add_tables/vb/Program.vb#snippet3)] *** ## Create the table object and set its properties -Before you can insert a table into a document, you must create the [Table](/dotnet/api/documentformat.openxml.wordprocessing.table) object and set its properties. To set a table's properties, you create and supply values for a [TableProperties](/dotnet/api/documentformat.openxml.wordprocessing.tableproperties) object. The **TableProperties** class provides many table-oriented properties, like [Shading](/dotnet/api/documentformat.openxml.wordprocessing.tableproperties.shading), [TableBorders](/dotnet/api/documentformat.openxml.wordprocessing.tableproperties.tableborders), [TableCaption](/dotnet/api/documentformat.openxml.wordprocessing.tableproperties.tablecaption), [TableCellSpacing](/dotnet/api/documentformat.openxml.wordprocessing.tableproperties.tablecellspacing), [TableJustification](/dotnet/api/documentformat.openxml.wordprocessing.tableproperties.tablejustification), and more. The sample method includes the following code. +Before you can insert a table into a document, you must create the object and set its properties. To set a table's properties, you create and supply values for a object. The `TableProperties` class provides many table-oriented properties, like , , , , , and more. The sample method includes the following code. ### [C#](#tab/cs-3) -```csharp - Table table = new Table(); - - TableProperties props = new TableProperties( - new TableBorders( - new TopBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new BottomBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new LeftBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new RightBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new InsideHorizontalBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new InsideVerticalBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - })); - - table.AppendChild(props); -``` - +[!code-csharp[](../../samples/word/add_tables/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - Dim table As New Table() - - Dim props As TableProperties = _ - New TableProperties(New TableBorders( _ - New TopBorder With { - .Val = New EnumValue(Of BorderValues)(BorderValues.Single), - .Size = 12}, - New BottomBorder With { - .Val = New EnumValue(Of BorderValues)(BorderValues.Single), - .Size = 12}, - New LeftBorder With { - .Val = New EnumValue(Of BorderValues)(BorderValues.Single), - .Size = 12}, - New RightBorder With { - .Val = New EnumValue(Of BorderValues)(BorderValues.Single), - .Size = 12}, _ - New InsideHorizontalBorder With { - .Val = New EnumValue(Of BorderValues)(BorderValues.Single), - .Size = 12}, _ - New InsideVerticalBorder With { - .Val = New EnumValue(Of BorderValues)(BorderValues.Single), - .Size = 12})) - table.AppendChild(Of TableProperties)(props) -``` +[!code-vb[](../../samples/word/add_tables/vb/Program.vb#snippet4)] *** -The constructor for the **TableProperties** class allows you to specify as many child elements as you like (much like the [XElement](/dotnet/api/system.xml.linq.xelement) constructor). In this case, the code creates [TopBorder](/dotnet/api/documentformat.openxml.wordprocessing.topborder), [BottomBorder](/dotnet/api/documentformat.openxml.wordprocessing.bottomborder), [LeftBorder](/dotnet/api/documentformat.openxml.wordprocessing.leftborder), [RightBorder](/dotnet/api/documentformat.openxml.wordprocessing.rightborder), [InsideHorizontalBorder](/dotnet/api/documentformat.openxml.wordprocessing.insidehorizontalborder), and [InsideVerticalBorder](/dotnet/api/documentformat.openxml.wordprocessing.insideverticalborder) child elements, each describing one of the border elements for the table. For each element, the code sets the **Val** and **Size** properties as part of calling the constructor. Setting the size is simple, but setting the **Val** property requires a bit more effort: this property, for this particular object, represents the border style, and you must set it to an enumerated value. To do that, create an instance of the [EnumValue\](/dotnet/api/documentformat.openxml.enumvalue-1) generic type, passing the specific border type ([Single](/dotnet/api/documentformat.openxml.wordprocessing.bordervalues) as a parameter to the constructor. Once the code has set all the table border value it needs to set, it calls the [AppendChild\](/dotnet/api/documentformat.openxml.openxmlelement.appendchild) method of the table, indicating that the generic type is [TableProperties](/dotnet/api/ ocumentformat.openxml.wordprocessing.tableproperties)—that is, it is appending an instance of the **TableProperties** class, using the variable **props** as the value. +The constructor for the `TableProperties` class allows you to specify as many child elements as you like (much like the constructor). In this case, the code creates , , , , , and child elements, each describing one of the border elements for the table. For each element, the code sets the `Val` and `Size` properties as part of calling the constructor. Setting the size is simple, but setting the `Val` property requires a bit more effort: this property, for this particular object, represents the border style, and you must set it to an enumerated value. To do that, create an instance of the generic type, passing the specific border type () as a parameter to the constructor. Once the code has set all the table border value it needs to set, it calls the method of the table, indicating that the generic type is i.e., it is appending an instance of the `TableProperties` class, using the variable `props` as the value. ## Fill the table with data -Given that table and its properties, now it is time to fill the table with data. The sample procedure iterates first through all the rows of data in the array of strings that you specified, creating a new [TableRow](/dotnet/api/documentformat.openxml.wordprocessing.tablerow) instance for each row of data. The following code leaves out the details of filling in the row with data, but it shows how you create and append the row to the table: - -### [C#](#tab/cs-4) -```csharp - for (var i = 0; i <= data.GetUpperBound(0); i++) - { - var tr = new TableRow(); - // Code removed here… - table.Append(tr); - } -``` - -### [Visual Basic](#tab/vb-4) -```vb - For i = 0 To UBound(data, 1) - Dim tr As New TableRow - ' Code removed here… - table.Append(tr) - Next -``` -*** - - -For each row, the code iterates through all the columns in the array of strings you specified. For each column, the code creates a new [TableCell](/dotnet/api/documentformat.openxml.wordprocessing.tablecell) object, fills it with data, and appends it to the row. The following code leaves out the details of filling each cell with data, but it shows how you create and append the column to the table: - -### [C#](#tab/cs-5) -```csharp - for (var j = 0; j <= data.GetUpperBound(1); j++) - { - var tc = new TableCell(); - // Code removed here… - tr.Append(tc); - } -``` - -### [Visual Basic](#tab/vb-5) -```vb - For j = 0 To UBound(data, 2) - Dim tc As New TableCell - ' Code removed here… - tr.Append(tc) - Next -``` -*** - +Given that table and its properties, now it is time to fill the table with data. The sample procedure iterates first through all the rows of data in the array of strings that you specified, creating a new instance for each row of data. The following code shows how you create and append the row to the table. Then for each column, the code creates a new object, fills it with data, and appends it to the row. Next, the code does the following: -- Creates a new [Text](/dotnet/api/documentformat.openxml.wordprocessing.text) object that contains a value from the array of strings. -- Passes the [Text](/dotnet/api/documentformat.openxml.wordprocessing.text) object to the constructor for a new [Run](/dotnet/api/documentformat.openxml.wordprocessing.run) object. -- Passes the [Run](/dotnet/api/documentformat.openxml.wordprocessing.run) object to the constructor for a new [Paragraph](/dotnet/api/documentformat.openxml.wordprocessing.paragraph) object. -- Passes the [Paragraph](/dotnet/api/documentformat.openxml.wordprocessing.paragraph) object to the [Append](/dotnet/api/documentformat.openxml.openxmlelement.append)method of the cell. +- Creates a new object that contains a value from the array of strings. +- Passes the object to the constructor for a new object. +- Passes the object to the constructor for a new object. +- Passes the object to the method of the cell. -In other words, the following code appends the text to the new **TableCell** object. +The code then appends a new object to the cell. This `TableCellProperties` object, like the `TableProperties` object you already saw, can accept as many objects in its constructor as you care to supply. In this case, the code passes only a new object, with its property set to (so that the table automatically sizes the width of each column). -### [C#](#tab/cs-6) -```csharp - tc.Append(new Paragraph(new Run(new Text(data[i, j])))); -``` - -### [Visual Basic](#tab/vb-6) -```vb - tc.Append(New Paragraph(New Run(New Text(data(i, j))))) -``` -*** - - -The code then appends a new [TableCellProperties](/dotnet/api/documentformat.openxml.wordprocessing.tablecellproperties) object to the cell. This **TableCellProperties** object, like the **TableProperties** object you already saw, can accept as many objects in its constructor as you care to supply. In this case, the code passes only a new [TableCellWidth](/dotnet/api/documentformat.openxml.wordprocessing.tablecellwidth) object, with its [Type](/dotnet/api/documentformat.openxml.wordprocessing.tablewidthtype.type) property set to [Auto](/dotnet/api/documentformat.openxml.wordprocessing.tablewidthunitvalues) (so that the table automatically sizes the width of each column). - -### [C#](#tab/cs-7) -```csharp - // Assume you want columns that are automatically sized. - tc.Append(new TableCellProperties( - new TableCellWidth { Type = TableWidthUnitValues.Auto })); -``` - -### [Visual Basic](#tab/vb-7) -```vb - ' Assume you want columns that are automatically sized. - tc.Append(New TableCellProperties( - New TableCellWidth With {.Type = TableWidthUnitValues.Auto})) -``` +### [C#](#tab/cs-4) +[!code-csharp[](../../samples/word/add_tables/cs/Program.cs#snippet5)] +### [Visual Basic](#tab/vb-4) +[!code-vb[](../../samples/word/add_tables/vb/Program.vb#snippet5)] *** - ## Finish up The following code concludes by appending the table to the body of the document, and then saving the document. ### [C#](#tab/cs-8) -```csharp - doc.Body.Append(table); - doc.Save(); -``` - +[!code-csharp[](../../samples/word/add_tables/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-8) -```vb - doc.Body.Append(table) - doc.Save() -``` +[!code-vb[](../../samples/word/add_tables/vb/Program.vb#snippet6)] *** @@ -277,10 +106,10 @@ The following code concludes by appending the table to the body of the document, The following is the complete **AddTable** code sample in C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/word/add_tables/cs/Program.cs)] - +[!code-csharp[](../../samples/word/add_tables/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/word/add_tables/vb/Program.vb)] +[!code-vb[](../../samples/word/add_tables/vb/Program.vb#snippet0)] +*** ## See also diff --git a/docs/word/how-to-apply-a-style-to-a-paragraph-in-a-word-processing-document.md b/docs/word/how-to-apply-a-style-to-a-paragraph-in-a-word-processing-document.md index 94fe5f23..83c7dfb7 100644 --- a/docs/word/how-to-apply-a-style-to-a-paragraph-in-a-word-processing-document.md +++ b/docs/word/how-to-apply-a-style-to-a-paragraph-in-a-word-processing-document.md @@ -10,30 +10,24 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 06/28/2021 +ms.date: 06/27/2024 ms.localizationpriority: high --- # Apply a style to a paragraph in a word processing document -This topic shows how to use the classes in the Open XML SDK for Office to programmatically apply a style to a paragraph within a word processing document. It contains an example **ApplyStyleToParagraph** method to illustrate this task, plus several supplemental example methods to check whether a style exists, add a new style, and add the styles part. +This topic shows how to use the classes in the Open XML SDK for Office to programmatically apply a style to a paragraph within a word processing document. It contains an example `ApplyStyleToParagraph` method to illustrate this task, plus several supplemental example methods to check whether a style exists, add a new style, and add the styles part. ## ApplyStyleToParagraph method -The **ApplyStyleToParagraph** example method can be used to apply a style to a paragraph. You must first obtain a reference to the document as well as a reference to the paragraph that you want to style. The method accepts four parameters that indicate: the reference to the opened word processing document, the styleid of the style to be applied, the name of the style to be applied, and the reference to the paragraph to which to apply the style. +The `ApplyStyleToParagraph` example method can be used to apply a style to a paragraph. You must first obtain a reference to the document as well as a reference to the paragraph that you want to style. The method accepts four parameters that indicate: the path to the word processing document to open, the styleid of the style to be applied, the name of the style to be applied, and the reference to the paragraph to which to apply the style. ### [C#](#tab/cs-0) -```csharp - public static void ApplyStyleToParagraph(WordprocessingDocument doc, string styleid, string stylename, Paragraph p) -``` - +[!code-csharp[](../../samples/word/apply_a_style_to_a_paragraph/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-0) -```vb - Public Sub ApplyStyleToParagraph(ByVal doc As WordprocessingDocument, - ByVal styleid As String, ByVal stylename As String, ByVal p As Paragraph) -``` +[!code-vb[](../../samples/word/apply_a_style_to_a_paragraph/vb/Program.vb#snippet1)] *** @@ -43,24 +37,12 @@ The following sections in this topic explain the implementation of this method a The Sample Code section also shows the code required to set up for calling the sample method. To use the method to apply a style to a paragraph in a document, you first need a reference to the open document. In the Open XML SDK, the class represents a Word document package. To open and work with a Word document, create an instance of the class from the document. After you create the instance, use it to obtain access to the main document part that contains the text of the document. The content in the main document part is represented in the package as XML using WordprocessingML markup. -To create the class instance, call one of the overloads of the [Open()](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) method. The following sample code shows how to use the [WordprocessingDocument.Open](/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument.open) 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 to open the file for editing. In this example the parameter is **true** to enable read/write access to the file. +To create the class instance, call one of the overloads of the method. The following sample code shows how to use the `DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Open(String, Boolean)` 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 to open the file for editing. In this example the parameter is `true` to enable read/write access to the file. ### [C#](#tab/cs-1) -```csharp - using (WordprocessingDocument doc = - WordprocessingDocument.Open(fileName, true)) - { - // Code removed here. - } -``` - +[!code-csharp[](../../samples/word/apply_a_style_to_a_paragraph/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-1) -```vb - Using doc As WordprocessingDocument = _ - WordprocessingDocument.Open(fileName, True) - ' Code removed here. - End Using -``` +[!code-vb[](../../samples/word/apply_a_style_to_a_paragraph/vb/Program.vb#snippet2)] *** @@ -68,43 +50,22 @@ To create the class instance, call one of the overloads of the [Open()](/dotnet/ ## Get the paragraph to style -After opening the file, the sample code retrieves a reference to the first paragraph. Because a typical word processing document body contains many types of elements, the code filters the descendants in the body of the document to those of type **Paragraph**. The [ElementAtOrDefault](/dotnet/api/system.linq.enumerable.elementatordefault) method is then employed to retrieve a reference to the paragraph. Because the elements are indexed starting at zero, you pass a zero to retrieve the reference to the first paragraph, as shown in the following code example. +After opening the file, the sample code retrieves a reference to the first paragraph. Because a typical word processing document body contains many types of elements, the code filters the descendants in the body of the document to those of type `Paragraph`. The method is then employed to retrieve a reference to the paragraph. Because the elements are indexed starting at zero, you pass a zero to retrieve the reference to the first paragraph, as shown in the following code example. ### [C#](#tab/cs-2) -```csharp - // Get the first paragraph. - Paragraph p = - doc.MainDocumentPart.Document.Body.Descendants() - .ElementAtOrDefault(0); - - // Check for a null reference. - if (p == null) - { - // Code removed here… - } -``` - +[!code-csharp[](../../samples/word/apply_a_style_to_a_paragraph/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-2) -```vb - Dim p = doc.MainDocumentPart.Document.Body.Descendants(Of Paragraph)() _ - .ElementAtOrDefault(0) - - ' Check for a null reference. - If p Is Nothing Then - ' Code removed here. - End If -``` +[!code-vb[](../../samples/word/apply_a_style_to_a_paragraph/vb/Program.vb#snippet3)] *** -The reference to the found paragraph is stored in a variable named p. If -a paragraph is not found at the specified index, the -[ElementAtOrDefault](/dotnet/api/system.linq.enumerable.elementatordefault) +The reference to the found paragraph is stored in a variable named paragraph. If +a paragraph is not found at the specified index, the `ElementAtOrDefault` method returns null as the default value. This provides an opportunity to test for null and throw an error with an appropriate error message. Once you have the references to the document and the paragraph, you can -call the **ApplyStyleToParagraph** example +call the `ApplyStyleToParagraph` example method to do the remaining work. To call the method, you pass the reference to the document as the first parameter, the styleid of the style to apply as the second parameter, the name of the style as the @@ -119,17 +80,17 @@ child element of the paragraph and includes a set of properties that allow you to specify the formatting for the paragraph. The following information from the ISO/IEC 29500 specification -introduces the **pPr** (paragraph properties) +introduces the `pPr` (paragraph properties) element used for specifying the formatting of a paragraph. Note that section numbers preceded by § are from the ISO specification. Within the paragraph, all rich formatting at the paragraph level is -stored within the **pPr** element (§17.3.1.25; §17.3.1.26). [Note: Some +stored within the `pPr` element (§17.3.1.25; §17.3.1.26). [Note: Some examples of paragraph properties are alignment, border, hyphenation override, indentation, line spacing, shading, text direction, and widow/orphan control. -Among the properties is the **pStyle** element +Among the properties is the `pStyle` element to specify the style to apply to the paragraph. For example, the following sample markup shows a pStyle element that specifies the "OverdueAmount" style. @@ -143,35 +104,17 @@ following sample markup shows a pStyle element that specifies the ``` -In the Open XML SDK, the **pPr** element is -represented by the [ParagraphProperties](/dotnet/api/documentformat.openxml.wordprocessing.paragraphproperties) class. The code +In the Open XML SDK, the `pPr` element is +represented by the class. The code determines if the element exists, and creates a new instance of the -**ParagraphProperties** class if it does not. -The **pPr** element is a child of the **p** (paragraph) element; consequently, the [PrependChild\(T)](/dotnet/api/documentformat.openxml.openxmlelement.prependchild) method is used to add +`ParagraphProperties` class if it does not. +The `pPr` element is a child of the `p` (paragraph) element; consequently, the method is used to add the instance, as shown in the following code example. ### [C#](#tab/cs-3) -```csharp - // If the paragraph has no ParagraphProperties object, create one. - if (p.Elements().Count() == 0) - { - p.PrependChild(new ParagraphProperties()); - } - - // Get the paragraph properties element of the paragraph. - ParagraphProperties pPr = p.Elements().First(); -``` - +[!code-csharp[](../../samples/word/apply_a_style_to_a_paragraph/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-3) -```vb - ' If the paragraph has no ParagraphProperties object, create one. - If p.Elements(Of ParagraphProperties)().Count() = 0 Then - p.PrependChild(Of ParagraphProperties)(New ParagraphProperties()) - End If - - ' Get the paragraph properties element of the paragraph. - Dim pPr As ParagraphProperties = p.Elements(Of ParagraphProperties)().First() -``` +[!code-vb[](../../samples/word/apply_a_style_to_a_paragraph/vb/Program.vb#snippet4)] *** @@ -190,65 +133,23 @@ following code verifies that the styles part exists, and creates it if it does not. ### [C#](#tab/cs-4) -```csharp - // Get the Styles part for this document. - StyleDefinitionsPart part = - doc.MainDocumentPart.StyleDefinitionsPart; - - // If the Styles part does not exist, add it and then add the style. - if (part == null) - { - part = AddStylesPartToPackage(doc); - // Code removed here... - } -``` - +[!code-csharp[](../../samples/word/apply_a_style_to_a_paragraph/cs/Program.cs#snippet5)] ### [Visual Basic](#tab/vb-4) -```vb - ' Get the Styles part for this document. - Dim part As StyleDefinitionsPart = doc.MainDocumentPart.StyleDefinitionsPart - - ' If the Styles part does not exist, add it and then add the style. - If part Is Nothing Then - part = AddStylesPartToPackage(doc) - ' Code removed here... - End If -``` +[!code-vb[](../../samples/word/apply_a_style_to_a_paragraph/vb/Program.vb#snippet5)] *** -The **AddStylesPartToPackage** example method -does the work of adding the styles part. It creates a part of the **StyleDefinitionsPart** type, adding it as a child -to the main document part. The code then appends the **Styles** root element, which is the parent element -that contains all of the styles. The **Styles** -element is represented by the [Styles](/dotnet/api/documentformat.openxml.wordprocessing.styles) class in the Open XML SDK. Finally, +The `AddStylesPartToPackage` example method +does the work of adding the styles part. It creates a part of the `StyleDefinitionsPart` type, adding it as a child +to the main document part. The code then appends the `Styles` root element, which is the parent element +that contains all of the styles. The `Styles` +element is represented by the class in the Open XML SDK. Finally, the code saves the part. ### [C#](#tab/cs-5) -```csharp - // Add a StylesDefinitionsPart to the document. Returns a reference to it. - public static StyleDefinitionsPart AddStylesPartToPackage(WordprocessingDocument doc) - { - StyleDefinitionsPart part; - part = doc.MainDocumentPart.AddNewPart(); - Styles root = new Styles(); - root.Save(part); - return part; - } -``` - +[!code-csharp[](../../samples/word/apply_a_style_to_a_paragraph/cs/Program.cs#snippet6)] ### [Visual Basic](#tab/vb-5) -```vb - ' Add a StylesDefinitionsPart to the document. Returns a reference to it. - Public Function AddStylesPartToPackage(ByVal doc As WordprocessingDocument) _ - As StyleDefinitionsPart - Dim part As StyleDefinitionsPart - part = doc.MainDocumentPart.AddNewPart(Of StyleDefinitionsPart)() - Dim root As New Styles() - root.Save(part) - Return part - End Function -``` +[!code-vb[](../../samples/word/apply_a_style_to_a_paragraph/vb/Program.vb#snippet6)] *** @@ -261,73 +162,26 @@ Styles are stored in the styles part, therefore if the styles part does not exist, the style itself cannot exist. If the styles part exists, the code verifies a matching style by calling -the **IsStyleIdInDocument** example method and +the `IsStyleIdInDocument` example method and passing the document and the styleid. If no match is found on styleid, -the code then tries to lookup the styleid by calling the **GetStyleIdFromStyleName** example method and +the code then tries to lookup the styleid by calling the `GetStyleIdFromStyleName` example method and passing it the style name. If the style does not exist, either because the styles part did not exist, or because the styles part exists, but the style does not, the -code calls the **AddNewStyle** example method +code calls the `AddNewStyle` example method to add the style. ### [C#](#tab/cs-6) -```csharp - // Get the Styles part for this document. - StyleDefinitionsPart part = - doc.MainDocumentPart.StyleDefinitionsPart; - - // If the Styles part does not exist, add it and then add the style. - if (part == null) - { - part = AddStylesPartToPackage(doc); - AddNewStyle(part, styleid, stylename); - } - else - { - // If the style is not in the document, add it. - if (IsStyleIdInDocument(doc, styleid) != true) - { - // No match on styleid, so let's try style name. - string styleidFromName = GetStyleIdFromStyleName(doc, stylename); - if (styleidFromName == null) - { - AddNewStyle(part, styleid, stylename); - } - else - styleid = styleidFromName; - } - } -``` - +[!code-csharp[](../../samples/word/apply_a_style_to_a_paragraph/cs/Program.cs#snippet7)] ### [Visual Basic](#tab/vb-6) -```vb - ' Get the Styles part for this document. - Dim part As StyleDefinitionsPart = doc.MainDocumentPart.StyleDefinitionsPart - - ' If the Styles part does not exist, add it and then add the style. - If part Is Nothing Then - part = AddStylesPartToPackage(doc) - AddNewStyle(part, styleid, stylename) - Else - ' If the style is not in the document, add it. - If IsStyleIdInDocument(doc, styleid) <> True Then - ' No match on styleid, so let's try style name. - Dim styleidFromName As String = - GetStyleIdFromStyleName(doc, stylename) - If styleidFromName Is Nothing Then - AddNewStyle(part, styleid, stylename) - Else - styleid = styleidFromName - End If - End If - End If -``` +[!code-vb[](../../samples/word/apply_a_style_to_a_paragraph/vb/Program.vb#snippet7)] *** -Within the **IsStyleInDocument** example -method, the work begins with retrieving the **Styles** element through the **Styles** property of the [StyleDefinitionsPart](/dotnet/api/documentformat.openxml.packaging.maindocumentpart.styledefinitionspart) of the main document +Within the `IsStyleInDocument` example +method, the work begins with retrieving the `Styles` element through the `Styles` property of the + of the main document part, and then determining whether any styles exist as children of that element. All style elements are stored as children of the styles element. @@ -336,81 +190,34 @@ If styles do exist, the code looks for a match on the styleid. The styleid is an attribute of the style that is used in many places in the document to refer to the style, and can be thought of as its primary identifier. Typically you use the styleid to identify a style in code. -The -[FirstOrDefault](/dotnet/api/system.linq.enumerable.firstordefault) +The method defaults to null if no match is found, so the code verifies for null to see whether a style was matched, as shown in the following excerpt. ### [C#](#tab/cs-7) -```csharp - // Return true if the style id is in the document, false otherwise. - public static bool IsStyleIdInDocument(WordprocessingDocument doc, - string styleid) - { - // Get access to the Styles element for this document. - Styles s = doc.MainDocumentPart.StyleDefinitionsPart.Styles; - - // Check that there are styles and how many. - int n = s.Elements